PackageManagerService.java revision b8a279ee838c309a64211a3caa5e5e204250163d
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.AppsQueryHelper;
109import android.content.pm.FeatureInfo;
110import android.content.pm.IOnPermissionsChangeListener;
111import android.content.pm.IPackageDataObserver;
112import android.content.pm.IPackageDeleteObserver;
113import android.content.pm.IPackageDeleteObserver2;
114import android.content.pm.IPackageInstallObserver2;
115import android.content.pm.IPackageInstaller;
116import android.content.pm.IPackageManager;
117import android.content.pm.IPackageMoveObserver;
118import android.content.pm.IPackageStatsObserver;
119import android.content.pm.InstrumentationInfo;
120import android.content.pm.IntentFilterVerificationInfo;
121import android.content.pm.KeySet;
122import android.content.pm.ManifestDigest;
123import android.content.pm.PackageCleanItem;
124import android.content.pm.PackageInfo;
125import android.content.pm.PackageInfoLite;
126import android.content.pm.PackageInstaller;
127import android.content.pm.PackageManager;
128import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
129import android.content.pm.PackageManagerInternal;
130import android.content.pm.PackageParser;
131import android.content.pm.PackageParser.ActivityIntentInfo;
132import android.content.pm.PackageParser.PackageLite;
133import android.content.pm.PackageParser.PackageParserException;
134import android.content.pm.PackageStats;
135import android.content.pm.PackageUserState;
136import android.content.pm.ParceledListSlice;
137import android.content.pm.PermissionGroupInfo;
138import android.content.pm.PermissionInfo;
139import android.content.pm.ProviderInfo;
140import android.content.pm.ResolveInfo;
141import android.content.pm.ServiceInfo;
142import android.content.pm.Signature;
143import android.content.pm.UserInfo;
144import android.content.pm.VerificationParams;
145import android.content.pm.VerifierDeviceIdentity;
146import android.content.pm.VerifierInfo;
147import android.content.res.Resources;
148import android.hardware.display.DisplayManager;
149import android.net.Uri;
150import android.os.Debug;
151import android.os.Binder;
152import android.os.Build;
153import android.os.Bundle;
154import android.os.Environment;
155import android.os.Environment.UserEnvironment;
156import android.os.FileUtils;
157import android.os.Handler;
158import android.os.IBinder;
159import android.os.Looper;
160import android.os.Message;
161import android.os.Parcel;
162import android.os.ParcelFileDescriptor;
163import android.os.Process;
164import android.os.RemoteCallbackList;
165import android.os.RemoteException;
166import android.os.ResultReceiver;
167import android.os.SELinux;
168import android.os.ServiceManager;
169import android.os.SystemClock;
170import android.os.SystemProperties;
171import android.os.Trace;
172import android.os.UserHandle;
173import android.os.UserManager;
174import android.os.storage.IMountService;
175import android.os.storage.MountServiceInternal;
176import android.os.storage.StorageEventListener;
177import android.os.storage.StorageManager;
178import android.os.storage.VolumeInfo;
179import android.os.storage.VolumeRecord;
180import android.security.KeyStore;
181import android.security.SystemKeyStore;
182import android.system.ErrnoException;
183import android.system.Os;
184import android.system.StructStat;
185import android.text.TextUtils;
186import android.text.format.DateUtils;
187import android.util.ArrayMap;
188import android.util.ArraySet;
189import android.util.AtomicFile;
190import android.util.DisplayMetrics;
191import android.util.EventLog;
192import android.util.ExceptionUtils;
193import android.util.Log;
194import android.util.LogPrinter;
195import android.util.MathUtils;
196import android.util.PrintStreamPrinter;
197import android.util.Slog;
198import android.util.SparseArray;
199import android.util.SparseBooleanArray;
200import android.util.SparseIntArray;
201import android.util.Xml;
202import android.view.Display;
203
204import dalvik.system.DexFile;
205import dalvik.system.VMRuntime;
206
207import libcore.io.IoUtils;
208import libcore.util.EmptyArray;
209
210import com.android.internal.R;
211import com.android.internal.annotations.GuardedBy;
212import com.android.internal.app.EphemeralResolveInfo;
213import com.android.internal.app.IMediaContainerService;
214import com.android.internal.app.ResolverActivity;
215import com.android.internal.content.NativeLibraryHelper;
216import com.android.internal.content.PackageHelper;
217import com.android.internal.os.IParcelFileDescriptorFactory;
218import com.android.internal.os.SomeArgs;
219import com.android.internal.os.Zygote;
220import com.android.internal.util.ArrayUtils;
221import com.android.internal.util.FastPrintWriter;
222import com.android.internal.util.FastXmlSerializer;
223import com.android.internal.util.IndentingPrintWriter;
224import com.android.internal.util.Preconditions;
225import com.android.server.EventLogTags;
226import com.android.server.FgThread;
227import com.android.server.IntentResolver;
228import com.android.server.LocalServices;
229import com.android.server.ServiceThread;
230import com.android.server.SystemConfig;
231import com.android.server.Watchdog;
232import com.android.server.pm.PermissionsState.PermissionState;
233import com.android.server.pm.Settings.DatabaseVersion;
234import com.android.server.pm.Settings.VersionInfo;
235import com.android.server.storage.DeviceStorageMonitorInternal;
236
237import org.xmlpull.v1.XmlPullParser;
238import org.xmlpull.v1.XmlPullParserException;
239import org.xmlpull.v1.XmlSerializer;
240
241import java.io.BufferedInputStream;
242import java.io.BufferedOutputStream;
243import java.io.BufferedReader;
244import java.io.ByteArrayInputStream;
245import java.io.ByteArrayOutputStream;
246import java.io.File;
247import java.io.FileDescriptor;
248import java.io.FileNotFoundException;
249import java.io.FileOutputStream;
250import java.io.FileReader;
251import java.io.FilenameFilter;
252import java.io.IOException;
253import java.io.InputStream;
254import java.io.PrintWriter;
255import java.nio.charset.StandardCharsets;
256import java.security.MessageDigest;
257import java.security.NoSuchAlgorithmException;
258import java.security.PublicKey;
259import java.security.cert.CertificateEncodingException;
260import java.security.cert.CertificateException;
261import java.text.SimpleDateFormat;
262import java.util.ArrayList;
263import java.util.Arrays;
264import java.util.Collection;
265import java.util.Collections;
266import java.util.Comparator;
267import java.util.Date;
268import java.util.Iterator;
269import java.util.List;
270import java.util.Map;
271import java.util.Objects;
272import java.util.Set;
273import java.util.concurrent.CountDownLatch;
274import java.util.concurrent.TimeUnit;
275import java.util.concurrent.atomic.AtomicBoolean;
276import java.util.concurrent.atomic.AtomicInteger;
277import java.util.concurrent.atomic.AtomicLong;
278
279/**
280 * Keep track of all those .apks everywhere.
281 *
282 * This is very central to the platform's security; please run the unit
283 * tests whenever making modifications here:
284 *
285runtest -c android.content.pm.PackageManagerTests frameworks-core
286 *
287 * {@hide}
288 */
289public class PackageManagerService extends IPackageManager.Stub {
290    static final String TAG = "PackageManager";
291    static final boolean DEBUG_SETTINGS = false;
292    static final boolean DEBUG_PREFERRED = false;
293    static final boolean DEBUG_UPGRADE = false;
294    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
295    private static final boolean DEBUG_BACKUP = false;
296    private static final boolean DEBUG_INSTALL = false;
297    private static final boolean DEBUG_REMOVE = false;
298    private static final boolean DEBUG_BROADCASTS = false;
299    private static final boolean DEBUG_SHOW_INFO = false;
300    private static final boolean DEBUG_PACKAGE_INFO = false;
301    private static final boolean DEBUG_INTENT_MATCHING = false;
302    private static final boolean DEBUG_PACKAGE_SCANNING = false;
303    private static final boolean DEBUG_VERIFY = false;
304    private static final boolean DEBUG_DEXOPT = false;
305    private static final boolean DEBUG_ABI_SELECTION = false;
306    private static final boolean DEBUG_EPHEMERAL = false;
307
308    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
309
310    private static final int RADIO_UID = Process.PHONE_UID;
311    private static final int LOG_UID = Process.LOG_UID;
312    private static final int NFC_UID = Process.NFC_UID;
313    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
314    private static final int SHELL_UID = Process.SHELL_UID;
315
316    // Cap the size of permission trees that 3rd party apps can define
317    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
318
319    // Suffix used during package installation when copying/moving
320    // package apks to install directory.
321    private static final String INSTALL_PACKAGE_SUFFIX = "-";
322
323    static final int SCAN_NO_DEX = 1<<1;
324    static final int SCAN_FORCE_DEX = 1<<2;
325    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
326    static final int SCAN_NEW_INSTALL = 1<<4;
327    static final int SCAN_NO_PATHS = 1<<5;
328    static final int SCAN_UPDATE_TIME = 1<<6;
329    static final int SCAN_DEFER_DEX = 1<<7;
330    static final int SCAN_BOOTING = 1<<8;
331    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
332    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
333    static final int SCAN_REPLACING = 1<<11;
334    static final int SCAN_REQUIRE_KNOWN = 1<<12;
335    static final int SCAN_MOVE = 1<<13;
336    static final int SCAN_INITIAL = 1<<14;
337
338    static final int REMOVE_CHATTY = 1<<16;
339
340    private static final int[] EMPTY_INT_ARRAY = new int[0];
341
342    /**
343     * Timeout (in milliseconds) after which the watchdog should declare that
344     * our handler thread is wedged.  The usual default for such things is one
345     * minute but we sometimes do very lengthy I/O operations on this thread,
346     * such as installing multi-gigabyte applications, so ours needs to be longer.
347     */
348    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
349
350    /**
351     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
352     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
353     * settings entry if available, otherwise we use the hardcoded default.  If it's been
354     * more than this long since the last fstrim, we force one during the boot sequence.
355     *
356     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
357     * one gets run at the next available charging+idle time.  This final mandatory
358     * no-fstrim check kicks in only of the other scheduling criteria is never met.
359     */
360    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
361
362    /**
363     * Whether verification is enabled by default.
364     */
365    private static final boolean DEFAULT_VERIFY_ENABLE = true;
366
367    /**
368     * The default maximum time to wait for the verification agent to return in
369     * milliseconds.
370     */
371    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
372
373    /**
374     * The default response for package verification timeout.
375     *
376     * This can be either PackageManager.VERIFICATION_ALLOW or
377     * PackageManager.VERIFICATION_REJECT.
378     */
379    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
380
381    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
382
383    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
384            DEFAULT_CONTAINER_PACKAGE,
385            "com.android.defcontainer.DefaultContainerService");
386
387    private static final String KILL_APP_REASON_GIDS_CHANGED =
388            "permission grant or revoke changed gids";
389
390    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
391            "permissions revoked";
392
393    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
394
395    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
396
397    /** Permission grant: not grant the permission. */
398    private static final int GRANT_DENIED = 1;
399
400    /** Permission grant: grant the permission as an install permission. */
401    private static final int GRANT_INSTALL = 2;
402
403    /** Permission grant: grant the permission as an install permission for a legacy app. */
404    private static final int GRANT_INSTALL_LEGACY = 3;
405
406    /** Permission grant: grant the permission as a runtime one. */
407    private static final int GRANT_RUNTIME = 4;
408
409    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
410    private static final int GRANT_UPGRADE = 5;
411
412    /** Canonical intent used to identify what counts as a "web browser" app */
413    private static final Intent sBrowserIntent;
414    static {
415        sBrowserIntent = new Intent();
416        sBrowserIntent.setAction(Intent.ACTION_VIEW);
417        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
418        sBrowserIntent.setData(Uri.parse("http:"));
419    }
420
421    final ServiceThread mHandlerThread;
422
423    final PackageHandler mHandler;
424
425    /**
426     * Messages for {@link #mHandler} that need to wait for system ready before
427     * being dispatched.
428     */
429    private ArrayList<Message> mPostSystemReadyMessages;
430
431    final int mSdkVersion = Build.VERSION.SDK_INT;
432
433    final Context mContext;
434    final boolean mFactoryTest;
435    final boolean mOnlyCore;
436    final DisplayMetrics mMetrics;
437    final int mDefParseFlags;
438    final String[] mSeparateProcesses;
439    final boolean mIsUpgrade;
440
441    // This is where all application persistent data goes.
442    final File mAppDataDir;
443
444    // This is where all application persistent data goes for secondary users.
445    final File mUserAppDataDir;
446
447    /** The location for ASEC container files on internal storage. */
448    final String mAsecInternalPath;
449
450    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
451    // LOCK HELD.  Can be called with mInstallLock held.
452    @GuardedBy("mInstallLock")
453    final Installer mInstaller;
454
455    /** Directory where installed third-party apps stored */
456    final File mAppInstallDir;
457
458    /**
459     * Directory to which applications installed internally have their
460     * 32 bit native libraries copied.
461     */
462    private File mAppLib32InstallDir;
463
464    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
465    // apps.
466    final File mDrmAppPrivateInstallDir;
467
468    // ----------------------------------------------------------------
469
470    // Lock for state used when installing and doing other long running
471    // operations.  Methods that must be called with this lock held have
472    // the suffix "LI".
473    final Object mInstallLock = new Object();
474
475    // ----------------------------------------------------------------
476
477    // Keys are String (package name), values are Package.  This also serves
478    // as the lock for the global state.  Methods that must be called with
479    // this lock held have the prefix "LP".
480    @GuardedBy("mPackages")
481    final ArrayMap<String, PackageParser.Package> mPackages =
482            new ArrayMap<String, PackageParser.Package>();
483
484    // Tracks available target package names -> overlay package paths.
485    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
486        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
487
488    /**
489     * Tracks new system packages [received in an OTA] that we expect to
490     * find updated user-installed versions. Keys are package name, values
491     * are package location.
492     */
493    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
494
495    /**
496     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
497     */
498    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
499    /**
500     * Whether or not system app permissions should be promoted from install to runtime.
501     */
502    boolean mPromoteSystemApps;
503
504    final Settings mSettings;
505    boolean mRestoredSettings;
506
507    // System configuration read by SystemConfig.
508    final int[] mGlobalGids;
509    final SparseArray<ArraySet<String>> mSystemPermissions;
510    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
511
512    // If mac_permissions.xml was found for seinfo labeling.
513    boolean mFoundPolicyFile;
514
515    // If a recursive restorecon of /data/data/<pkg> is needed.
516    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
517
518    public static final class SharedLibraryEntry {
519        public final String path;
520        public final String apk;
521
522        SharedLibraryEntry(String _path, String _apk) {
523            path = _path;
524            apk = _apk;
525        }
526    }
527
528    // Currently known shared libraries.
529    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
530            new ArrayMap<String, SharedLibraryEntry>();
531
532    // All available activities, for your resolving pleasure.
533    final ActivityIntentResolver mActivities =
534            new ActivityIntentResolver();
535
536    // All available receivers, for your resolving pleasure.
537    final ActivityIntentResolver mReceivers =
538            new ActivityIntentResolver();
539
540    // All available services, for your resolving pleasure.
541    final ServiceIntentResolver mServices = new ServiceIntentResolver();
542
543    // All available providers, for your resolving pleasure.
544    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
545
546    // Mapping from provider base names (first directory in content URI codePath)
547    // to the provider information.
548    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
549            new ArrayMap<String, PackageParser.Provider>();
550
551    // Mapping from instrumentation class names to info about them.
552    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
553            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
554
555    // Mapping from permission names to info about them.
556    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
557            new ArrayMap<String, PackageParser.PermissionGroup>();
558
559    // Packages whose data we have transfered into another package, thus
560    // should no longer exist.
561    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
562
563    // Broadcast actions that are only available to the system.
564    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
565
566    /** List of packages waiting for verification. */
567    final SparseArray<PackageVerificationState> mPendingVerification
568            = new SparseArray<PackageVerificationState>();
569
570    /** Set of packages associated with each app op permission. */
571    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
572
573    final PackageInstallerService mInstallerService;
574
575    private final PackageDexOptimizer mPackageDexOptimizer;
576
577    private AtomicInteger mNextMoveId = new AtomicInteger();
578    private final MoveCallbacks mMoveCallbacks;
579
580    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
581
582    // Cache of users who need badging.
583    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
584
585    /** Token for keys in mPendingVerification. */
586    private int mPendingVerificationToken = 0;
587
588    volatile boolean mSystemReady;
589    volatile boolean mSafeMode;
590    volatile boolean mHasSystemUidErrors;
591
592    ApplicationInfo mAndroidApplication;
593    final ActivityInfo mResolveActivity = new ActivityInfo();
594    final ResolveInfo mResolveInfo = new ResolveInfo();
595    ComponentName mResolveComponentName;
596    PackageParser.Package mPlatformPackage;
597    ComponentName mCustomResolverComponentName;
598
599    boolean mResolverReplaced = false;
600
601    private final ComponentName mIntentFilterVerifierComponent;
602    private int mIntentFilterVerificationToken = 0;
603
604    /** Component that knows whether or not an ephemeral application exists */
605    final ComponentName mEphemeralResolverComponent;
606    /** The service connection to the ephemeral resolver */
607    final EphemeralResolverConnection mEphemeralResolverConnection;
608
609    /** Component used to install ephemeral applications */
610    final ComponentName mEphemeralInstallerComponent;
611    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
612    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
613
614    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
615            = new SparseArray<IntentFilterVerificationState>();
616
617    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
618            new DefaultPermissionGrantPolicy(this);
619
620    private static class IFVerificationParams {
621        PackageParser.Package pkg;
622        boolean replacing;
623        int userId;
624        int verifierUid;
625
626        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
627                int _userId, int _verifierUid) {
628            pkg = _pkg;
629            replacing = _replacing;
630            userId = _userId;
631            replacing = _replacing;
632            verifierUid = _verifierUid;
633        }
634    }
635
636    private interface IntentFilterVerifier<T extends IntentFilter> {
637        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
638                                               T filter, String packageName);
639        void startVerifications(int userId);
640        void receiveVerificationResponse(int verificationId);
641    }
642
643    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
644        private Context mContext;
645        private ComponentName mIntentFilterVerifierComponent;
646        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
647
648        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
649            mContext = context;
650            mIntentFilterVerifierComponent = verifierComponent;
651        }
652
653        private String getDefaultScheme() {
654            return IntentFilter.SCHEME_HTTPS;
655        }
656
657        @Override
658        public void startVerifications(int userId) {
659            // Launch verifications requests
660            int count = mCurrentIntentFilterVerifications.size();
661            for (int n=0; n<count; n++) {
662                int verificationId = mCurrentIntentFilterVerifications.get(n);
663                final IntentFilterVerificationState ivs =
664                        mIntentFilterVerificationStates.get(verificationId);
665
666                String packageName = ivs.getPackageName();
667
668                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
669                final int filterCount = filters.size();
670                ArraySet<String> domainsSet = new ArraySet<>();
671                for (int m=0; m<filterCount; m++) {
672                    PackageParser.ActivityIntentInfo filter = filters.get(m);
673                    domainsSet.addAll(filter.getHostsList());
674                }
675                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
676                synchronized (mPackages) {
677                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
678                            packageName, domainsList) != null) {
679                        scheduleWriteSettingsLocked();
680                    }
681                }
682                sendVerificationRequest(userId, verificationId, ivs);
683            }
684            mCurrentIntentFilterVerifications.clear();
685        }
686
687        private void sendVerificationRequest(int userId, int verificationId,
688                IntentFilterVerificationState ivs) {
689
690            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
691            verificationIntent.putExtra(
692                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
693                    verificationId);
694            verificationIntent.putExtra(
695                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
696                    getDefaultScheme());
697            verificationIntent.putExtra(
698                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
699                    ivs.getHostsString());
700            verificationIntent.putExtra(
701                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
702                    ivs.getPackageName());
703            verificationIntent.setComponent(mIntentFilterVerifierComponent);
704            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
705
706            UserHandle user = new UserHandle(userId);
707            mContext.sendBroadcastAsUser(verificationIntent, user);
708            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
709                    "Sending IntentFilter verification broadcast");
710        }
711
712        public void receiveVerificationResponse(int verificationId) {
713            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
714
715            final boolean verified = ivs.isVerified();
716
717            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
718            final int count = filters.size();
719            if (DEBUG_DOMAIN_VERIFICATION) {
720                Slog.i(TAG, "Received verification response " + verificationId
721                        + " for " + count + " filters, verified=" + verified);
722            }
723            for (int n=0; n<count; n++) {
724                PackageParser.ActivityIntentInfo filter = filters.get(n);
725                filter.setVerified(verified);
726
727                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
728                        + " verified with result:" + verified + " and hosts:"
729                        + ivs.getHostsString());
730            }
731
732            mIntentFilterVerificationStates.remove(verificationId);
733
734            final String packageName = ivs.getPackageName();
735            IntentFilterVerificationInfo ivi = null;
736
737            synchronized (mPackages) {
738                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
739            }
740            if (ivi == null) {
741                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
742                        + verificationId + " packageName:" + packageName);
743                return;
744            }
745            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
746                    "Updating IntentFilterVerificationInfo for package " + packageName
747                            +" verificationId:" + verificationId);
748
749            synchronized (mPackages) {
750                if (verified) {
751                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
752                } else {
753                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
754                }
755                scheduleWriteSettingsLocked();
756
757                final int userId = ivs.getUserId();
758                if (userId != UserHandle.USER_ALL) {
759                    final int userStatus =
760                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
761
762                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
763                    boolean needUpdate = false;
764
765                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
766                    // already been set by the User thru the Disambiguation dialog
767                    switch (userStatus) {
768                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
769                            if (verified) {
770                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
771                            } else {
772                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
773                            }
774                            needUpdate = true;
775                            break;
776
777                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
778                            if (verified) {
779                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
780                                needUpdate = true;
781                            }
782                            break;
783
784                        default:
785                            // Nothing to do
786                    }
787
788                    if (needUpdate) {
789                        mSettings.updateIntentFilterVerificationStatusLPw(
790                                packageName, updatedStatus, userId);
791                        scheduleWritePackageRestrictionsLocked(userId);
792                    }
793                }
794            }
795        }
796
797        @Override
798        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
799                    ActivityIntentInfo filter, String packageName) {
800            if (!hasValidDomains(filter)) {
801                return false;
802            }
803            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
804            if (ivs == null) {
805                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
806                        packageName);
807            }
808            if (DEBUG_DOMAIN_VERIFICATION) {
809                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
810            }
811            ivs.addFilter(filter);
812            return true;
813        }
814
815        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
816                int userId, int verificationId, String packageName) {
817            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
818                    verifierUid, userId, packageName);
819            ivs.setPendingState();
820            synchronized (mPackages) {
821                mIntentFilterVerificationStates.append(verificationId, ivs);
822                mCurrentIntentFilterVerifications.add(verificationId);
823            }
824            return ivs;
825        }
826    }
827
828    private static boolean hasValidDomains(ActivityIntentInfo filter) {
829        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
830                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
831                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
832    }
833
834    private IntentFilterVerifier mIntentFilterVerifier;
835
836    // Set of pending broadcasts for aggregating enable/disable of components.
837    static class PendingPackageBroadcasts {
838        // for each user id, a map of <package name -> components within that package>
839        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
840
841        public PendingPackageBroadcasts() {
842            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
843        }
844
845        public ArrayList<String> get(int userId, String packageName) {
846            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
847            return packages.get(packageName);
848        }
849
850        public void put(int userId, String packageName, ArrayList<String> components) {
851            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
852            packages.put(packageName, components);
853        }
854
855        public void remove(int userId, String packageName) {
856            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
857            if (packages != null) {
858                packages.remove(packageName);
859            }
860        }
861
862        public void remove(int userId) {
863            mUidMap.remove(userId);
864        }
865
866        public int userIdCount() {
867            return mUidMap.size();
868        }
869
870        public int userIdAt(int n) {
871            return mUidMap.keyAt(n);
872        }
873
874        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
875            return mUidMap.get(userId);
876        }
877
878        public int size() {
879            // total number of pending broadcast entries across all userIds
880            int num = 0;
881            for (int i = 0; i< mUidMap.size(); i++) {
882                num += mUidMap.valueAt(i).size();
883            }
884            return num;
885        }
886
887        public void clear() {
888            mUidMap.clear();
889        }
890
891        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
892            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
893            if (map == null) {
894                map = new ArrayMap<String, ArrayList<String>>();
895                mUidMap.put(userId, map);
896            }
897            return map;
898        }
899    }
900    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
901
902    // Service Connection to remote media container service to copy
903    // package uri's from external media onto secure containers
904    // or internal storage.
905    private IMediaContainerService mContainerService = null;
906
907    static final int SEND_PENDING_BROADCAST = 1;
908    static final int MCS_BOUND = 3;
909    static final int END_COPY = 4;
910    static final int INIT_COPY = 5;
911    static final int MCS_UNBIND = 6;
912    static final int START_CLEANING_PACKAGE = 7;
913    static final int FIND_INSTALL_LOC = 8;
914    static final int POST_INSTALL = 9;
915    static final int MCS_RECONNECT = 10;
916    static final int MCS_GIVE_UP = 11;
917    static final int UPDATED_MEDIA_STATUS = 12;
918    static final int WRITE_SETTINGS = 13;
919    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
920    static final int PACKAGE_VERIFIED = 15;
921    static final int CHECK_PENDING_VERIFICATION = 16;
922    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
923    static final int INTENT_FILTER_VERIFIED = 18;
924
925    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
926
927    // Delay time in millisecs
928    static final int BROADCAST_DELAY = 10 * 1000;
929
930    static UserManagerService sUserManager;
931
932    // Stores a list of users whose package restrictions file needs to be updated
933    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
934
935    final private DefaultContainerConnection mDefContainerConn =
936            new DefaultContainerConnection();
937    class DefaultContainerConnection implements ServiceConnection {
938        public void onServiceConnected(ComponentName name, IBinder service) {
939            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
940            IMediaContainerService imcs =
941                IMediaContainerService.Stub.asInterface(service);
942            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
943        }
944
945        public void onServiceDisconnected(ComponentName name) {
946            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
947        }
948    }
949
950    // Recordkeeping of restore-after-install operations that are currently in flight
951    // between the Package Manager and the Backup Manager
952    class PostInstallData {
953        public InstallArgs args;
954        public PackageInstalledInfo res;
955
956        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
957            args = _a;
958            res = _r;
959        }
960    }
961
962    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
963    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
964
965    // XML tags for backup/restore of various bits of state
966    private static final String TAG_PREFERRED_BACKUP = "pa";
967    private static final String TAG_DEFAULT_APPS = "da";
968    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
969
970    final String mRequiredVerifierPackage;
971    final String mRequiredInstallerPackage;
972
973    private final PackageUsage mPackageUsage = new PackageUsage();
974
975    private class PackageUsage {
976        private static final int WRITE_INTERVAL
977            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
978
979        private final Object mFileLock = new Object();
980        private final AtomicLong mLastWritten = new AtomicLong(0);
981        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
982
983        private boolean mIsHistoricalPackageUsageAvailable = true;
984
985        boolean isHistoricalPackageUsageAvailable() {
986            return mIsHistoricalPackageUsageAvailable;
987        }
988
989        void write(boolean force) {
990            if (force) {
991                writeInternal();
992                return;
993            }
994            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
995                && !DEBUG_DEXOPT) {
996                return;
997            }
998            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
999                new Thread("PackageUsage_DiskWriter") {
1000                    @Override
1001                    public void run() {
1002                        try {
1003                            writeInternal();
1004                        } finally {
1005                            mBackgroundWriteRunning.set(false);
1006                        }
1007                    }
1008                }.start();
1009            }
1010        }
1011
1012        private void writeInternal() {
1013            synchronized (mPackages) {
1014                synchronized (mFileLock) {
1015                    AtomicFile file = getFile();
1016                    FileOutputStream f = null;
1017                    try {
1018                        f = file.startWrite();
1019                        BufferedOutputStream out = new BufferedOutputStream(f);
1020                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1021                        StringBuilder sb = new StringBuilder();
1022                        for (PackageParser.Package pkg : mPackages.values()) {
1023                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1024                                continue;
1025                            }
1026                            sb.setLength(0);
1027                            sb.append(pkg.packageName);
1028                            sb.append(' ');
1029                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1030                            sb.append('\n');
1031                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1032                        }
1033                        out.flush();
1034                        file.finishWrite(f);
1035                    } catch (IOException e) {
1036                        if (f != null) {
1037                            file.failWrite(f);
1038                        }
1039                        Log.e(TAG, "Failed to write package usage times", e);
1040                    }
1041                }
1042            }
1043            mLastWritten.set(SystemClock.elapsedRealtime());
1044        }
1045
1046        void readLP() {
1047            synchronized (mFileLock) {
1048                AtomicFile file = getFile();
1049                BufferedInputStream in = null;
1050                try {
1051                    in = new BufferedInputStream(file.openRead());
1052                    StringBuffer sb = new StringBuffer();
1053                    while (true) {
1054                        String packageName = readToken(in, sb, ' ');
1055                        if (packageName == null) {
1056                            break;
1057                        }
1058                        String timeInMillisString = readToken(in, sb, '\n');
1059                        if (timeInMillisString == null) {
1060                            throw new IOException("Failed to find last usage time for package "
1061                                                  + packageName);
1062                        }
1063                        PackageParser.Package pkg = mPackages.get(packageName);
1064                        if (pkg == null) {
1065                            continue;
1066                        }
1067                        long timeInMillis;
1068                        try {
1069                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1070                        } catch (NumberFormatException e) {
1071                            throw new IOException("Failed to parse " + timeInMillisString
1072                                                  + " as a long.", e);
1073                        }
1074                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1075                    }
1076                } catch (FileNotFoundException expected) {
1077                    mIsHistoricalPackageUsageAvailable = false;
1078                } catch (IOException e) {
1079                    Log.w(TAG, "Failed to read package usage times", e);
1080                } finally {
1081                    IoUtils.closeQuietly(in);
1082                }
1083            }
1084            mLastWritten.set(SystemClock.elapsedRealtime());
1085        }
1086
1087        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1088                throws IOException {
1089            sb.setLength(0);
1090            while (true) {
1091                int ch = in.read();
1092                if (ch == -1) {
1093                    if (sb.length() == 0) {
1094                        return null;
1095                    }
1096                    throw new IOException("Unexpected EOF");
1097                }
1098                if (ch == endOfToken) {
1099                    return sb.toString();
1100                }
1101                sb.append((char)ch);
1102            }
1103        }
1104
1105        private AtomicFile getFile() {
1106            File dataDir = Environment.getDataDirectory();
1107            File systemDir = new File(dataDir, "system");
1108            File fname = new File(systemDir, "package-usage.list");
1109            return new AtomicFile(fname);
1110        }
1111    }
1112
1113    class PackageHandler extends Handler {
1114        private boolean mBound = false;
1115        final ArrayList<HandlerParams> mPendingInstalls =
1116            new ArrayList<HandlerParams>();
1117
1118        private boolean connectToService() {
1119            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1120                    " DefaultContainerService");
1121            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1122            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1123            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1124                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1125                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1126                mBound = true;
1127                return true;
1128            }
1129            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1130            return false;
1131        }
1132
1133        private void disconnectService() {
1134            mContainerService = null;
1135            mBound = false;
1136            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1137            mContext.unbindService(mDefContainerConn);
1138            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1139        }
1140
1141        PackageHandler(Looper looper) {
1142            super(looper);
1143        }
1144
1145        public void handleMessage(Message msg) {
1146            try {
1147                doHandleMessage(msg);
1148            } finally {
1149                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1150            }
1151        }
1152
1153        void doHandleMessage(Message msg) {
1154            switch (msg.what) {
1155                case INIT_COPY: {
1156                    HandlerParams params = (HandlerParams) msg.obj;
1157                    int idx = mPendingInstalls.size();
1158                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1159                    // If a bind was already initiated we dont really
1160                    // need to do anything. The pending install
1161                    // will be processed later on.
1162                    if (!mBound) {
1163                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1164                                System.identityHashCode(mHandler));
1165                        // If this is the only one pending we might
1166                        // have to bind to the service again.
1167                        if (!connectToService()) {
1168                            Slog.e(TAG, "Failed to bind to media container service");
1169                            params.serviceError();
1170                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1171                                    System.identityHashCode(mHandler));
1172                            if (params.traceMethod != null) {
1173                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1174                                        params.traceCookie);
1175                            }
1176                            return;
1177                        } else {
1178                            // Once we bind to the service, the first
1179                            // pending request will be processed.
1180                            mPendingInstalls.add(idx, params);
1181                        }
1182                    } else {
1183                        mPendingInstalls.add(idx, params);
1184                        // Already bound to the service. Just make
1185                        // sure we trigger off processing the first request.
1186                        if (idx == 0) {
1187                            mHandler.sendEmptyMessage(MCS_BOUND);
1188                        }
1189                    }
1190                    break;
1191                }
1192                case MCS_BOUND: {
1193                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1194                    if (msg.obj != null) {
1195                        mContainerService = (IMediaContainerService) msg.obj;
1196                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1197                                System.identityHashCode(mHandler));
1198                    }
1199                    if (mContainerService == null) {
1200                        if (!mBound) {
1201                            // Something seriously wrong since we are not bound and we are not
1202                            // waiting for connection. Bail out.
1203                            Slog.e(TAG, "Cannot bind to media container service");
1204                            for (HandlerParams params : mPendingInstalls) {
1205                                // Indicate service bind error
1206                                params.serviceError();
1207                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1208                                        System.identityHashCode(params));
1209                                if (params.traceMethod != null) {
1210                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1211                                            params.traceMethod, params.traceCookie);
1212                                }
1213                                return;
1214                            }
1215                            mPendingInstalls.clear();
1216                        } else {
1217                            Slog.w(TAG, "Waiting to connect to media container service");
1218                        }
1219                    } else if (mPendingInstalls.size() > 0) {
1220                        HandlerParams params = mPendingInstalls.get(0);
1221                        if (params != null) {
1222                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1223                                    System.identityHashCode(params));
1224                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1225                            if (params.startCopy()) {
1226                                // We are done...  look for more work or to
1227                                // go idle.
1228                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1229                                        "Checking for more work or unbind...");
1230                                // Delete pending install
1231                                if (mPendingInstalls.size() > 0) {
1232                                    mPendingInstalls.remove(0);
1233                                }
1234                                if (mPendingInstalls.size() == 0) {
1235                                    if (mBound) {
1236                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1237                                                "Posting delayed MCS_UNBIND");
1238                                        removeMessages(MCS_UNBIND);
1239                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1240                                        // Unbind after a little delay, to avoid
1241                                        // continual thrashing.
1242                                        sendMessageDelayed(ubmsg, 10000);
1243                                    }
1244                                } else {
1245                                    // There are more pending requests in queue.
1246                                    // Just post MCS_BOUND message to trigger processing
1247                                    // of next pending install.
1248                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1249                                            "Posting MCS_BOUND for next work");
1250                                    mHandler.sendEmptyMessage(MCS_BOUND);
1251                                }
1252                            }
1253                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1254                        }
1255                    } else {
1256                        // Should never happen ideally.
1257                        Slog.w(TAG, "Empty queue");
1258                    }
1259                    break;
1260                }
1261                case MCS_RECONNECT: {
1262                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1263                    if (mPendingInstalls.size() > 0) {
1264                        if (mBound) {
1265                            disconnectService();
1266                        }
1267                        if (!connectToService()) {
1268                            Slog.e(TAG, "Failed to bind to media container service");
1269                            for (HandlerParams params : mPendingInstalls) {
1270                                // Indicate service bind error
1271                                params.serviceError();
1272                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1273                                        System.identityHashCode(params));
1274                            }
1275                            mPendingInstalls.clear();
1276                        }
1277                    }
1278                    break;
1279                }
1280                case MCS_UNBIND: {
1281                    // If there is no actual work left, then time to unbind.
1282                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1283
1284                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1285                        if (mBound) {
1286                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1287
1288                            disconnectService();
1289                        }
1290                    } else if (mPendingInstalls.size() > 0) {
1291                        // There are more pending requests in queue.
1292                        // Just post MCS_BOUND message to trigger processing
1293                        // of next pending install.
1294                        mHandler.sendEmptyMessage(MCS_BOUND);
1295                    }
1296
1297                    break;
1298                }
1299                case MCS_GIVE_UP: {
1300                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1301                    HandlerParams params = mPendingInstalls.remove(0);
1302                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1303                            System.identityHashCode(params));
1304                    break;
1305                }
1306                case SEND_PENDING_BROADCAST: {
1307                    String packages[];
1308                    ArrayList<String> components[];
1309                    int size = 0;
1310                    int uids[];
1311                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1312                    synchronized (mPackages) {
1313                        if (mPendingBroadcasts == null) {
1314                            return;
1315                        }
1316                        size = mPendingBroadcasts.size();
1317                        if (size <= 0) {
1318                            // Nothing to be done. Just return
1319                            return;
1320                        }
1321                        packages = new String[size];
1322                        components = new ArrayList[size];
1323                        uids = new int[size];
1324                        int i = 0;  // filling out the above arrays
1325
1326                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1327                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1328                            Iterator<Map.Entry<String, ArrayList<String>>> it
1329                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1330                                            .entrySet().iterator();
1331                            while (it.hasNext() && i < size) {
1332                                Map.Entry<String, ArrayList<String>> ent = it.next();
1333                                packages[i] = ent.getKey();
1334                                components[i] = ent.getValue();
1335                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1336                                uids[i] = (ps != null)
1337                                        ? UserHandle.getUid(packageUserId, ps.appId)
1338                                        : -1;
1339                                i++;
1340                            }
1341                        }
1342                        size = i;
1343                        mPendingBroadcasts.clear();
1344                    }
1345                    // Send broadcasts
1346                    for (int i = 0; i < size; i++) {
1347                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1348                    }
1349                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1350                    break;
1351                }
1352                case START_CLEANING_PACKAGE: {
1353                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1354                    final String packageName = (String)msg.obj;
1355                    final int userId = msg.arg1;
1356                    final boolean andCode = msg.arg2 != 0;
1357                    synchronized (mPackages) {
1358                        if (userId == UserHandle.USER_ALL) {
1359                            int[] users = sUserManager.getUserIds();
1360                            for (int user : users) {
1361                                mSettings.addPackageToCleanLPw(
1362                                        new PackageCleanItem(user, packageName, andCode));
1363                            }
1364                        } else {
1365                            mSettings.addPackageToCleanLPw(
1366                                    new PackageCleanItem(userId, packageName, andCode));
1367                        }
1368                    }
1369                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1370                    startCleaningPackages();
1371                } break;
1372                case POST_INSTALL: {
1373                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1374                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1375                    mRunningInstalls.delete(msg.arg1);
1376                    boolean deleteOld = false;
1377
1378                    if (data != null) {
1379                        InstallArgs args = data.args;
1380                        PackageInstalledInfo res = data.res;
1381
1382                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1383                            final String packageName = res.pkg.applicationInfo.packageName;
1384                            res.removedInfo.sendBroadcast(false, true, false);
1385                            Bundle extras = new Bundle(1);
1386                            extras.putInt(Intent.EXTRA_UID, res.uid);
1387
1388                            // Now that we successfully installed the package, grant runtime
1389                            // permissions if requested before broadcasting the install.
1390                            if ((args.installFlags
1391                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1392                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1393                                        args.installGrantPermissions);
1394                            }
1395
1396                            // Determine the set of users who are adding this
1397                            // package for the first time vs. those who are seeing
1398                            // an update.
1399                            int[] firstUsers;
1400                            int[] updateUsers = new int[0];
1401                            if (res.origUsers == null || res.origUsers.length == 0) {
1402                                firstUsers = res.newUsers;
1403                            } else {
1404                                firstUsers = new int[0];
1405                                for (int i=0; i<res.newUsers.length; i++) {
1406                                    int user = res.newUsers[i];
1407                                    boolean isNew = true;
1408                                    for (int j=0; j<res.origUsers.length; j++) {
1409                                        if (res.origUsers[j] == user) {
1410                                            isNew = false;
1411                                            break;
1412                                        }
1413                                    }
1414                                    if (isNew) {
1415                                        int[] newFirst = new int[firstUsers.length+1];
1416                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1417                                                firstUsers.length);
1418                                        newFirst[firstUsers.length] = user;
1419                                        firstUsers = newFirst;
1420                                    } else {
1421                                        int[] newUpdate = new int[updateUsers.length+1];
1422                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1423                                                updateUsers.length);
1424                                        newUpdate[updateUsers.length] = user;
1425                                        updateUsers = newUpdate;
1426                                    }
1427                                }
1428                            }
1429                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1430                                    packageName, extras, 0, null, null, firstUsers);
1431                            final boolean update = res.removedInfo.removedPackage != null;
1432                            if (update) {
1433                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1434                            }
1435                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1436                                    packageName, extras, 0, null, null, updateUsers);
1437                            if (update) {
1438                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1439                                        packageName, extras, 0, null, null, updateUsers);
1440                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1441                                        null, null, 0, packageName, null, updateUsers);
1442
1443                                // treat asec-hosted packages like removable media on upgrade
1444                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1445                                    if (DEBUG_INSTALL) {
1446                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1447                                                + " is ASEC-hosted -> AVAILABLE");
1448                                    }
1449                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1450                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1451                                    pkgList.add(packageName);
1452                                    sendResourcesChangedBroadcast(true, true,
1453                                            pkgList,uidArray, null);
1454                                }
1455                            }
1456                            if (res.removedInfo.args != null) {
1457                                // Remove the replaced package's older resources safely now
1458                                deleteOld = true;
1459                            }
1460
1461                            // If this app is a browser and it's newly-installed for some
1462                            // users, clear any default-browser state in those users
1463                            if (firstUsers.length > 0) {
1464                                // the app's nature doesn't depend on the user, so we can just
1465                                // check its browser nature in any user and generalize.
1466                                if (packageIsBrowser(packageName, firstUsers[0])) {
1467                                    synchronized (mPackages) {
1468                                        for (int userId : firstUsers) {
1469                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1470                                        }
1471                                    }
1472                                }
1473                            }
1474                            // Log current value of "unknown sources" setting
1475                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1476                                getUnknownSourcesSettings());
1477                        }
1478                        // Force a gc to clear up things
1479                        Runtime.getRuntime().gc();
1480                        // We delete after a gc for applications  on sdcard.
1481                        if (deleteOld) {
1482                            synchronized (mInstallLock) {
1483                                res.removedInfo.args.doPostDeleteLI(true);
1484                            }
1485                        }
1486                        if (args.observer != null) {
1487                            try {
1488                                Bundle extras = extrasForInstallResult(res);
1489                                args.observer.onPackageInstalled(res.name, res.returnCode,
1490                                        res.returnMsg, extras);
1491                            } catch (RemoteException e) {
1492                                Slog.i(TAG, "Observer no longer exists.");
1493                            }
1494                        }
1495                        if (args.traceMethod != null) {
1496                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1497                                    args.traceCookie);
1498                        }
1499                        return;
1500                    } else {
1501                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1502                    }
1503
1504                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1505                } break;
1506                case UPDATED_MEDIA_STATUS: {
1507                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1508                    boolean reportStatus = msg.arg1 == 1;
1509                    boolean doGc = msg.arg2 == 1;
1510                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1511                    if (doGc) {
1512                        // Force a gc to clear up stale containers.
1513                        Runtime.getRuntime().gc();
1514                    }
1515                    if (msg.obj != null) {
1516                        @SuppressWarnings("unchecked")
1517                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1518                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1519                        // Unload containers
1520                        unloadAllContainers(args);
1521                    }
1522                    if (reportStatus) {
1523                        try {
1524                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1525                            PackageHelper.getMountService().finishMediaUpdate();
1526                        } catch (RemoteException e) {
1527                            Log.e(TAG, "MountService not running?");
1528                        }
1529                    }
1530                } break;
1531                case WRITE_SETTINGS: {
1532                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1533                    synchronized (mPackages) {
1534                        removeMessages(WRITE_SETTINGS);
1535                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1536                        mSettings.writeLPr();
1537                        mDirtyUsers.clear();
1538                    }
1539                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1540                } break;
1541                case WRITE_PACKAGE_RESTRICTIONS: {
1542                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1543                    synchronized (mPackages) {
1544                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1545                        for (int userId : mDirtyUsers) {
1546                            mSettings.writePackageRestrictionsLPr(userId);
1547                        }
1548                        mDirtyUsers.clear();
1549                    }
1550                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1551                } break;
1552                case CHECK_PENDING_VERIFICATION: {
1553                    final int verificationId = msg.arg1;
1554                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1555
1556                    if ((state != null) && !state.timeoutExtended()) {
1557                        final InstallArgs args = state.getInstallArgs();
1558                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1559
1560                        Slog.i(TAG, "Verification timed out for " + originUri);
1561                        mPendingVerification.remove(verificationId);
1562
1563                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1564
1565                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1566                            Slog.i(TAG, "Continuing with installation of " + originUri);
1567                            state.setVerifierResponse(Binder.getCallingUid(),
1568                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1569                            broadcastPackageVerified(verificationId, originUri,
1570                                    PackageManager.VERIFICATION_ALLOW,
1571                                    state.getInstallArgs().getUser());
1572                            try {
1573                                ret = args.copyApk(mContainerService, true);
1574                            } catch (RemoteException e) {
1575                                Slog.e(TAG, "Could not contact the ContainerService");
1576                            }
1577                        } else {
1578                            broadcastPackageVerified(verificationId, originUri,
1579                                    PackageManager.VERIFICATION_REJECT,
1580                                    state.getInstallArgs().getUser());
1581                        }
1582
1583                        Trace.asyncTraceEnd(
1584                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1585
1586                        processPendingInstall(args, ret);
1587                        mHandler.sendEmptyMessage(MCS_UNBIND);
1588                    }
1589                    break;
1590                }
1591                case PACKAGE_VERIFIED: {
1592                    final int verificationId = msg.arg1;
1593
1594                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1595                    if (state == null) {
1596                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1597                        break;
1598                    }
1599
1600                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1601
1602                    state.setVerifierResponse(response.callerUid, response.code);
1603
1604                    if (state.isVerificationComplete()) {
1605                        mPendingVerification.remove(verificationId);
1606
1607                        final InstallArgs args = state.getInstallArgs();
1608                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1609
1610                        int ret;
1611                        if (state.isInstallAllowed()) {
1612                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1613                            broadcastPackageVerified(verificationId, originUri,
1614                                    response.code, state.getInstallArgs().getUser());
1615                            try {
1616                                ret = args.copyApk(mContainerService, true);
1617                            } catch (RemoteException e) {
1618                                Slog.e(TAG, "Could not contact the ContainerService");
1619                            }
1620                        } else {
1621                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1622                        }
1623
1624                        Trace.asyncTraceEnd(
1625                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1626
1627                        processPendingInstall(args, ret);
1628                        mHandler.sendEmptyMessage(MCS_UNBIND);
1629                    }
1630
1631                    break;
1632                }
1633                case START_INTENT_FILTER_VERIFICATIONS: {
1634                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1635                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1636                            params.replacing, params.pkg);
1637                    break;
1638                }
1639                case INTENT_FILTER_VERIFIED: {
1640                    final int verificationId = msg.arg1;
1641
1642                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1643                            verificationId);
1644                    if (state == null) {
1645                        Slog.w(TAG, "Invalid IntentFilter verification token "
1646                                + verificationId + " received");
1647                        break;
1648                    }
1649
1650                    final int userId = state.getUserId();
1651
1652                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1653                            "Processing IntentFilter verification with token:"
1654                            + verificationId + " and userId:" + userId);
1655
1656                    final IntentFilterVerificationResponse response =
1657                            (IntentFilterVerificationResponse) msg.obj;
1658
1659                    state.setVerifierResponse(response.callerUid, response.code);
1660
1661                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1662                            "IntentFilter verification with token:" + verificationId
1663                            + " and userId:" + userId
1664                            + " is settings verifier response with response code:"
1665                            + response.code);
1666
1667                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1668                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1669                                + response.getFailedDomainsString());
1670                    }
1671
1672                    if (state.isVerificationComplete()) {
1673                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1674                    } else {
1675                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1676                                "IntentFilter verification with token:" + verificationId
1677                                + " was not said to be complete");
1678                    }
1679
1680                    break;
1681                }
1682            }
1683        }
1684    }
1685
1686    private StorageEventListener mStorageListener = new StorageEventListener() {
1687        @Override
1688        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1689            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1690                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1691                    final String volumeUuid = vol.getFsUuid();
1692
1693                    // Clean up any users or apps that were removed or recreated
1694                    // while this volume was missing
1695                    reconcileUsers(volumeUuid);
1696                    reconcileApps(volumeUuid);
1697
1698                    // Clean up any install sessions that expired or were
1699                    // cancelled while this volume was missing
1700                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1701
1702                    loadPrivatePackages(vol);
1703
1704                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1705                    unloadPrivatePackages(vol);
1706                }
1707            }
1708
1709            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1710                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1711                    updateExternalMediaStatus(true, false);
1712                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1713                    updateExternalMediaStatus(false, false);
1714                }
1715            }
1716        }
1717
1718        @Override
1719        public void onVolumeForgotten(String fsUuid) {
1720            if (TextUtils.isEmpty(fsUuid)) {
1721                Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1722                return;
1723            }
1724
1725            // Remove any apps installed on the forgotten volume
1726            synchronized (mPackages) {
1727                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1728                for (PackageSetting ps : packages) {
1729                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1730                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1731                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1732                }
1733
1734                mSettings.onVolumeForgotten(fsUuid);
1735                mSettings.writeLPr();
1736            }
1737        }
1738    };
1739
1740    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1741            String[] grantedPermissions) {
1742        if (userId >= UserHandle.USER_SYSTEM) {
1743            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1744        } else if (userId == UserHandle.USER_ALL) {
1745            final int[] userIds;
1746            synchronized (mPackages) {
1747                userIds = UserManagerService.getInstance().getUserIds();
1748            }
1749            for (int someUserId : userIds) {
1750                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1751            }
1752        }
1753
1754        // We could have touched GID membership, so flush out packages.list
1755        synchronized (mPackages) {
1756            mSettings.writePackageListLPr();
1757        }
1758    }
1759
1760    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1761            String[] grantedPermissions) {
1762        SettingBase sb = (SettingBase) pkg.mExtras;
1763        if (sb == null) {
1764            return;
1765        }
1766
1767        PermissionsState permissionsState = sb.getPermissionsState();
1768
1769        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1770                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1771
1772        synchronized (mPackages) {
1773            for (String permission : pkg.requestedPermissions) {
1774                BasePermission bp = mSettings.mPermissions.get(permission);
1775                if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1776                        && (grantedPermissions == null
1777                               || ArrayUtils.contains(grantedPermissions, permission))) {
1778                    final int flags = permissionsState.getPermissionFlags(permission, userId);
1779                    // Installer cannot change immutable permissions.
1780                    if ((flags & immutableFlags) == 0) {
1781                        grantRuntimePermission(pkg.packageName, permission, userId);
1782                    }
1783                }
1784            }
1785        }
1786    }
1787
1788    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1789        Bundle extras = null;
1790        switch (res.returnCode) {
1791            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1792                extras = new Bundle();
1793                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1794                        res.origPermission);
1795                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1796                        res.origPackage);
1797                break;
1798            }
1799            case PackageManager.INSTALL_SUCCEEDED: {
1800                extras = new Bundle();
1801                extras.putBoolean(Intent.EXTRA_REPLACING,
1802                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1803                break;
1804            }
1805        }
1806        return extras;
1807    }
1808
1809    void scheduleWriteSettingsLocked() {
1810        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1811            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1812        }
1813    }
1814
1815    void scheduleWritePackageRestrictionsLocked(int userId) {
1816        if (!sUserManager.exists(userId)) return;
1817        mDirtyUsers.add(userId);
1818        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1819            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1820        }
1821    }
1822
1823    public static PackageManagerService main(Context context, Installer installer,
1824            boolean factoryTest, boolean onlyCore) {
1825        PackageManagerService m = new PackageManagerService(context, installer,
1826                factoryTest, onlyCore);
1827        m.enableSystemUserApps();
1828        ServiceManager.addService("package", m);
1829        return m;
1830    }
1831
1832    private void enableSystemUserApps() {
1833        if (!UserManager.isSplitSystemUser()) {
1834            return;
1835        }
1836        // For system user, enable apps based on the following conditions:
1837        // - app is whitelisted or belong to one of these groups:
1838        //   -- system app which has no launcher icons
1839        //   -- system app which has INTERACT_ACROSS_USERS permission
1840        //   -- system IME app
1841        // - app is not in the blacklist
1842        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1843        Set<String> enableApps = new ArraySet<>();
1844        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
1845                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
1846                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
1847        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
1848        enableApps.addAll(wlApps);
1849        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
1850        enableApps.removeAll(blApps);
1851
1852        List<String> systemApps = queryHelper.queryApps(0, /* systemAppsOnly */ true,
1853                UserHandle.SYSTEM);
1854        final int systemAppsSize = systemApps.size();
1855        synchronized (mPackages) {
1856            for (int i = 0; i < systemAppsSize; i++) {
1857                String pName = systemApps.get(i);
1858                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
1859                // Should not happen, but we shouldn't be failing if it does
1860                if (pkgSetting == null) {
1861                    continue;
1862                }
1863                boolean installed = enableApps.contains(pName);
1864                pkgSetting.setInstalled(installed, UserHandle.USER_SYSTEM);
1865            }
1866        }
1867    }
1868
1869    static String[] splitString(String str, char sep) {
1870        int count = 1;
1871        int i = 0;
1872        while ((i=str.indexOf(sep, i)) >= 0) {
1873            count++;
1874            i++;
1875        }
1876
1877        String[] res = new String[count];
1878        i=0;
1879        count = 0;
1880        int lastI=0;
1881        while ((i=str.indexOf(sep, i)) >= 0) {
1882            res[count] = str.substring(lastI, i);
1883            count++;
1884            i++;
1885            lastI = i;
1886        }
1887        res[count] = str.substring(lastI, str.length());
1888        return res;
1889    }
1890
1891    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1892        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1893                Context.DISPLAY_SERVICE);
1894        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1895    }
1896
1897    public PackageManagerService(Context context, Installer installer,
1898            boolean factoryTest, boolean onlyCore) {
1899        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1900                SystemClock.uptimeMillis());
1901
1902        if (mSdkVersion <= 0) {
1903            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1904        }
1905
1906        mContext = context;
1907        mFactoryTest = factoryTest;
1908        mOnlyCore = onlyCore;
1909        mMetrics = new DisplayMetrics();
1910        mSettings = new Settings(mPackages);
1911        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1912                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1913        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1914                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1915        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1916                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1917        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1918                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1919        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1920                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1921        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1922                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1923
1924        String separateProcesses = SystemProperties.get("debug.separate_processes");
1925        if (separateProcesses != null && separateProcesses.length() > 0) {
1926            if ("*".equals(separateProcesses)) {
1927                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1928                mSeparateProcesses = null;
1929                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1930            } else {
1931                mDefParseFlags = 0;
1932                mSeparateProcesses = separateProcesses.split(",");
1933                Slog.w(TAG, "Running with debug.separate_processes: "
1934                        + separateProcesses);
1935            }
1936        } else {
1937            mDefParseFlags = 0;
1938            mSeparateProcesses = null;
1939        }
1940
1941        mInstaller = installer;
1942        mPackageDexOptimizer = new PackageDexOptimizer(this);
1943        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1944
1945        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1946                FgThread.get().getLooper());
1947
1948        getDefaultDisplayMetrics(context, mMetrics);
1949
1950        SystemConfig systemConfig = SystemConfig.getInstance();
1951        mGlobalGids = systemConfig.getGlobalGids();
1952        mSystemPermissions = systemConfig.getSystemPermissions();
1953        mAvailableFeatures = systemConfig.getAvailableFeatures();
1954
1955        synchronized (mInstallLock) {
1956        // writer
1957        synchronized (mPackages) {
1958            mHandlerThread = new ServiceThread(TAG,
1959                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1960            mHandlerThread.start();
1961            mHandler = new PackageHandler(mHandlerThread.getLooper());
1962            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1963
1964            File dataDir = Environment.getDataDirectory();
1965            mAppDataDir = new File(dataDir, "data");
1966            mAppInstallDir = new File(dataDir, "app");
1967            mAppLib32InstallDir = new File(dataDir, "app-lib");
1968            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1969            mUserAppDataDir = new File(dataDir, "user");
1970            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1971
1972            sUserManager = new UserManagerService(context, this, mPackages);
1973
1974            // Propagate permission configuration in to package manager.
1975            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1976                    = systemConfig.getPermissions();
1977            for (int i=0; i<permConfig.size(); i++) {
1978                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1979                BasePermission bp = mSettings.mPermissions.get(perm.name);
1980                if (bp == null) {
1981                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1982                    mSettings.mPermissions.put(perm.name, bp);
1983                }
1984                if (perm.gids != null) {
1985                    bp.setGids(perm.gids, perm.perUser);
1986                }
1987            }
1988
1989            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1990            for (int i=0; i<libConfig.size(); i++) {
1991                mSharedLibraries.put(libConfig.keyAt(i),
1992                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1993            }
1994
1995            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1996
1997            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
1998
1999            String customResolverActivity = Resources.getSystem().getString(
2000                    R.string.config_customResolverActivity);
2001            if (TextUtils.isEmpty(customResolverActivity)) {
2002                customResolverActivity = null;
2003            } else {
2004                mCustomResolverComponentName = ComponentName.unflattenFromString(
2005                        customResolverActivity);
2006            }
2007
2008            long startTime = SystemClock.uptimeMillis();
2009
2010            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2011                    startTime);
2012
2013            // Set flag to monitor and not change apk file paths when
2014            // scanning install directories.
2015            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2016
2017            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2018            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2019
2020            if (bootClassPath == null) {
2021                Slog.w(TAG, "No BOOTCLASSPATH found!");
2022            }
2023
2024            if (systemServerClassPath == null) {
2025                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2026            }
2027
2028            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2029            final String[] dexCodeInstructionSets =
2030                    getDexCodeInstructionSets(
2031                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2032
2033            /**
2034             * Ensure all external libraries have had dexopt run on them.
2035             */
2036            if (mSharedLibraries.size() > 0) {
2037                // NOTE: For now, we're compiling these system "shared libraries"
2038                // (and framework jars) into all available architectures. It's possible
2039                // to compile them only when we come across an app that uses them (there's
2040                // already logic for that in scanPackageLI) but that adds some complexity.
2041                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2042                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2043                        final String lib = libEntry.path;
2044                        if (lib == null) {
2045                            continue;
2046                        }
2047
2048                        try {
2049                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
2050                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2051                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2052                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/);
2053                            }
2054                        } catch (FileNotFoundException e) {
2055                            Slog.w(TAG, "Library not found: " + lib);
2056                        } catch (IOException e) {
2057                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2058                                    + e.getMessage());
2059                        }
2060                    }
2061                }
2062            }
2063
2064            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2065
2066            final VersionInfo ver = mSettings.getInternalVersion();
2067            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2068            // when upgrading from pre-M, promote system app permissions from install to runtime
2069            mPromoteSystemApps =
2070                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2071
2072            // save off the names of pre-existing system packages prior to scanning; we don't
2073            // want to automatically grant runtime permissions for new system apps
2074            if (mPromoteSystemApps) {
2075                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2076                while (pkgSettingIter.hasNext()) {
2077                    PackageSetting ps = pkgSettingIter.next();
2078                    if (isSystemApp(ps)) {
2079                        mExistingSystemPackages.add(ps.name);
2080                    }
2081                }
2082            }
2083
2084            // Collect vendor overlay packages.
2085            // (Do this before scanning any apps.)
2086            // For security and version matching reason, only consider
2087            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2088            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2089            scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2090                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2091
2092            // Find base frameworks (resource packages without code).
2093            scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2094                    | PackageParser.PARSE_IS_SYSTEM_DIR
2095                    | PackageParser.PARSE_IS_PRIVILEGED,
2096                    scanFlags | SCAN_NO_DEX, 0);
2097
2098            // Collected privileged system packages.
2099            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2100            scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2101                    | PackageParser.PARSE_IS_SYSTEM_DIR
2102                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2103
2104            // Collect ordinary system packages.
2105            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2106            scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2107                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2108
2109            // Collect all vendor packages.
2110            File vendorAppDir = new File("/vendor/app");
2111            try {
2112                vendorAppDir = vendorAppDir.getCanonicalFile();
2113            } catch (IOException e) {
2114                // failed to look up canonical path, continue with original one
2115            }
2116            scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2117                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2118
2119            // Collect all OEM packages.
2120            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2121            scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2122                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2123
2124            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2125            mInstaller.moveFiles();
2126
2127            // Prune any system packages that no longer exist.
2128            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2129            if (!mOnlyCore) {
2130                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2131                while (psit.hasNext()) {
2132                    PackageSetting ps = psit.next();
2133
2134                    /*
2135                     * If this is not a system app, it can't be a
2136                     * disable system app.
2137                     */
2138                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2139                        continue;
2140                    }
2141
2142                    /*
2143                     * If the package is scanned, it's not erased.
2144                     */
2145                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2146                    if (scannedPkg != null) {
2147                        /*
2148                         * If the system app is both scanned and in the
2149                         * disabled packages list, then it must have been
2150                         * added via OTA. Remove it from the currently
2151                         * scanned package so the previously user-installed
2152                         * application can be scanned.
2153                         */
2154                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2155                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2156                                    + ps.name + "; removing system app.  Last known codePath="
2157                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2158                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2159                                    + scannedPkg.mVersionCode);
2160                            removePackageLI(ps, true);
2161                            mExpectingBetter.put(ps.name, ps.codePath);
2162                        }
2163
2164                        continue;
2165                    }
2166
2167                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2168                        psit.remove();
2169                        logCriticalInfo(Log.WARN, "System package " + ps.name
2170                                + " no longer exists; wiping its data");
2171                        removeDataDirsLI(null, ps.name);
2172                    } else {
2173                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2174                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2175                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2176                        }
2177                    }
2178                }
2179            }
2180
2181            //look for any incomplete package installations
2182            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2183            //clean up list
2184            for(int i = 0; i < deletePkgsList.size(); i++) {
2185                //clean up here
2186                cleanupInstallFailedPackage(deletePkgsList.get(i));
2187            }
2188            //delete tmp files
2189            deleteTempPackageFiles();
2190
2191            // Remove any shared userIDs that have no associated packages
2192            mSettings.pruneSharedUsersLPw();
2193
2194            if (!mOnlyCore) {
2195                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2196                        SystemClock.uptimeMillis());
2197                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2198
2199                scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2200                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2201
2202                /**
2203                 * Remove disable package settings for any updated system
2204                 * apps that were removed via an OTA. If they're not a
2205                 * previously-updated app, remove them completely.
2206                 * Otherwise, just revoke their system-level permissions.
2207                 */
2208                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2209                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2210                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2211
2212                    String msg;
2213                    if (deletedPkg == null) {
2214                        msg = "Updated system package " + deletedAppName
2215                                + " no longer exists; wiping its data";
2216                        removeDataDirsLI(null, deletedAppName);
2217                    } else {
2218                        msg = "Updated system app + " + deletedAppName
2219                                + " no longer present; removing system privileges for "
2220                                + deletedAppName;
2221
2222                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2223
2224                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2225                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2226                    }
2227                    logCriticalInfo(Log.WARN, msg);
2228                }
2229
2230                /**
2231                 * Make sure all system apps that we expected to appear on
2232                 * the userdata partition actually showed up. If they never
2233                 * appeared, crawl back and revive the system version.
2234                 */
2235                for (int i = 0; i < mExpectingBetter.size(); i++) {
2236                    final String packageName = mExpectingBetter.keyAt(i);
2237                    if (!mPackages.containsKey(packageName)) {
2238                        final File scanFile = mExpectingBetter.valueAt(i);
2239
2240                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2241                                + " but never showed up; reverting to system");
2242
2243                        final int reparseFlags;
2244                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2245                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2246                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2247                                    | PackageParser.PARSE_IS_PRIVILEGED;
2248                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2249                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2250                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2251                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2252                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2253                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2254                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2255                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2256                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2257                        } else {
2258                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2259                            continue;
2260                        }
2261
2262                        mSettings.enableSystemPackageLPw(packageName);
2263
2264                        try {
2265                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2266                        } catch (PackageManagerException e) {
2267                            Slog.e(TAG, "Failed to parse original system package: "
2268                                    + e.getMessage());
2269                        }
2270                    }
2271                }
2272            }
2273            mExpectingBetter.clear();
2274
2275            // Now that we know all of the shared libraries, update all clients to have
2276            // the correct library paths.
2277            updateAllSharedLibrariesLPw();
2278
2279            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2280                // NOTE: We ignore potential failures here during a system scan (like
2281                // the rest of the commands above) because there's precious little we
2282                // can do about it. A settings error is reported, though.
2283                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2284                        false /* boot complete */);
2285            }
2286
2287            // Now that we know all the packages we are keeping,
2288            // read and update their last usage times.
2289            mPackageUsage.readLP();
2290
2291            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2292                    SystemClock.uptimeMillis());
2293            Slog.i(TAG, "Time to scan packages: "
2294                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2295                    + " seconds");
2296
2297            // If the platform SDK has changed since the last time we booted,
2298            // we need to re-grant app permission to catch any new ones that
2299            // appear.  This is really a hack, and means that apps can in some
2300            // cases get permissions that the user didn't initially explicitly
2301            // allow...  it would be nice to have some better way to handle
2302            // this situation.
2303            int updateFlags = UPDATE_PERMISSIONS_ALL;
2304            if (ver.sdkVersion != mSdkVersion) {
2305                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2306                        + mSdkVersion + "; regranting permissions for internal storage");
2307                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2308            }
2309            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2310            ver.sdkVersion = mSdkVersion;
2311
2312            // If this is the first boot or an update from pre-M, and it is a normal
2313            // boot, then we need to initialize the default preferred apps across
2314            // all defined users.
2315            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2316                for (UserInfo user : sUserManager.getUsers(true)) {
2317                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2318                    applyFactoryDefaultBrowserLPw(user.id);
2319                    primeDomainVerificationsLPw(user.id);
2320                }
2321            }
2322
2323            // If this is first boot after an OTA, and a normal boot, then
2324            // we need to clear code cache directories.
2325            if (mIsUpgrade && !onlyCore) {
2326                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2327                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2328                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2329                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2330                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2331                    }
2332                }
2333                ver.fingerprint = Build.FINGERPRINT;
2334            }
2335
2336            checkDefaultBrowser();
2337
2338            // clear only after permissions and other defaults have been updated
2339            mExistingSystemPackages.clear();
2340            mPromoteSystemApps = false;
2341
2342            // All the changes are done during package scanning.
2343            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2344
2345            // can downgrade to reader
2346            mSettings.writeLPr();
2347
2348            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2349                    SystemClock.uptimeMillis());
2350
2351            mRequiredVerifierPackage = getRequiredVerifierLPr();
2352            mRequiredInstallerPackage = getRequiredInstallerLPr();
2353
2354            mInstallerService = new PackageInstallerService(context, this);
2355
2356            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2357            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2358                    mIntentFilterVerifierComponent);
2359
2360            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2361            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2362            // both the installer and resolver must be present to enable ephemeral
2363            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2364                if (DEBUG_EPHEMERAL) {
2365                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2366                            + " installer:" + ephemeralInstallerComponent);
2367                }
2368                mEphemeralResolverComponent = ephemeralResolverComponent;
2369                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2370                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2371                mEphemeralResolverConnection =
2372                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2373            } else {
2374                if (DEBUG_EPHEMERAL) {
2375                    final String missingComponent =
2376                            (ephemeralResolverComponent == null)
2377                            ? (ephemeralInstallerComponent == null)
2378                                    ? "resolver and installer"
2379                                    : "resolver"
2380                            : "installer";
2381                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2382                }
2383                mEphemeralResolverComponent = null;
2384                mEphemeralInstallerComponent = null;
2385                mEphemeralResolverConnection = null;
2386            }
2387        } // synchronized (mPackages)
2388        } // synchronized (mInstallLock)
2389
2390        // Now after opening every single application zip, make sure they
2391        // are all flushed.  Not really needed, but keeps things nice and
2392        // tidy.
2393        Runtime.getRuntime().gc();
2394
2395        // The initial scanning above does many calls into installd while
2396        // holding the mPackages lock, but we're mostly interested in yelling
2397        // once we have a booted system.
2398        mInstaller.setWarnIfHeld(mPackages);
2399
2400        // Expose private service for system components to use.
2401        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2402    }
2403
2404    @Override
2405    public boolean isFirstBoot() {
2406        return !mRestoredSettings;
2407    }
2408
2409    @Override
2410    public boolean isOnlyCoreApps() {
2411        return mOnlyCore;
2412    }
2413
2414    @Override
2415    public boolean isUpgrade() {
2416        return mIsUpgrade;
2417    }
2418
2419    private String getRequiredVerifierLPr() {
2420        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2421        // We only care about verifier that's installed under system user.
2422        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2423                PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM);
2424
2425        String requiredVerifier = null;
2426
2427        final int N = receivers.size();
2428        for (int i = 0; i < N; i++) {
2429            final ResolveInfo info = receivers.get(i);
2430
2431            if (info.activityInfo == null) {
2432                continue;
2433            }
2434
2435            final String packageName = info.activityInfo.packageName;
2436
2437            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2438                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2439                continue;
2440            }
2441
2442            if (requiredVerifier != null) {
2443                throw new RuntimeException("There can be only one required verifier");
2444            }
2445
2446            requiredVerifier = packageName;
2447        }
2448
2449        return requiredVerifier;
2450    }
2451
2452    private String getRequiredInstallerLPr() {
2453        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2454        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2455        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2456
2457        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2458                PACKAGE_MIME_TYPE, 0, UserHandle.USER_SYSTEM);
2459
2460        String requiredInstaller = null;
2461
2462        final int N = installers.size();
2463        for (int i = 0; i < N; i++) {
2464            final ResolveInfo info = installers.get(i);
2465            final String packageName = info.activityInfo.packageName;
2466
2467            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2468                continue;
2469            }
2470
2471            if (requiredInstaller != null) {
2472                throw new RuntimeException("There must be one required installer");
2473            }
2474
2475            requiredInstaller = packageName;
2476        }
2477
2478        if (requiredInstaller == null) {
2479            throw new RuntimeException("There must be one required installer");
2480        }
2481
2482        return requiredInstaller;
2483    }
2484
2485    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2486        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2487        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2488                PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM);
2489
2490        ComponentName verifierComponentName = null;
2491
2492        int priority = -1000;
2493        final int N = receivers.size();
2494        for (int i = 0; i < N; i++) {
2495            final ResolveInfo info = receivers.get(i);
2496
2497            if (info.activityInfo == null) {
2498                continue;
2499            }
2500
2501            final String packageName = info.activityInfo.packageName;
2502
2503            final PackageSetting ps = mSettings.mPackages.get(packageName);
2504            if (ps == null) {
2505                continue;
2506            }
2507
2508            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2509                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2510                continue;
2511            }
2512
2513            // Select the IntentFilterVerifier with the highest priority
2514            if (priority < info.priority) {
2515                priority = info.priority;
2516                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2517                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2518                        + verifierComponentName + " with priority: " + info.priority);
2519            }
2520        }
2521
2522        return verifierComponentName;
2523    }
2524
2525    private ComponentName getEphemeralResolverLPr() {
2526        final String[] packageArray =
2527                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2528        if (packageArray.length == 0) {
2529            if (DEBUG_EPHEMERAL) {
2530                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2531            }
2532            return null;
2533        }
2534
2535        Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2536        final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent,
2537                null /*resolvedType*/, 0 /*flags*/, UserHandle.USER_SYSTEM);
2538
2539        final int N = resolvers.size();
2540        if (N == 0) {
2541            if (DEBUG_EPHEMERAL) {
2542                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2543            }
2544            return null;
2545        }
2546
2547        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2548        for (int i = 0; i < N; i++) {
2549            final ResolveInfo info = resolvers.get(i);
2550
2551            if (info.serviceInfo == null) {
2552                continue;
2553            }
2554
2555            final String packageName = info.serviceInfo.packageName;
2556            if (!possiblePackages.contains(packageName)) {
2557                if (DEBUG_EPHEMERAL) {
2558                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2559                            + " pkg: " + packageName + ", info:" + info);
2560                }
2561                continue;
2562            }
2563
2564            if (DEBUG_EPHEMERAL) {
2565                Slog.v(TAG, "Ephemeral resolver found;"
2566                        + " pkg: " + packageName + ", info:" + info);
2567            }
2568            return new ComponentName(packageName, info.serviceInfo.name);
2569        }
2570        if (DEBUG_EPHEMERAL) {
2571            Slog.v(TAG, "Ephemeral resolver NOT found");
2572        }
2573        return null;
2574    }
2575
2576    private ComponentName getEphemeralInstallerLPr() {
2577        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2578        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2579        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2580        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2581                PACKAGE_MIME_TYPE, 0 /*flags*/, 0 /*userId*/);
2582
2583        ComponentName ephemeralInstaller = null;
2584
2585        final int N = installers.size();
2586        for (int i = 0; i < N; i++) {
2587            final ResolveInfo info = installers.get(i);
2588            final String packageName = info.activityInfo.packageName;
2589
2590            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2591                if (DEBUG_EPHEMERAL) {
2592                    Slog.d(TAG, "Ephemeral installer is not system app;"
2593                            + " pkg: " + packageName + ", info:" + info);
2594                }
2595                continue;
2596            }
2597
2598            if (ephemeralInstaller != null) {
2599                throw new RuntimeException("There must only be one ephemeral installer");
2600            }
2601
2602            ephemeralInstaller = new ComponentName(packageName, info.activityInfo.name);
2603        }
2604
2605        return ephemeralInstaller;
2606    }
2607
2608    private void primeDomainVerificationsLPw(int userId) {
2609        if (DEBUG_DOMAIN_VERIFICATION) {
2610            Slog.d(TAG, "Priming domain verifications in user " + userId);
2611        }
2612
2613        SystemConfig systemConfig = SystemConfig.getInstance();
2614        ArraySet<String> packages = systemConfig.getLinkedApps();
2615        ArraySet<String> domains = new ArraySet<String>();
2616
2617        for (String packageName : packages) {
2618            PackageParser.Package pkg = mPackages.get(packageName);
2619            if (pkg != null) {
2620                if (!pkg.isSystemApp()) {
2621                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2622                    continue;
2623                }
2624
2625                domains.clear();
2626                for (PackageParser.Activity a : pkg.activities) {
2627                    for (ActivityIntentInfo filter : a.intents) {
2628                        if (hasValidDomains(filter)) {
2629                            domains.addAll(filter.getHostsList());
2630                        }
2631                    }
2632                }
2633
2634                if (domains.size() > 0) {
2635                    if (DEBUG_DOMAIN_VERIFICATION) {
2636                        Slog.v(TAG, "      + " + packageName);
2637                    }
2638                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2639                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2640                    // and then 'always' in the per-user state actually used for intent resolution.
2641                    final IntentFilterVerificationInfo ivi;
2642                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2643                            new ArrayList<String>(domains));
2644                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2645                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2646                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2647                } else {
2648                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2649                            + "' does not handle web links");
2650                }
2651            } else {
2652                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2653            }
2654        }
2655
2656        scheduleWritePackageRestrictionsLocked(userId);
2657        scheduleWriteSettingsLocked();
2658    }
2659
2660    private void applyFactoryDefaultBrowserLPw(int userId) {
2661        // The default browser app's package name is stored in a string resource,
2662        // with a product-specific overlay used for vendor customization.
2663        String browserPkg = mContext.getResources().getString(
2664                com.android.internal.R.string.default_browser);
2665        if (!TextUtils.isEmpty(browserPkg)) {
2666            // non-empty string => required to be a known package
2667            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2668            if (ps == null) {
2669                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2670                browserPkg = null;
2671            } else {
2672                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2673            }
2674        }
2675
2676        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2677        // default.  If there's more than one, just leave everything alone.
2678        if (browserPkg == null) {
2679            calculateDefaultBrowserLPw(userId);
2680        }
2681    }
2682
2683    private void calculateDefaultBrowserLPw(int userId) {
2684        List<String> allBrowsers = resolveAllBrowserApps(userId);
2685        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2686        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2687    }
2688
2689    private List<String> resolveAllBrowserApps(int userId) {
2690        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2691        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2692                PackageManager.MATCH_ALL, userId);
2693
2694        final int count = list.size();
2695        List<String> result = new ArrayList<String>(count);
2696        for (int i=0; i<count; i++) {
2697            ResolveInfo info = list.get(i);
2698            if (info.activityInfo == null
2699                    || !info.handleAllWebDataURI
2700                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2701                    || result.contains(info.activityInfo.packageName)) {
2702                continue;
2703            }
2704            result.add(info.activityInfo.packageName);
2705        }
2706
2707        return result;
2708    }
2709
2710    private boolean packageIsBrowser(String packageName, int userId) {
2711        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2712                PackageManager.MATCH_ALL, userId);
2713        final int N = list.size();
2714        for (int i = 0; i < N; i++) {
2715            ResolveInfo info = list.get(i);
2716            if (packageName.equals(info.activityInfo.packageName)) {
2717                return true;
2718            }
2719        }
2720        return false;
2721    }
2722
2723    private void checkDefaultBrowser() {
2724        final int myUserId = UserHandle.myUserId();
2725        final String packageName = getDefaultBrowserPackageName(myUserId);
2726        if (packageName != null) {
2727            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2728            if (info == null) {
2729                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2730                synchronized (mPackages) {
2731                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2732                }
2733            }
2734        }
2735    }
2736
2737    @Override
2738    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2739            throws RemoteException {
2740        try {
2741            return super.onTransact(code, data, reply, flags);
2742        } catch (RuntimeException e) {
2743            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2744                Slog.wtf(TAG, "Package Manager Crash", e);
2745            }
2746            throw e;
2747        }
2748    }
2749
2750    void cleanupInstallFailedPackage(PackageSetting ps) {
2751        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2752
2753        removeDataDirsLI(ps.volumeUuid, ps.name);
2754        if (ps.codePath != null) {
2755            if (ps.codePath.isDirectory()) {
2756                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2757            } else {
2758                ps.codePath.delete();
2759            }
2760        }
2761        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2762            if (ps.resourcePath.isDirectory()) {
2763                FileUtils.deleteContents(ps.resourcePath);
2764            }
2765            ps.resourcePath.delete();
2766        }
2767        mSettings.removePackageLPw(ps.name);
2768    }
2769
2770    static int[] appendInts(int[] cur, int[] add) {
2771        if (add == null) return cur;
2772        if (cur == null) return add;
2773        final int N = add.length;
2774        for (int i=0; i<N; i++) {
2775            cur = appendInt(cur, add[i]);
2776        }
2777        return cur;
2778    }
2779
2780    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2781        if (!sUserManager.exists(userId)) return null;
2782        final PackageSetting ps = (PackageSetting) p.mExtras;
2783        if (ps == null) {
2784            return null;
2785        }
2786
2787        final PermissionsState permissionsState = ps.getPermissionsState();
2788
2789        final int[] gids = permissionsState.computeGids(userId);
2790        final Set<String> permissions = permissionsState.getPermissions(userId);
2791        final PackageUserState state = ps.readUserState(userId);
2792
2793        return PackageParser.generatePackageInfo(p, gids, flags,
2794                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2795    }
2796
2797    @Override
2798    public boolean isPackageFrozen(String packageName) {
2799        synchronized (mPackages) {
2800            final PackageSetting ps = mSettings.mPackages.get(packageName);
2801            if (ps != null) {
2802                return ps.frozen;
2803            }
2804        }
2805        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2806        return true;
2807    }
2808
2809    @Override
2810    public boolean isPackageAvailable(String packageName, int userId) {
2811        if (!sUserManager.exists(userId)) return false;
2812        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2813        synchronized (mPackages) {
2814            PackageParser.Package p = mPackages.get(packageName);
2815            if (p != null) {
2816                final PackageSetting ps = (PackageSetting) p.mExtras;
2817                if (ps != null) {
2818                    final PackageUserState state = ps.readUserState(userId);
2819                    if (state != null) {
2820                        return PackageParser.isAvailable(state);
2821                    }
2822                }
2823            }
2824        }
2825        return false;
2826    }
2827
2828    @Override
2829    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2830        if (!sUserManager.exists(userId)) return null;
2831        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2832        // reader
2833        synchronized (mPackages) {
2834            PackageParser.Package p = mPackages.get(packageName);
2835            if (DEBUG_PACKAGE_INFO)
2836                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2837            if (p != null) {
2838                return generatePackageInfo(p, flags, userId);
2839            }
2840            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2841                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2842            }
2843        }
2844        return null;
2845    }
2846
2847    @Override
2848    public String[] currentToCanonicalPackageNames(String[] names) {
2849        String[] out = new String[names.length];
2850        // reader
2851        synchronized (mPackages) {
2852            for (int i=names.length-1; i>=0; i--) {
2853                PackageSetting ps = mSettings.mPackages.get(names[i]);
2854                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2855            }
2856        }
2857        return out;
2858    }
2859
2860    @Override
2861    public String[] canonicalToCurrentPackageNames(String[] names) {
2862        String[] out = new String[names.length];
2863        // reader
2864        synchronized (mPackages) {
2865            for (int i=names.length-1; i>=0; i--) {
2866                String cur = mSettings.mRenamedPackages.get(names[i]);
2867                out[i] = cur != null ? cur : names[i];
2868            }
2869        }
2870        return out;
2871    }
2872
2873    @Override
2874    public int getPackageUid(String packageName, int userId) {
2875        return getPackageUidEtc(packageName, 0, userId);
2876    }
2877
2878    @Override
2879    public int getPackageUidEtc(String packageName, int flags, int userId) {
2880        if (!sUserManager.exists(userId)) return -1;
2881        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2882
2883        // reader
2884        synchronized (mPackages) {
2885            final PackageParser.Package p = mPackages.get(packageName);
2886            if (p != null) {
2887                return UserHandle.getUid(userId, p.applicationInfo.uid);
2888            }
2889            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2890                final PackageSetting ps = mSettings.mPackages.get(packageName);
2891                if (ps != null) {
2892                    return UserHandle.getUid(userId, ps.appId);
2893                }
2894            }
2895        }
2896
2897        return -1;
2898    }
2899
2900    @Override
2901    public int[] getPackageGids(String packageName, int userId) {
2902        return getPackageGidsEtc(packageName, 0, userId);
2903    }
2904
2905    @Override
2906    public int[] getPackageGidsEtc(String packageName, int flags, int userId) {
2907        if (!sUserManager.exists(userId)) {
2908            return null;
2909        }
2910
2911        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2912                "getPackageGids");
2913
2914        // reader
2915        synchronized (mPackages) {
2916            final PackageParser.Package p = mPackages.get(packageName);
2917            if (p != null) {
2918                PackageSetting ps = (PackageSetting) p.mExtras;
2919                return ps.getPermissionsState().computeGids(userId);
2920            }
2921            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2922                final PackageSetting ps = mSettings.mPackages.get(packageName);
2923                if (ps != null) {
2924                    return ps.getPermissionsState().computeGids(userId);
2925                }
2926            }
2927        }
2928
2929        return null;
2930    }
2931
2932    static PermissionInfo generatePermissionInfo(
2933            BasePermission bp, int flags) {
2934        if (bp.perm != null) {
2935            return PackageParser.generatePermissionInfo(bp.perm, flags);
2936        }
2937        PermissionInfo pi = new PermissionInfo();
2938        pi.name = bp.name;
2939        pi.packageName = bp.sourcePackage;
2940        pi.nonLocalizedLabel = bp.name;
2941        pi.protectionLevel = bp.protectionLevel;
2942        return pi;
2943    }
2944
2945    @Override
2946    public PermissionInfo getPermissionInfo(String name, int flags) {
2947        // reader
2948        synchronized (mPackages) {
2949            final BasePermission p = mSettings.mPermissions.get(name);
2950            if (p != null) {
2951                return generatePermissionInfo(p, flags);
2952            }
2953            return null;
2954        }
2955    }
2956
2957    @Override
2958    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2959        // reader
2960        synchronized (mPackages) {
2961            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2962            for (BasePermission p : mSettings.mPermissions.values()) {
2963                if (group == null) {
2964                    if (p.perm == null || p.perm.info.group == null) {
2965                        out.add(generatePermissionInfo(p, flags));
2966                    }
2967                } else {
2968                    if (p.perm != null && group.equals(p.perm.info.group)) {
2969                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2970                    }
2971                }
2972            }
2973
2974            if (out.size() > 0) {
2975                return out;
2976            }
2977            return mPermissionGroups.containsKey(group) ? out : null;
2978        }
2979    }
2980
2981    @Override
2982    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2983        // reader
2984        synchronized (mPackages) {
2985            return PackageParser.generatePermissionGroupInfo(
2986                    mPermissionGroups.get(name), flags);
2987        }
2988    }
2989
2990    @Override
2991    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2992        // reader
2993        synchronized (mPackages) {
2994            final int N = mPermissionGroups.size();
2995            ArrayList<PermissionGroupInfo> out
2996                    = new ArrayList<PermissionGroupInfo>(N);
2997            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2998                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2999            }
3000            return out;
3001        }
3002    }
3003
3004    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3005            int userId) {
3006        if (!sUserManager.exists(userId)) return null;
3007        PackageSetting ps = mSettings.mPackages.get(packageName);
3008        if (ps != null) {
3009            if (ps.pkg == null) {
3010                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
3011                        flags, userId);
3012                if (pInfo != null) {
3013                    return pInfo.applicationInfo;
3014                }
3015                return null;
3016            }
3017            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3018                    ps.readUserState(userId), userId);
3019        }
3020        return null;
3021    }
3022
3023    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
3024            int userId) {
3025        if (!sUserManager.exists(userId)) return null;
3026        PackageSetting ps = mSettings.mPackages.get(packageName);
3027        if (ps != null) {
3028            PackageParser.Package pkg = ps.pkg;
3029            if (pkg == null) {
3030                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
3031                    return null;
3032                }
3033                // Only data remains, so we aren't worried about code paths
3034                pkg = new PackageParser.Package(packageName);
3035                pkg.applicationInfo.packageName = packageName;
3036                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
3037                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
3038                pkg.applicationInfo.uid = ps.appId;
3039                pkg.applicationInfo.initForUser(userId);
3040                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
3041                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
3042            }
3043            return generatePackageInfo(pkg, flags, userId);
3044        }
3045        return null;
3046    }
3047
3048    @Override
3049    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3050        if (!sUserManager.exists(userId)) return null;
3051        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
3052        // writer
3053        synchronized (mPackages) {
3054            PackageParser.Package p = mPackages.get(packageName);
3055            if (DEBUG_PACKAGE_INFO) Log.v(
3056                    TAG, "getApplicationInfo " + packageName
3057                    + ": " + p);
3058            if (p != null) {
3059                PackageSetting ps = mSettings.mPackages.get(packageName);
3060                if (ps == null) return null;
3061                // Note: isEnabledLP() does not apply here - always return info
3062                return PackageParser.generateApplicationInfo(
3063                        p, flags, ps.readUserState(userId), userId);
3064            }
3065            if ("android".equals(packageName)||"system".equals(packageName)) {
3066                return mAndroidApplication;
3067            }
3068            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
3069                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3070            }
3071        }
3072        return null;
3073    }
3074
3075    @Override
3076    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3077            final IPackageDataObserver observer) {
3078        mContext.enforceCallingOrSelfPermission(
3079                android.Manifest.permission.CLEAR_APP_CACHE, null);
3080        // Queue up an async operation since clearing cache may take a little while.
3081        mHandler.post(new Runnable() {
3082            public void run() {
3083                mHandler.removeCallbacks(this);
3084                int retCode = -1;
3085                synchronized (mInstallLock) {
3086                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
3087                    if (retCode < 0) {
3088                        Slog.w(TAG, "Couldn't clear application caches");
3089                    }
3090                }
3091                if (observer != null) {
3092                    try {
3093                        observer.onRemoveCompleted(null, (retCode >= 0));
3094                    } catch (RemoteException e) {
3095                        Slog.w(TAG, "RemoveException when invoking call back");
3096                    }
3097                }
3098            }
3099        });
3100    }
3101
3102    @Override
3103    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3104            final IntentSender pi) {
3105        mContext.enforceCallingOrSelfPermission(
3106                android.Manifest.permission.CLEAR_APP_CACHE, null);
3107        // Queue up an async operation since clearing cache may take a little while.
3108        mHandler.post(new Runnable() {
3109            public void run() {
3110                mHandler.removeCallbacks(this);
3111                int retCode = -1;
3112                synchronized (mInstallLock) {
3113                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
3114                    if (retCode < 0) {
3115                        Slog.w(TAG, "Couldn't clear application caches");
3116                    }
3117                }
3118                if(pi != null) {
3119                    try {
3120                        // Callback via pending intent
3121                        int code = (retCode >= 0) ? 1 : 0;
3122                        pi.sendIntent(null, code, null,
3123                                null, null);
3124                    } catch (SendIntentException e1) {
3125                        Slog.i(TAG, "Failed to send pending intent");
3126                    }
3127                }
3128            }
3129        });
3130    }
3131
3132    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3133        synchronized (mInstallLock) {
3134            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
3135                throw new IOException("Failed to free enough space");
3136            }
3137        }
3138    }
3139
3140    /**
3141     * Augment the given flags depending on current user running state. This is
3142     * purposefully done before acquiring {@link #mPackages} lock.
3143     */
3144    private int augmentFlagsForUser(int flags, int userId) {
3145        if (SystemProperties.getBoolean(StorageManager.PROP_HAS_FBE, false)) {
3146            final IMountService mount = IMountService.Stub
3147                    .asInterface(ServiceManager.getService(Context.STORAGE_SERVICE));
3148            if (mount == null) {
3149                // We must be early in boot, so the best we can do is assume the
3150                // user is fully running.
3151                return flags;
3152            }
3153            final long token = Binder.clearCallingIdentity();
3154            try {
3155                if (!mount.isUserKeyUnlocked(userId)) {
3156                    flags |= PackageManager.FLAG_USER_RUNNING_WITH_AMNESIA;
3157                }
3158            } catch (RemoteException e) {
3159                throw e.rethrowAsRuntimeException();
3160            } finally {
3161                Binder.restoreCallingIdentity(token);
3162            }
3163        }
3164        return flags;
3165    }
3166
3167    @Override
3168    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3169        if (!sUserManager.exists(userId)) return null;
3170        flags = augmentFlagsForUser(flags, userId);
3171        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
3172        synchronized (mPackages) {
3173            PackageParser.Activity a = mActivities.mActivities.get(component);
3174
3175            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3176            if (a != null && mSettings.isEnabledAndVisibleLPr(a.info, flags, userId)) {
3177                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3178                if (ps == null) return null;
3179                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3180                        userId);
3181            }
3182            if (mResolveComponentName.equals(component)) {
3183                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3184                        new PackageUserState(), userId);
3185            }
3186        }
3187        return null;
3188    }
3189
3190    @Override
3191    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3192            String resolvedType) {
3193        synchronized (mPackages) {
3194            if (component.equals(mResolveComponentName)) {
3195                // The resolver supports EVERYTHING!
3196                return true;
3197            }
3198            PackageParser.Activity a = mActivities.mActivities.get(component);
3199            if (a == null) {
3200                return false;
3201            }
3202            for (int i=0; i<a.intents.size(); i++) {
3203                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3204                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3205                    return true;
3206                }
3207            }
3208            return false;
3209        }
3210    }
3211
3212    @Override
3213    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3214        if (!sUserManager.exists(userId)) return null;
3215        flags = augmentFlagsForUser(flags, userId);
3216        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3217        synchronized (mPackages) {
3218            PackageParser.Activity a = mReceivers.mActivities.get(component);
3219            if (DEBUG_PACKAGE_INFO) Log.v(
3220                TAG, "getReceiverInfo " + component + ": " + a);
3221            if (a != null && mSettings.isEnabledAndVisibleLPr(a.info, flags, userId)) {
3222                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3223                if (ps == null) return null;
3224                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3225                        userId);
3226            }
3227        }
3228        return null;
3229    }
3230
3231    @Override
3232    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3233        if (!sUserManager.exists(userId)) return null;
3234        flags = augmentFlagsForUser(flags, userId);
3235        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3236        synchronized (mPackages) {
3237            PackageParser.Service s = mServices.mServices.get(component);
3238            if (DEBUG_PACKAGE_INFO) Log.v(
3239                TAG, "getServiceInfo " + component + ": " + s);
3240            if (s != null && mSettings.isEnabledAndVisibleLPr(s.info, flags, userId)) {
3241                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3242                if (ps == null) return null;
3243                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3244                        userId);
3245            }
3246        }
3247        return null;
3248    }
3249
3250    @Override
3251    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3252        if (!sUserManager.exists(userId)) return null;
3253        flags = augmentFlagsForUser(flags, userId);
3254        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3255        synchronized (mPackages) {
3256            PackageParser.Provider p = mProviders.mProviders.get(component);
3257            if (DEBUG_PACKAGE_INFO) Log.v(
3258                TAG, "getProviderInfo " + component + ": " + p);
3259            if (p != null && mSettings.isEnabledAndVisibleLPr(p.info, flags, userId)) {
3260                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3261                if (ps == null) return null;
3262                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3263                        userId);
3264            }
3265        }
3266        return null;
3267    }
3268
3269    @Override
3270    public String[] getSystemSharedLibraryNames() {
3271        Set<String> libSet;
3272        synchronized (mPackages) {
3273            libSet = mSharedLibraries.keySet();
3274            int size = libSet.size();
3275            if (size > 0) {
3276                String[] libs = new String[size];
3277                libSet.toArray(libs);
3278                return libs;
3279            }
3280        }
3281        return null;
3282    }
3283
3284    /**
3285     * @hide
3286     */
3287    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3288        synchronized (mPackages) {
3289            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3290            if (lib != null && lib.apk != null) {
3291                return mPackages.get(lib.apk);
3292            }
3293        }
3294        return null;
3295    }
3296
3297    @Override
3298    public FeatureInfo[] getSystemAvailableFeatures() {
3299        Collection<FeatureInfo> featSet;
3300        synchronized (mPackages) {
3301            featSet = mAvailableFeatures.values();
3302            int size = featSet.size();
3303            if (size > 0) {
3304                FeatureInfo[] features = new FeatureInfo[size+1];
3305                featSet.toArray(features);
3306                FeatureInfo fi = new FeatureInfo();
3307                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3308                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3309                features[size] = fi;
3310                return features;
3311            }
3312        }
3313        return null;
3314    }
3315
3316    @Override
3317    public boolean hasSystemFeature(String name) {
3318        synchronized (mPackages) {
3319            return mAvailableFeatures.containsKey(name);
3320        }
3321    }
3322
3323    private void checkValidCaller(int uid, int userId) {
3324        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3325            return;
3326
3327        throw new SecurityException("Caller uid=" + uid
3328                + " is not privileged to communicate with user=" + userId);
3329    }
3330
3331    @Override
3332    public int checkPermission(String permName, String pkgName, int userId) {
3333        if (!sUserManager.exists(userId)) {
3334            return PackageManager.PERMISSION_DENIED;
3335        }
3336
3337        synchronized (mPackages) {
3338            final PackageParser.Package p = mPackages.get(pkgName);
3339            if (p != null && p.mExtras != null) {
3340                final PackageSetting ps = (PackageSetting) p.mExtras;
3341                final PermissionsState permissionsState = ps.getPermissionsState();
3342                if (permissionsState.hasPermission(permName, userId)) {
3343                    return PackageManager.PERMISSION_GRANTED;
3344                }
3345                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3346                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3347                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3348                    return PackageManager.PERMISSION_GRANTED;
3349                }
3350            }
3351        }
3352
3353        return PackageManager.PERMISSION_DENIED;
3354    }
3355
3356    @Override
3357    public int checkUidPermission(String permName, int uid) {
3358        final int userId = UserHandle.getUserId(uid);
3359
3360        if (!sUserManager.exists(userId)) {
3361            return PackageManager.PERMISSION_DENIED;
3362        }
3363
3364        synchronized (mPackages) {
3365            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3366            if (obj != null) {
3367                final SettingBase ps = (SettingBase) obj;
3368                final PermissionsState permissionsState = ps.getPermissionsState();
3369                if (permissionsState.hasPermission(permName, userId)) {
3370                    return PackageManager.PERMISSION_GRANTED;
3371                }
3372                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3373                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3374                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3375                    return PackageManager.PERMISSION_GRANTED;
3376                }
3377            } else {
3378                ArraySet<String> perms = mSystemPermissions.get(uid);
3379                if (perms != null) {
3380                    if (perms.contains(permName)) {
3381                        return PackageManager.PERMISSION_GRANTED;
3382                    }
3383                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3384                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3385                        return PackageManager.PERMISSION_GRANTED;
3386                    }
3387                }
3388            }
3389        }
3390
3391        return PackageManager.PERMISSION_DENIED;
3392    }
3393
3394    @Override
3395    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3396        if (UserHandle.getCallingUserId() != userId) {
3397            mContext.enforceCallingPermission(
3398                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3399                    "isPermissionRevokedByPolicy for user " + userId);
3400        }
3401
3402        if (checkPermission(permission, packageName, userId)
3403                == PackageManager.PERMISSION_GRANTED) {
3404            return false;
3405        }
3406
3407        final long identity = Binder.clearCallingIdentity();
3408        try {
3409            final int flags = getPermissionFlags(permission, packageName, userId);
3410            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3411        } finally {
3412            Binder.restoreCallingIdentity(identity);
3413        }
3414    }
3415
3416    @Override
3417    public String getPermissionControllerPackageName() {
3418        synchronized (mPackages) {
3419            return mRequiredInstallerPackage;
3420        }
3421    }
3422
3423    /**
3424     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3425     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3426     * @param checkShell TODO(yamasani):
3427     * @param message the message to log on security exception
3428     */
3429    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3430            boolean checkShell, String message) {
3431        if (userId < 0) {
3432            throw new IllegalArgumentException("Invalid userId " + userId);
3433        }
3434        if (checkShell) {
3435            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3436        }
3437        if (userId == UserHandle.getUserId(callingUid)) return;
3438        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3439            if (requireFullPermission) {
3440                mContext.enforceCallingOrSelfPermission(
3441                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3442            } else {
3443                try {
3444                    mContext.enforceCallingOrSelfPermission(
3445                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3446                } catch (SecurityException se) {
3447                    mContext.enforceCallingOrSelfPermission(
3448                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3449                }
3450            }
3451        }
3452    }
3453
3454    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3455        if (callingUid == Process.SHELL_UID) {
3456            if (userHandle >= 0
3457                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3458                throw new SecurityException("Shell does not have permission to access user "
3459                        + userHandle);
3460            } else if (userHandle < 0) {
3461                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3462                        + Debug.getCallers(3));
3463            }
3464        }
3465    }
3466
3467    private BasePermission findPermissionTreeLP(String permName) {
3468        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3469            if (permName.startsWith(bp.name) &&
3470                    permName.length() > bp.name.length() &&
3471                    permName.charAt(bp.name.length()) == '.') {
3472                return bp;
3473            }
3474        }
3475        return null;
3476    }
3477
3478    private BasePermission checkPermissionTreeLP(String permName) {
3479        if (permName != null) {
3480            BasePermission bp = findPermissionTreeLP(permName);
3481            if (bp != null) {
3482                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3483                    return bp;
3484                }
3485                throw new SecurityException("Calling uid "
3486                        + Binder.getCallingUid()
3487                        + " is not allowed to add to permission tree "
3488                        + bp.name + " owned by uid " + bp.uid);
3489            }
3490        }
3491        throw new SecurityException("No permission tree found for " + permName);
3492    }
3493
3494    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3495        if (s1 == null) {
3496            return s2 == null;
3497        }
3498        if (s2 == null) {
3499            return false;
3500        }
3501        if (s1.getClass() != s2.getClass()) {
3502            return false;
3503        }
3504        return s1.equals(s2);
3505    }
3506
3507    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3508        if (pi1.icon != pi2.icon) return false;
3509        if (pi1.logo != pi2.logo) return false;
3510        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3511        if (!compareStrings(pi1.name, pi2.name)) return false;
3512        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3513        // We'll take care of setting this one.
3514        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3515        // These are not currently stored in settings.
3516        //if (!compareStrings(pi1.group, pi2.group)) return false;
3517        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3518        //if (pi1.labelRes != pi2.labelRes) return false;
3519        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3520        return true;
3521    }
3522
3523    int permissionInfoFootprint(PermissionInfo info) {
3524        int size = info.name.length();
3525        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3526        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3527        return size;
3528    }
3529
3530    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3531        int size = 0;
3532        for (BasePermission perm : mSettings.mPermissions.values()) {
3533            if (perm.uid == tree.uid) {
3534                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3535            }
3536        }
3537        return size;
3538    }
3539
3540    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3541        // We calculate the max size of permissions defined by this uid and throw
3542        // if that plus the size of 'info' would exceed our stated maximum.
3543        if (tree.uid != Process.SYSTEM_UID) {
3544            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3545            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3546                throw new SecurityException("Permission tree size cap exceeded");
3547            }
3548        }
3549    }
3550
3551    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3552        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3553            throw new SecurityException("Label must be specified in permission");
3554        }
3555        BasePermission tree = checkPermissionTreeLP(info.name);
3556        BasePermission bp = mSettings.mPermissions.get(info.name);
3557        boolean added = bp == null;
3558        boolean changed = true;
3559        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3560        if (added) {
3561            enforcePermissionCapLocked(info, tree);
3562            bp = new BasePermission(info.name, tree.sourcePackage,
3563                    BasePermission.TYPE_DYNAMIC);
3564        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3565            throw new SecurityException(
3566                    "Not allowed to modify non-dynamic permission "
3567                    + info.name);
3568        } else {
3569            if (bp.protectionLevel == fixedLevel
3570                    && bp.perm.owner.equals(tree.perm.owner)
3571                    && bp.uid == tree.uid
3572                    && comparePermissionInfos(bp.perm.info, info)) {
3573                changed = false;
3574            }
3575        }
3576        bp.protectionLevel = fixedLevel;
3577        info = new PermissionInfo(info);
3578        info.protectionLevel = fixedLevel;
3579        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3580        bp.perm.info.packageName = tree.perm.info.packageName;
3581        bp.uid = tree.uid;
3582        if (added) {
3583            mSettings.mPermissions.put(info.name, bp);
3584        }
3585        if (changed) {
3586            if (!async) {
3587                mSettings.writeLPr();
3588            } else {
3589                scheduleWriteSettingsLocked();
3590            }
3591        }
3592        return added;
3593    }
3594
3595    @Override
3596    public boolean addPermission(PermissionInfo info) {
3597        synchronized (mPackages) {
3598            return addPermissionLocked(info, false);
3599        }
3600    }
3601
3602    @Override
3603    public boolean addPermissionAsync(PermissionInfo info) {
3604        synchronized (mPackages) {
3605            return addPermissionLocked(info, true);
3606        }
3607    }
3608
3609    @Override
3610    public void removePermission(String name) {
3611        synchronized (mPackages) {
3612            checkPermissionTreeLP(name);
3613            BasePermission bp = mSettings.mPermissions.get(name);
3614            if (bp != null) {
3615                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3616                    throw new SecurityException(
3617                            "Not allowed to modify non-dynamic permission "
3618                            + name);
3619                }
3620                mSettings.mPermissions.remove(name);
3621                mSettings.writeLPr();
3622            }
3623        }
3624    }
3625
3626    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3627            BasePermission bp) {
3628        int index = pkg.requestedPermissions.indexOf(bp.name);
3629        if (index == -1) {
3630            throw new SecurityException("Package " + pkg.packageName
3631                    + " has not requested permission " + bp.name);
3632        }
3633        if (!bp.isRuntime() && !bp.isDevelopment()) {
3634            throw new SecurityException("Permission " + bp.name
3635                    + " is not a changeable permission type");
3636        }
3637    }
3638
3639    @Override
3640    public void grantRuntimePermission(String packageName, String name, final int userId) {
3641        if (!sUserManager.exists(userId)) {
3642            Log.e(TAG, "No such user:" + userId);
3643            return;
3644        }
3645
3646        mContext.enforceCallingOrSelfPermission(
3647                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3648                "grantRuntimePermission");
3649
3650        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3651                "grantRuntimePermission");
3652
3653        final int uid;
3654        final SettingBase sb;
3655
3656        synchronized (mPackages) {
3657            final PackageParser.Package pkg = mPackages.get(packageName);
3658            if (pkg == null) {
3659                throw new IllegalArgumentException("Unknown package: " + packageName);
3660            }
3661
3662            final BasePermission bp = mSettings.mPermissions.get(name);
3663            if (bp == null) {
3664                throw new IllegalArgumentException("Unknown permission: " + name);
3665            }
3666
3667            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3668
3669            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3670            sb = (SettingBase) pkg.mExtras;
3671            if (sb == null) {
3672                throw new IllegalArgumentException("Unknown package: " + packageName);
3673            }
3674
3675            final PermissionsState permissionsState = sb.getPermissionsState();
3676
3677            final int flags = permissionsState.getPermissionFlags(name, userId);
3678            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3679                throw new SecurityException("Cannot grant system fixed permission: "
3680                        + name + " for package: " + packageName);
3681            }
3682
3683            if (bp.isDevelopment()) {
3684                // Development permissions must be handled specially, since they are not
3685                // normal runtime permissions.  For now they apply to all users.
3686                if (permissionsState.grantInstallPermission(bp) !=
3687                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3688                    scheduleWriteSettingsLocked();
3689                }
3690                return;
3691            }
3692
3693            final int result = permissionsState.grantRuntimePermission(bp, userId);
3694            switch (result) {
3695                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3696                    return;
3697                }
3698
3699                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3700                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3701                    mHandler.post(new Runnable() {
3702                        @Override
3703                        public void run() {
3704                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3705                        }
3706                    });
3707                }
3708                break;
3709            }
3710
3711            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3712
3713            // Not critical if that is lost - app has to request again.
3714            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3715        }
3716
3717        // Only need to do this if user is initialized. Otherwise it's a new user
3718        // and there are no processes running as the user yet and there's no need
3719        // to make an expensive call to remount processes for the changed permissions.
3720        if (READ_EXTERNAL_STORAGE.equals(name)
3721                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3722            final long token = Binder.clearCallingIdentity();
3723            try {
3724                if (sUserManager.isInitialized(userId)) {
3725                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3726                            MountServiceInternal.class);
3727                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3728                }
3729            } finally {
3730                Binder.restoreCallingIdentity(token);
3731            }
3732        }
3733    }
3734
3735    @Override
3736    public void revokeRuntimePermission(String packageName, String name, int userId) {
3737        if (!sUserManager.exists(userId)) {
3738            Log.e(TAG, "No such user:" + userId);
3739            return;
3740        }
3741
3742        mContext.enforceCallingOrSelfPermission(
3743                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3744                "revokeRuntimePermission");
3745
3746        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3747                "revokeRuntimePermission");
3748
3749        final int appId;
3750
3751        synchronized (mPackages) {
3752            final PackageParser.Package pkg = mPackages.get(packageName);
3753            if (pkg == null) {
3754                throw new IllegalArgumentException("Unknown package: " + packageName);
3755            }
3756
3757            final BasePermission bp = mSettings.mPermissions.get(name);
3758            if (bp == null) {
3759                throw new IllegalArgumentException("Unknown permission: " + name);
3760            }
3761
3762            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3763
3764            SettingBase sb = (SettingBase) pkg.mExtras;
3765            if (sb == null) {
3766                throw new IllegalArgumentException("Unknown package: " + packageName);
3767            }
3768
3769            final PermissionsState permissionsState = sb.getPermissionsState();
3770
3771            final int flags = permissionsState.getPermissionFlags(name, userId);
3772            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3773                throw new SecurityException("Cannot revoke system fixed permission: "
3774                        + name + " for package: " + packageName);
3775            }
3776
3777            if (bp.isDevelopment()) {
3778                // Development permissions must be handled specially, since they are not
3779                // normal runtime permissions.  For now they apply to all users.
3780                if (permissionsState.revokeInstallPermission(bp) !=
3781                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3782                    scheduleWriteSettingsLocked();
3783                }
3784                return;
3785            }
3786
3787            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3788                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3789                return;
3790            }
3791
3792            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3793
3794            // Critical, after this call app should never have the permission.
3795            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3796
3797            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3798        }
3799
3800        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3801    }
3802
3803    @Override
3804    public void resetRuntimePermissions() {
3805        mContext.enforceCallingOrSelfPermission(
3806                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3807                "revokeRuntimePermission");
3808
3809        int callingUid = Binder.getCallingUid();
3810        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3811            mContext.enforceCallingOrSelfPermission(
3812                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3813                    "resetRuntimePermissions");
3814        }
3815
3816        synchronized (mPackages) {
3817            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3818            for (int userId : UserManagerService.getInstance().getUserIds()) {
3819                final int packageCount = mPackages.size();
3820                for (int i = 0; i < packageCount; i++) {
3821                    PackageParser.Package pkg = mPackages.valueAt(i);
3822                    if (!(pkg.mExtras instanceof PackageSetting)) {
3823                        continue;
3824                    }
3825                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3826                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3827                }
3828            }
3829        }
3830    }
3831
3832    @Override
3833    public int getPermissionFlags(String name, String packageName, int userId) {
3834        if (!sUserManager.exists(userId)) {
3835            return 0;
3836        }
3837
3838        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3839
3840        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3841                "getPermissionFlags");
3842
3843        synchronized (mPackages) {
3844            final PackageParser.Package pkg = mPackages.get(packageName);
3845            if (pkg == null) {
3846                throw new IllegalArgumentException("Unknown package: " + packageName);
3847            }
3848
3849            final BasePermission bp = mSettings.mPermissions.get(name);
3850            if (bp == null) {
3851                throw new IllegalArgumentException("Unknown permission: " + name);
3852            }
3853
3854            SettingBase sb = (SettingBase) pkg.mExtras;
3855            if (sb == null) {
3856                throw new IllegalArgumentException("Unknown package: " + packageName);
3857            }
3858
3859            PermissionsState permissionsState = sb.getPermissionsState();
3860            return permissionsState.getPermissionFlags(name, userId);
3861        }
3862    }
3863
3864    @Override
3865    public void updatePermissionFlags(String name, String packageName, int flagMask,
3866            int flagValues, int userId) {
3867        if (!sUserManager.exists(userId)) {
3868            return;
3869        }
3870
3871        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3872
3873        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3874                "updatePermissionFlags");
3875
3876        // Only the system can change these flags and nothing else.
3877        if (getCallingUid() != Process.SYSTEM_UID) {
3878            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3879            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3880            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3881            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3882        }
3883
3884        synchronized (mPackages) {
3885            final PackageParser.Package pkg = mPackages.get(packageName);
3886            if (pkg == null) {
3887                throw new IllegalArgumentException("Unknown package: " + packageName);
3888            }
3889
3890            final BasePermission bp = mSettings.mPermissions.get(name);
3891            if (bp == null) {
3892                throw new IllegalArgumentException("Unknown permission: " + name);
3893            }
3894
3895            SettingBase sb = (SettingBase) pkg.mExtras;
3896            if (sb == null) {
3897                throw new IllegalArgumentException("Unknown package: " + packageName);
3898            }
3899
3900            PermissionsState permissionsState = sb.getPermissionsState();
3901
3902            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3903
3904            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3905                // Install and runtime permissions are stored in different places,
3906                // so figure out what permission changed and persist the change.
3907                if (permissionsState.getInstallPermissionState(name) != null) {
3908                    scheduleWriteSettingsLocked();
3909                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3910                        || hadState) {
3911                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3912                }
3913            }
3914        }
3915    }
3916
3917    /**
3918     * Update the permission flags for all packages and runtime permissions of a user in order
3919     * to allow device or profile owner to remove POLICY_FIXED.
3920     */
3921    @Override
3922    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3923        if (!sUserManager.exists(userId)) {
3924            return;
3925        }
3926
3927        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
3928
3929        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3930                "updatePermissionFlagsForAllApps");
3931
3932        // Only the system can change system fixed flags.
3933        if (getCallingUid() != Process.SYSTEM_UID) {
3934            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3935            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3936        }
3937
3938        synchronized (mPackages) {
3939            boolean changed = false;
3940            final int packageCount = mPackages.size();
3941            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3942                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3943                SettingBase sb = (SettingBase) pkg.mExtras;
3944                if (sb == null) {
3945                    continue;
3946                }
3947                PermissionsState permissionsState = sb.getPermissionsState();
3948                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3949                        userId, flagMask, flagValues);
3950            }
3951            if (changed) {
3952                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3953            }
3954        }
3955    }
3956
3957    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
3958        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
3959                != PackageManager.PERMISSION_GRANTED
3960            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
3961                != PackageManager.PERMISSION_GRANTED) {
3962            throw new SecurityException(message + " requires "
3963                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
3964                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
3965        }
3966    }
3967
3968    @Override
3969    public boolean shouldShowRequestPermissionRationale(String permissionName,
3970            String packageName, int userId) {
3971        if (UserHandle.getCallingUserId() != userId) {
3972            mContext.enforceCallingPermission(
3973                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3974                    "canShowRequestPermissionRationale for user " + userId);
3975        }
3976
3977        final int uid = getPackageUid(packageName, userId);
3978        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3979            return false;
3980        }
3981
3982        if (checkPermission(permissionName, packageName, userId)
3983                == PackageManager.PERMISSION_GRANTED) {
3984            return false;
3985        }
3986
3987        final int flags;
3988
3989        final long identity = Binder.clearCallingIdentity();
3990        try {
3991            flags = getPermissionFlags(permissionName,
3992                    packageName, userId);
3993        } finally {
3994            Binder.restoreCallingIdentity(identity);
3995        }
3996
3997        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3998                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3999                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4000
4001        if ((flags & fixedFlags) != 0) {
4002            return false;
4003        }
4004
4005        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4006    }
4007
4008    @Override
4009    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4010        mContext.enforceCallingOrSelfPermission(
4011                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4012                "addOnPermissionsChangeListener");
4013
4014        synchronized (mPackages) {
4015            mOnPermissionChangeListeners.addListenerLocked(listener);
4016        }
4017    }
4018
4019    @Override
4020    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4021        synchronized (mPackages) {
4022            mOnPermissionChangeListeners.removeListenerLocked(listener);
4023        }
4024    }
4025
4026    @Override
4027    public boolean isProtectedBroadcast(String actionName) {
4028        synchronized (mPackages) {
4029            return mProtectedBroadcasts.contains(actionName);
4030        }
4031    }
4032
4033    @Override
4034    public int checkSignatures(String pkg1, String pkg2) {
4035        synchronized (mPackages) {
4036            final PackageParser.Package p1 = mPackages.get(pkg1);
4037            final PackageParser.Package p2 = mPackages.get(pkg2);
4038            if (p1 == null || p1.mExtras == null
4039                    || p2 == null || p2.mExtras == null) {
4040                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4041            }
4042            return compareSignatures(p1.mSignatures, p2.mSignatures);
4043        }
4044    }
4045
4046    @Override
4047    public int checkUidSignatures(int uid1, int uid2) {
4048        // Map to base uids.
4049        uid1 = UserHandle.getAppId(uid1);
4050        uid2 = UserHandle.getAppId(uid2);
4051        // reader
4052        synchronized (mPackages) {
4053            Signature[] s1;
4054            Signature[] s2;
4055            Object obj = mSettings.getUserIdLPr(uid1);
4056            if (obj != null) {
4057                if (obj instanceof SharedUserSetting) {
4058                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4059                } else if (obj instanceof PackageSetting) {
4060                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4061                } else {
4062                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4063                }
4064            } else {
4065                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4066            }
4067            obj = mSettings.getUserIdLPr(uid2);
4068            if (obj != null) {
4069                if (obj instanceof SharedUserSetting) {
4070                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4071                } else if (obj instanceof PackageSetting) {
4072                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4073                } else {
4074                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4075                }
4076            } else {
4077                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4078            }
4079            return compareSignatures(s1, s2);
4080        }
4081    }
4082
4083    private void killUid(int appId, int userId, String reason) {
4084        final long identity = Binder.clearCallingIdentity();
4085        try {
4086            IActivityManager am = ActivityManagerNative.getDefault();
4087            if (am != null) {
4088                try {
4089                    am.killUid(appId, userId, reason);
4090                } catch (RemoteException e) {
4091                    /* ignore - same process */
4092                }
4093            }
4094        } finally {
4095            Binder.restoreCallingIdentity(identity);
4096        }
4097    }
4098
4099    /**
4100     * Compares two sets of signatures. Returns:
4101     * <br />
4102     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4103     * <br />
4104     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4105     * <br />
4106     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4107     * <br />
4108     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4109     * <br />
4110     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4111     */
4112    static int compareSignatures(Signature[] s1, Signature[] s2) {
4113        if (s1 == null) {
4114            return s2 == null
4115                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4116                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4117        }
4118
4119        if (s2 == null) {
4120            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4121        }
4122
4123        if (s1.length != s2.length) {
4124            return PackageManager.SIGNATURE_NO_MATCH;
4125        }
4126
4127        // Since both signature sets are of size 1, we can compare without HashSets.
4128        if (s1.length == 1) {
4129            return s1[0].equals(s2[0]) ?
4130                    PackageManager.SIGNATURE_MATCH :
4131                    PackageManager.SIGNATURE_NO_MATCH;
4132        }
4133
4134        ArraySet<Signature> set1 = new ArraySet<Signature>();
4135        for (Signature sig : s1) {
4136            set1.add(sig);
4137        }
4138        ArraySet<Signature> set2 = new ArraySet<Signature>();
4139        for (Signature sig : s2) {
4140            set2.add(sig);
4141        }
4142        // Make sure s2 contains all signatures in s1.
4143        if (set1.equals(set2)) {
4144            return PackageManager.SIGNATURE_MATCH;
4145        }
4146        return PackageManager.SIGNATURE_NO_MATCH;
4147    }
4148
4149    /**
4150     * If the database version for this type of package (internal storage or
4151     * external storage) is less than the version where package signatures
4152     * were updated, return true.
4153     */
4154    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4155        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4156        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4157    }
4158
4159    /**
4160     * Used for backward compatibility to make sure any packages with
4161     * certificate chains get upgraded to the new style. {@code existingSigs}
4162     * will be in the old format (since they were stored on disk from before the
4163     * system upgrade) and {@code scannedSigs} will be in the newer format.
4164     */
4165    private int compareSignaturesCompat(PackageSignatures existingSigs,
4166            PackageParser.Package scannedPkg) {
4167        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4168            return PackageManager.SIGNATURE_NO_MATCH;
4169        }
4170
4171        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4172        for (Signature sig : existingSigs.mSignatures) {
4173            existingSet.add(sig);
4174        }
4175        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4176        for (Signature sig : scannedPkg.mSignatures) {
4177            try {
4178                Signature[] chainSignatures = sig.getChainSignatures();
4179                for (Signature chainSig : chainSignatures) {
4180                    scannedCompatSet.add(chainSig);
4181                }
4182            } catch (CertificateEncodingException e) {
4183                scannedCompatSet.add(sig);
4184            }
4185        }
4186        /*
4187         * Make sure the expanded scanned set contains all signatures in the
4188         * existing one.
4189         */
4190        if (scannedCompatSet.equals(existingSet)) {
4191            // Migrate the old signatures to the new scheme.
4192            existingSigs.assignSignatures(scannedPkg.mSignatures);
4193            // The new KeySets will be re-added later in the scanning process.
4194            synchronized (mPackages) {
4195                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4196            }
4197            return PackageManager.SIGNATURE_MATCH;
4198        }
4199        return PackageManager.SIGNATURE_NO_MATCH;
4200    }
4201
4202    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4203        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4204        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4205    }
4206
4207    private int compareSignaturesRecover(PackageSignatures existingSigs,
4208            PackageParser.Package scannedPkg) {
4209        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4210            return PackageManager.SIGNATURE_NO_MATCH;
4211        }
4212
4213        String msg = null;
4214        try {
4215            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4216                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4217                        + scannedPkg.packageName);
4218                return PackageManager.SIGNATURE_MATCH;
4219            }
4220        } catch (CertificateException e) {
4221            msg = e.getMessage();
4222        }
4223
4224        logCriticalInfo(Log.INFO,
4225                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4226        return PackageManager.SIGNATURE_NO_MATCH;
4227    }
4228
4229    @Override
4230    public String[] getPackagesForUid(int uid) {
4231        uid = UserHandle.getAppId(uid);
4232        // reader
4233        synchronized (mPackages) {
4234            Object obj = mSettings.getUserIdLPr(uid);
4235            if (obj instanceof SharedUserSetting) {
4236                final SharedUserSetting sus = (SharedUserSetting) obj;
4237                final int N = sus.packages.size();
4238                final String[] res = new String[N];
4239                final Iterator<PackageSetting> it = sus.packages.iterator();
4240                int i = 0;
4241                while (it.hasNext()) {
4242                    res[i++] = it.next().name;
4243                }
4244                return res;
4245            } else if (obj instanceof PackageSetting) {
4246                final PackageSetting ps = (PackageSetting) obj;
4247                return new String[] { ps.name };
4248            }
4249        }
4250        return null;
4251    }
4252
4253    @Override
4254    public String getNameForUid(int uid) {
4255        // reader
4256        synchronized (mPackages) {
4257            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4258            if (obj instanceof SharedUserSetting) {
4259                final SharedUserSetting sus = (SharedUserSetting) obj;
4260                return sus.name + ":" + sus.userId;
4261            } else if (obj instanceof PackageSetting) {
4262                final PackageSetting ps = (PackageSetting) obj;
4263                return ps.name;
4264            }
4265        }
4266        return null;
4267    }
4268
4269    @Override
4270    public int getUidForSharedUser(String sharedUserName) {
4271        if(sharedUserName == null) {
4272            return -1;
4273        }
4274        // reader
4275        synchronized (mPackages) {
4276            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4277            if (suid == null) {
4278                return -1;
4279            }
4280            return suid.userId;
4281        }
4282    }
4283
4284    @Override
4285    public int getFlagsForUid(int uid) {
4286        synchronized (mPackages) {
4287            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4288            if (obj instanceof SharedUserSetting) {
4289                final SharedUserSetting sus = (SharedUserSetting) obj;
4290                return sus.pkgFlags;
4291            } else if (obj instanceof PackageSetting) {
4292                final PackageSetting ps = (PackageSetting) obj;
4293                return ps.pkgFlags;
4294            }
4295        }
4296        return 0;
4297    }
4298
4299    @Override
4300    public int getPrivateFlagsForUid(int uid) {
4301        synchronized (mPackages) {
4302            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4303            if (obj instanceof SharedUserSetting) {
4304                final SharedUserSetting sus = (SharedUserSetting) obj;
4305                return sus.pkgPrivateFlags;
4306            } else if (obj instanceof PackageSetting) {
4307                final PackageSetting ps = (PackageSetting) obj;
4308                return ps.pkgPrivateFlags;
4309            }
4310        }
4311        return 0;
4312    }
4313
4314    @Override
4315    public boolean isUidPrivileged(int uid) {
4316        uid = UserHandle.getAppId(uid);
4317        // reader
4318        synchronized (mPackages) {
4319            Object obj = mSettings.getUserIdLPr(uid);
4320            if (obj instanceof SharedUserSetting) {
4321                final SharedUserSetting sus = (SharedUserSetting) obj;
4322                final Iterator<PackageSetting> it = sus.packages.iterator();
4323                while (it.hasNext()) {
4324                    if (it.next().isPrivileged()) {
4325                        return true;
4326                    }
4327                }
4328            } else if (obj instanceof PackageSetting) {
4329                final PackageSetting ps = (PackageSetting) obj;
4330                return ps.isPrivileged();
4331            }
4332        }
4333        return false;
4334    }
4335
4336    @Override
4337    public String[] getAppOpPermissionPackages(String permissionName) {
4338        synchronized (mPackages) {
4339            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4340            if (pkgs == null) {
4341                return null;
4342            }
4343            return pkgs.toArray(new String[pkgs.size()]);
4344        }
4345    }
4346
4347    @Override
4348    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4349            int flags, int userId) {
4350        if (!sUserManager.exists(userId)) return null;
4351        flags = augmentFlagsForUser(flags, userId);
4352        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4353        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4354        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4355    }
4356
4357    @Override
4358    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4359            IntentFilter filter, int match, ComponentName activity) {
4360        final int userId = UserHandle.getCallingUserId();
4361        if (DEBUG_PREFERRED) {
4362            Log.v(TAG, "setLastChosenActivity intent=" + intent
4363                + " resolvedType=" + resolvedType
4364                + " flags=" + flags
4365                + " filter=" + filter
4366                + " match=" + match
4367                + " activity=" + activity);
4368            filter.dump(new PrintStreamPrinter(System.out), "    ");
4369        }
4370        intent.setComponent(null);
4371        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4372        // Find any earlier preferred or last chosen entries and nuke them
4373        findPreferredActivity(intent, resolvedType,
4374                flags, query, 0, false, true, false, userId);
4375        // Add the new activity as the last chosen for this filter
4376        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4377                "Setting last chosen");
4378    }
4379
4380    @Override
4381    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4382        final int userId = UserHandle.getCallingUserId();
4383        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4384        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4385        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4386                false, false, false, userId);
4387    }
4388
4389    private boolean isEphemeralAvailable(Intent intent, String resolvedType, int userId) {
4390        MessageDigest digest = null;
4391        try {
4392            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4393        } catch (NoSuchAlgorithmException e) {
4394            // If we can't create a digest, ignore ephemeral apps.
4395            return false;
4396        }
4397
4398        final byte[] hostBytes = intent.getData().getHost().getBytes();
4399        final byte[] digestBytes = digest.digest(hostBytes);
4400        int shaPrefix =
4401                digestBytes[0] << 24
4402                | digestBytes[1] << 16
4403                | digestBytes[2] << 8
4404                | digestBytes[3] << 0;
4405        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4406                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4407        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4408            // No hash prefix match; there are no ephemeral apps for this domain.
4409            return false;
4410        }
4411        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4412            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4413            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4414                continue;
4415            }
4416            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4417            // No filters; this should never happen.
4418            if (filters.isEmpty()) {
4419                continue;
4420            }
4421            // We have a domain match; resolve the filters to see if anything matches.
4422            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4423            for (int j = filters.size() - 1; j >= 0; --j) {
4424                ephemeralResolver.addFilter(filters.get(j));
4425            }
4426            List<ResolveInfo> ephemeralResolveList = ephemeralResolver.queryIntent(
4427                    intent, resolvedType, false /*defaultOnly*/, userId);
4428            return !ephemeralResolveList.isEmpty();
4429        }
4430        // Hash or filter mis-match; no ephemeral apps for this domain.
4431        return false;
4432    }
4433
4434    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4435            int flags, List<ResolveInfo> query, int userId) {
4436        final boolean isWebUri = hasWebURI(intent);
4437        // Check whether or not an ephemeral app exists to handle the URI.
4438        if (isWebUri && mEphemeralResolverConnection != null) {
4439            // Deny ephemeral apps if the user choose _ALWAYS or _ALWAYS_ASK for intent resolution.
4440            boolean hasAlwaysHandler = false;
4441            synchronized (mPackages) {
4442                final int count = query.size();
4443                for (int n=0; n<count; n++) {
4444                    ResolveInfo info = query.get(n);
4445                    String packageName = info.activityInfo.packageName;
4446                    PackageSetting ps = mSettings.mPackages.get(packageName);
4447                    if (ps != null) {
4448                        // Try to get the status from User settings first
4449                        long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4450                        int status = (int) (packedStatus >> 32);
4451                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4452                                || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4453                            hasAlwaysHandler = true;
4454                            break;
4455                        }
4456                    }
4457                }
4458            }
4459
4460            // Only consider installing an ephemeral app if there isn't already a verified handler.
4461            // We've determined that there's an ephemeral app available for the URI, ignore any
4462            // ResolveInfo's and just return the ephemeral installer
4463            if (!hasAlwaysHandler && isEphemeralAvailable(intent, resolvedType, userId)) {
4464                if (DEBUG_EPHEMERAL) {
4465                    Slog.v(TAG, "Resolving to the ephemeral installer");
4466                }
4467                // ditch the result and return a ResolveInfo to launch the ephemeral installer
4468                ResolveInfo ri = new ResolveInfo(mEphemeralInstallerInfo);
4469                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4470                // make a deep copy of the applicationInfo
4471                ri.activityInfo.applicationInfo = new ApplicationInfo(
4472                        ri.activityInfo.applicationInfo);
4473                if (userId != 0) {
4474                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4475                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4476                }
4477                return ri;
4478            }
4479        }
4480        if (query != null) {
4481            final int N = query.size();
4482            if (N == 1) {
4483                return query.get(0);
4484            } else if (N > 1) {
4485                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4486                // If there is more than one activity with the same priority,
4487                // then let the user decide between them.
4488                ResolveInfo r0 = query.get(0);
4489                ResolveInfo r1 = query.get(1);
4490                if (DEBUG_INTENT_MATCHING || debug) {
4491                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4492                            + r1.activityInfo.name + "=" + r1.priority);
4493                }
4494                // If the first activity has a higher priority, or a different
4495                // default, then it is always desireable to pick it.
4496                if (r0.priority != r1.priority
4497                        || r0.preferredOrder != r1.preferredOrder
4498                        || r0.isDefault != r1.isDefault) {
4499                    return query.get(0);
4500                }
4501                // If we have saved a preference for a preferred activity for
4502                // this Intent, use that.
4503                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4504                        flags, query, r0.priority, true, false, debug, userId);
4505                if (ri != null) {
4506                    return ri;
4507                }
4508                ri = new ResolveInfo(mResolveInfo);
4509                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4510                ri.activityInfo.applicationInfo = new ApplicationInfo(
4511                        ri.activityInfo.applicationInfo);
4512                if (userId != 0) {
4513                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4514                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4515                }
4516                // Make sure that the resolver is displayable in car mode
4517                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4518                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4519                return ri;
4520            }
4521        }
4522        return null;
4523    }
4524
4525    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4526            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4527        final int N = query.size();
4528        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4529                .get(userId);
4530        // Get the list of persistent preferred activities that handle the intent
4531        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4532        List<PersistentPreferredActivity> pprefs = ppir != null
4533                ? ppir.queryIntent(intent, resolvedType,
4534                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4535                : null;
4536        if (pprefs != null && pprefs.size() > 0) {
4537            final int M = pprefs.size();
4538            for (int i=0; i<M; i++) {
4539                final PersistentPreferredActivity ppa = pprefs.get(i);
4540                if (DEBUG_PREFERRED || debug) {
4541                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4542                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4543                            + "\n  component=" + ppa.mComponent);
4544                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4545                }
4546                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4547                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4548                if (DEBUG_PREFERRED || debug) {
4549                    Slog.v(TAG, "Found persistent preferred activity:");
4550                    if (ai != null) {
4551                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4552                    } else {
4553                        Slog.v(TAG, "  null");
4554                    }
4555                }
4556                if (ai == null) {
4557                    // This previously registered persistent preferred activity
4558                    // component is no longer known. Ignore it and do NOT remove it.
4559                    continue;
4560                }
4561                for (int j=0; j<N; j++) {
4562                    final ResolveInfo ri = query.get(j);
4563                    if (!ri.activityInfo.applicationInfo.packageName
4564                            .equals(ai.applicationInfo.packageName)) {
4565                        continue;
4566                    }
4567                    if (!ri.activityInfo.name.equals(ai.name)) {
4568                        continue;
4569                    }
4570                    //  Found a persistent preference that can handle the intent.
4571                    if (DEBUG_PREFERRED || debug) {
4572                        Slog.v(TAG, "Returning persistent preferred activity: " +
4573                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4574                    }
4575                    return ri;
4576                }
4577            }
4578        }
4579        return null;
4580    }
4581
4582    // TODO: handle preferred activities missing while user has amnesia
4583    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4584            List<ResolveInfo> query, int priority, boolean always,
4585            boolean removeMatches, boolean debug, int userId) {
4586        if (!sUserManager.exists(userId)) return null;
4587        flags = augmentFlagsForUser(flags, userId);
4588        // writer
4589        synchronized (mPackages) {
4590            if (intent.getSelector() != null) {
4591                intent = intent.getSelector();
4592            }
4593            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4594
4595            // Try to find a matching persistent preferred activity.
4596            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4597                    debug, userId);
4598
4599            // If a persistent preferred activity matched, use it.
4600            if (pri != null) {
4601                return pri;
4602            }
4603
4604            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4605            // Get the list of preferred activities that handle the intent
4606            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4607            List<PreferredActivity> prefs = pir != null
4608                    ? pir.queryIntent(intent, resolvedType,
4609                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4610                    : null;
4611            if (prefs != null && prefs.size() > 0) {
4612                boolean changed = false;
4613                try {
4614                    // First figure out how good the original match set is.
4615                    // We will only allow preferred activities that came
4616                    // from the same match quality.
4617                    int match = 0;
4618
4619                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4620
4621                    final int N = query.size();
4622                    for (int j=0; j<N; j++) {
4623                        final ResolveInfo ri = query.get(j);
4624                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4625                                + ": 0x" + Integer.toHexString(match));
4626                        if (ri.match > match) {
4627                            match = ri.match;
4628                        }
4629                    }
4630
4631                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4632                            + Integer.toHexString(match));
4633
4634                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4635                    final int M = prefs.size();
4636                    for (int i=0; i<M; i++) {
4637                        final PreferredActivity pa = prefs.get(i);
4638                        if (DEBUG_PREFERRED || debug) {
4639                            Slog.v(TAG, "Checking PreferredActivity ds="
4640                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4641                                    + "\n  component=" + pa.mPref.mComponent);
4642                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4643                        }
4644                        if (pa.mPref.mMatch != match) {
4645                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4646                                    + Integer.toHexString(pa.mPref.mMatch));
4647                            continue;
4648                        }
4649                        // If it's not an "always" type preferred activity and that's what we're
4650                        // looking for, skip it.
4651                        if (always && !pa.mPref.mAlways) {
4652                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4653                            continue;
4654                        }
4655                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4656                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4657                        if (DEBUG_PREFERRED || debug) {
4658                            Slog.v(TAG, "Found preferred activity:");
4659                            if (ai != null) {
4660                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4661                            } else {
4662                                Slog.v(TAG, "  null");
4663                            }
4664                        }
4665                        if (ai == null) {
4666                            // This previously registered preferred activity
4667                            // component is no longer known.  Most likely an update
4668                            // to the app was installed and in the new version this
4669                            // component no longer exists.  Clean it up by removing
4670                            // it from the preferred activities list, and skip it.
4671                            Slog.w(TAG, "Removing dangling preferred activity: "
4672                                    + pa.mPref.mComponent);
4673                            pir.removeFilter(pa);
4674                            changed = true;
4675                            continue;
4676                        }
4677                        for (int j=0; j<N; j++) {
4678                            final ResolveInfo ri = query.get(j);
4679                            if (!ri.activityInfo.applicationInfo.packageName
4680                                    .equals(ai.applicationInfo.packageName)) {
4681                                continue;
4682                            }
4683                            if (!ri.activityInfo.name.equals(ai.name)) {
4684                                continue;
4685                            }
4686
4687                            if (removeMatches) {
4688                                pir.removeFilter(pa);
4689                                changed = true;
4690                                if (DEBUG_PREFERRED) {
4691                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4692                                }
4693                                break;
4694                            }
4695
4696                            // Okay we found a previously set preferred or last chosen app.
4697                            // If the result set is different from when this
4698                            // was created, we need to clear it and re-ask the
4699                            // user their preference, if we're looking for an "always" type entry.
4700                            if (always && !pa.mPref.sameSet(query)) {
4701                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4702                                        + intent + " type " + resolvedType);
4703                                if (DEBUG_PREFERRED) {
4704                                    Slog.v(TAG, "Removing preferred activity since set changed "
4705                                            + pa.mPref.mComponent);
4706                                }
4707                                pir.removeFilter(pa);
4708                                // Re-add the filter as a "last chosen" entry (!always)
4709                                PreferredActivity lastChosen = new PreferredActivity(
4710                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4711                                pir.addFilter(lastChosen);
4712                                changed = true;
4713                                return null;
4714                            }
4715
4716                            // Yay! Either the set matched or we're looking for the last chosen
4717                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4718                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4719                            return ri;
4720                        }
4721                    }
4722                } finally {
4723                    if (changed) {
4724                        if (DEBUG_PREFERRED) {
4725                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4726                        }
4727                        scheduleWritePackageRestrictionsLocked(userId);
4728                    }
4729                }
4730            }
4731        }
4732        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4733        return null;
4734    }
4735
4736    /*
4737     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4738     */
4739    @Override
4740    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4741            int targetUserId) {
4742        mContext.enforceCallingOrSelfPermission(
4743                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4744        List<CrossProfileIntentFilter> matches =
4745                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4746        if (matches != null) {
4747            int size = matches.size();
4748            for (int i = 0; i < size; i++) {
4749                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4750            }
4751        }
4752        if (hasWebURI(intent)) {
4753            // cross-profile app linking works only towards the parent.
4754            final UserInfo parent = getProfileParent(sourceUserId);
4755            synchronized(mPackages) {
4756                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4757                        intent, resolvedType, 0, sourceUserId, parent.id);
4758                return xpDomainInfo != null;
4759            }
4760        }
4761        return false;
4762    }
4763
4764    private UserInfo getProfileParent(int userId) {
4765        final long identity = Binder.clearCallingIdentity();
4766        try {
4767            return sUserManager.getProfileParent(userId);
4768        } finally {
4769            Binder.restoreCallingIdentity(identity);
4770        }
4771    }
4772
4773    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4774            String resolvedType, int userId) {
4775        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4776        if (resolver != null) {
4777            return resolver.queryIntent(intent, resolvedType, false, userId);
4778        }
4779        return null;
4780    }
4781
4782    @Override
4783    public List<ResolveInfo> queryIntentActivities(Intent intent,
4784            String resolvedType, int flags, int userId) {
4785        if (!sUserManager.exists(userId)) return Collections.emptyList();
4786        flags = augmentFlagsForUser(flags, userId);
4787        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4788        ComponentName comp = intent.getComponent();
4789        if (comp == null) {
4790            if (intent.getSelector() != null) {
4791                intent = intent.getSelector();
4792                comp = intent.getComponent();
4793            }
4794        }
4795
4796        if (comp != null) {
4797            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4798            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4799            if (ai != null) {
4800                final ResolveInfo ri = new ResolveInfo();
4801                ri.activityInfo = ai;
4802                list.add(ri);
4803            }
4804            return list;
4805        }
4806
4807        // reader
4808        synchronized (mPackages) {
4809            final String pkgName = intent.getPackage();
4810            if (pkgName == null) {
4811                List<CrossProfileIntentFilter> matchingFilters =
4812                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4813                // Check for results that need to skip the current profile.
4814                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4815                        resolvedType, flags, userId);
4816                if (xpResolveInfo != null) {
4817                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4818                    result.add(xpResolveInfo);
4819                    return filterIfNotSystemUser(result, userId);
4820                }
4821
4822                // Check for results in the current profile.
4823                List<ResolveInfo> result = mActivities.queryIntent(
4824                        intent, resolvedType, flags, userId);
4825
4826                // Check for cross profile results.
4827                xpResolveInfo = queryCrossProfileIntents(
4828                        matchingFilters, intent, resolvedType, flags, userId);
4829                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4830                    result.add(xpResolveInfo);
4831                    Collections.sort(result, mResolvePrioritySorter);
4832                }
4833                result = filterIfNotSystemUser(result, userId);
4834                if (hasWebURI(intent)) {
4835                    CrossProfileDomainInfo xpDomainInfo = null;
4836                    final UserInfo parent = getProfileParent(userId);
4837                    if (parent != null) {
4838                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4839                                flags, userId, parent.id);
4840                    }
4841                    if (xpDomainInfo != null) {
4842                        if (xpResolveInfo != null) {
4843                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4844                            // in the result.
4845                            result.remove(xpResolveInfo);
4846                        }
4847                        if (result.size() == 0) {
4848                            result.add(xpDomainInfo.resolveInfo);
4849                            return result;
4850                        }
4851                    } else if (result.size() <= 1) {
4852                        return result;
4853                    }
4854                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4855                            xpDomainInfo, userId);
4856                    Collections.sort(result, mResolvePrioritySorter);
4857                }
4858                return result;
4859            }
4860            final PackageParser.Package pkg = mPackages.get(pkgName);
4861            if (pkg != null) {
4862                return filterIfNotSystemUser(
4863                        mActivities.queryIntentForPackage(
4864                                intent, resolvedType, flags, pkg.activities, userId),
4865                        userId);
4866            }
4867            return new ArrayList<ResolveInfo>();
4868        }
4869    }
4870
4871    private static class CrossProfileDomainInfo {
4872        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4873        ResolveInfo resolveInfo;
4874        /* Best domain verification status of the activities found in the other profile */
4875        int bestDomainVerificationStatus;
4876    }
4877
4878    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4879            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4880        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4881                sourceUserId)) {
4882            return null;
4883        }
4884        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4885                resolvedType, flags, parentUserId);
4886
4887        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4888            return null;
4889        }
4890        CrossProfileDomainInfo result = null;
4891        int size = resultTargetUser.size();
4892        for (int i = 0; i < size; i++) {
4893            ResolveInfo riTargetUser = resultTargetUser.get(i);
4894            // Intent filter verification is only for filters that specify a host. So don't return
4895            // those that handle all web uris.
4896            if (riTargetUser.handleAllWebDataURI) {
4897                continue;
4898            }
4899            String packageName = riTargetUser.activityInfo.packageName;
4900            PackageSetting ps = mSettings.mPackages.get(packageName);
4901            if (ps == null) {
4902                continue;
4903            }
4904            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4905            int status = (int)(verificationState >> 32);
4906            if (result == null) {
4907                result = new CrossProfileDomainInfo();
4908                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
4909                        sourceUserId, parentUserId);
4910                result.bestDomainVerificationStatus = status;
4911            } else {
4912                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4913                        result.bestDomainVerificationStatus);
4914            }
4915        }
4916        // Don't consider matches with status NEVER across profiles.
4917        if (result != null && result.bestDomainVerificationStatus
4918                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4919            return null;
4920        }
4921        return result;
4922    }
4923
4924    /**
4925     * Verification statuses are ordered from the worse to the best, except for
4926     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4927     */
4928    private int bestDomainVerificationStatus(int status1, int status2) {
4929        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4930            return status2;
4931        }
4932        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4933            return status1;
4934        }
4935        return (int) MathUtils.max(status1, status2);
4936    }
4937
4938    private boolean isUserEnabled(int userId) {
4939        long callingId = Binder.clearCallingIdentity();
4940        try {
4941            UserInfo userInfo = sUserManager.getUserInfo(userId);
4942            return userInfo != null && userInfo.isEnabled();
4943        } finally {
4944            Binder.restoreCallingIdentity(callingId);
4945        }
4946    }
4947
4948    /**
4949     * Filter out activities with systemUserOnly flag set, when current user is not System.
4950     *
4951     * @return filtered list
4952     */
4953    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
4954        if (userId == UserHandle.USER_SYSTEM) {
4955            return resolveInfos;
4956        }
4957        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4958            ResolveInfo info = resolveInfos.get(i);
4959            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
4960                resolveInfos.remove(i);
4961            }
4962        }
4963        return resolveInfos;
4964    }
4965
4966    private static boolean hasWebURI(Intent intent) {
4967        if (intent.getData() == null) {
4968            return false;
4969        }
4970        final String scheme = intent.getScheme();
4971        if (TextUtils.isEmpty(scheme)) {
4972            return false;
4973        }
4974        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4975    }
4976
4977    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
4978            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
4979            int userId) {
4980        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
4981
4982        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4983            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
4984                    candidates.size());
4985        }
4986
4987        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4988        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4989        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4990        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
4991        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4992        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4993
4994        synchronized (mPackages) {
4995            final int count = candidates.size();
4996            // First, try to use linked apps. Partition the candidates into four lists:
4997            // one for the final results, one for the "do not use ever", one for "undefined status"
4998            // and finally one for "browser app type".
4999            for (int n=0; n<count; n++) {
5000                ResolveInfo info = candidates.get(n);
5001                String packageName = info.activityInfo.packageName;
5002                PackageSetting ps = mSettings.mPackages.get(packageName);
5003                if (ps != null) {
5004                    // Add to the special match all list (Browser use case)
5005                    if (info.handleAllWebDataURI) {
5006                        matchAllList.add(info);
5007                        continue;
5008                    }
5009                    // Try to get the status from User settings first
5010                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5011                    int status = (int)(packedStatus >> 32);
5012                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5013                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5014                        if (DEBUG_DOMAIN_VERIFICATION) {
5015                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5016                                    + " : linkgen=" + linkGeneration);
5017                        }
5018                        // Use link-enabled generation as preferredOrder, i.e.
5019                        // prefer newly-enabled over earlier-enabled.
5020                        info.preferredOrder = linkGeneration;
5021                        alwaysList.add(info);
5022                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5023                        if (DEBUG_DOMAIN_VERIFICATION) {
5024                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5025                        }
5026                        neverList.add(info);
5027                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5028                        if (DEBUG_DOMAIN_VERIFICATION) {
5029                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5030                        }
5031                        alwaysAskList.add(info);
5032                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5033                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5034                        if (DEBUG_DOMAIN_VERIFICATION) {
5035                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5036                        }
5037                        undefinedList.add(info);
5038                    }
5039                }
5040            }
5041
5042            // We'll want to include browser possibilities in a few cases
5043            boolean includeBrowser = false;
5044
5045            // First try to add the "always" resolution(s) for the current user, if any
5046            if (alwaysList.size() > 0) {
5047                result.addAll(alwaysList);
5048            } else {
5049                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5050                result.addAll(undefinedList);
5051                // Maybe add one for the other profile.
5052                if (xpDomainInfo != null && (
5053                        xpDomainInfo.bestDomainVerificationStatus
5054                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5055                    result.add(xpDomainInfo.resolveInfo);
5056                }
5057                includeBrowser = true;
5058            }
5059
5060            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5061            // If there were 'always' entries their preferred order has been set, so we also
5062            // back that off to make the alternatives equivalent
5063            if (alwaysAskList.size() > 0) {
5064                for (ResolveInfo i : result) {
5065                    i.preferredOrder = 0;
5066                }
5067                result.addAll(alwaysAskList);
5068                includeBrowser = true;
5069            }
5070
5071            if (includeBrowser) {
5072                // Also add browsers (all of them or only the default one)
5073                if (DEBUG_DOMAIN_VERIFICATION) {
5074                    Slog.v(TAG, "   ...including browsers in candidate set");
5075                }
5076                if ((matchFlags & MATCH_ALL) != 0) {
5077                    result.addAll(matchAllList);
5078                } else {
5079                    // Browser/generic handling case.  If there's a default browser, go straight
5080                    // to that (but only if there is no other higher-priority match).
5081                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5082                    int maxMatchPrio = 0;
5083                    ResolveInfo defaultBrowserMatch = null;
5084                    final int numCandidates = matchAllList.size();
5085                    for (int n = 0; n < numCandidates; n++) {
5086                        ResolveInfo info = matchAllList.get(n);
5087                        // track the highest overall match priority...
5088                        if (info.priority > maxMatchPrio) {
5089                            maxMatchPrio = info.priority;
5090                        }
5091                        // ...and the highest-priority default browser match
5092                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5093                            if (defaultBrowserMatch == null
5094                                    || (defaultBrowserMatch.priority < info.priority)) {
5095                                if (debug) {
5096                                    Slog.v(TAG, "Considering default browser match " + info);
5097                                }
5098                                defaultBrowserMatch = info;
5099                            }
5100                        }
5101                    }
5102                    if (defaultBrowserMatch != null
5103                            && defaultBrowserMatch.priority >= maxMatchPrio
5104                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5105                    {
5106                        if (debug) {
5107                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5108                        }
5109                        result.add(defaultBrowserMatch);
5110                    } else {
5111                        result.addAll(matchAllList);
5112                    }
5113                }
5114
5115                // If there is nothing selected, add all candidates and remove the ones that the user
5116                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5117                if (result.size() == 0) {
5118                    result.addAll(candidates);
5119                    result.removeAll(neverList);
5120                }
5121            }
5122        }
5123        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5124            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5125                    result.size());
5126            for (ResolveInfo info : result) {
5127                Slog.v(TAG, "  + " + info.activityInfo);
5128            }
5129        }
5130        return result;
5131    }
5132
5133    // Returns a packed value as a long:
5134    //
5135    // high 'int'-sized word: link status: undefined/ask/never/always.
5136    // low 'int'-sized word: relative priority among 'always' results.
5137    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5138        long result = ps.getDomainVerificationStatusForUser(userId);
5139        // if none available, get the master status
5140        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5141            if (ps.getIntentFilterVerificationInfo() != null) {
5142                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5143            }
5144        }
5145        return result;
5146    }
5147
5148    private ResolveInfo querySkipCurrentProfileIntents(
5149            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5150            int flags, int sourceUserId) {
5151        if (matchingFilters != null) {
5152            int size = matchingFilters.size();
5153            for (int i = 0; i < size; i ++) {
5154                CrossProfileIntentFilter filter = matchingFilters.get(i);
5155                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5156                    // Checking if there are activities in the target user that can handle the
5157                    // intent.
5158                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5159                            resolvedType, flags, sourceUserId);
5160                    if (resolveInfo != null) {
5161                        return resolveInfo;
5162                    }
5163                }
5164            }
5165        }
5166        return null;
5167    }
5168
5169    // Return matching ResolveInfo if any for skip current profile intent filters.
5170    private ResolveInfo queryCrossProfileIntents(
5171            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5172            int flags, int sourceUserId) {
5173        if (matchingFilters != null) {
5174            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5175            // match the same intent. For performance reasons, it is better not to
5176            // run queryIntent twice for the same userId
5177            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5178            int size = matchingFilters.size();
5179            for (int i = 0; i < size; i++) {
5180                CrossProfileIntentFilter filter = matchingFilters.get(i);
5181                int targetUserId = filter.getTargetUserId();
5182                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
5183                        && !alreadyTriedUserIds.get(targetUserId)) {
5184                    // Checking if there are activities in the target user that can handle the
5185                    // intent.
5186                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5187                            resolvedType, flags, sourceUserId);
5188                    if (resolveInfo != null) return resolveInfo;
5189                    alreadyTriedUserIds.put(targetUserId, true);
5190                }
5191            }
5192        }
5193        return null;
5194    }
5195
5196    /**
5197     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5198     * will forward the intent to the filter's target user.
5199     * Otherwise, returns null.
5200     */
5201    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5202            String resolvedType, int flags, int sourceUserId) {
5203        int targetUserId = filter.getTargetUserId();
5204        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5205                resolvedType, flags, targetUserId);
5206        if (resultTargetUser != null && !resultTargetUser.isEmpty()
5207                && isUserEnabled(targetUserId)) {
5208            return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId);
5209        }
5210        return null;
5211    }
5212
5213    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5214            int sourceUserId, int targetUserId) {
5215        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5216        long ident = Binder.clearCallingIdentity();
5217        boolean targetIsProfile;
5218        try {
5219            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5220        } finally {
5221            Binder.restoreCallingIdentity(ident);
5222        }
5223        String className;
5224        if (targetIsProfile) {
5225            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5226        } else {
5227            className = FORWARD_INTENT_TO_PARENT;
5228        }
5229        ComponentName forwardingActivityComponentName = new ComponentName(
5230                mAndroidApplication.packageName, className);
5231        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5232                sourceUserId);
5233        if (!targetIsProfile) {
5234            forwardingActivityInfo.showUserIcon = targetUserId;
5235            forwardingResolveInfo.noResourceId = true;
5236        }
5237        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5238        forwardingResolveInfo.priority = 0;
5239        forwardingResolveInfo.preferredOrder = 0;
5240        forwardingResolveInfo.match = 0;
5241        forwardingResolveInfo.isDefault = true;
5242        forwardingResolveInfo.filter = filter;
5243        forwardingResolveInfo.targetUserId = targetUserId;
5244        return forwardingResolveInfo;
5245    }
5246
5247    @Override
5248    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5249            Intent[] specifics, String[] specificTypes, Intent intent,
5250            String resolvedType, int flags, int userId) {
5251        if (!sUserManager.exists(userId)) return Collections.emptyList();
5252        flags = augmentFlagsForUser(flags, userId);
5253        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
5254                false, "query intent activity options");
5255        final String resultsAction = intent.getAction();
5256
5257        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
5258                | PackageManager.GET_RESOLVED_FILTER, userId);
5259
5260        if (DEBUG_INTENT_MATCHING) {
5261            Log.v(TAG, "Query " + intent + ": " + results);
5262        }
5263
5264        int specificsPos = 0;
5265        int N;
5266
5267        // todo: note that the algorithm used here is O(N^2).  This
5268        // isn't a problem in our current environment, but if we start running
5269        // into situations where we have more than 5 or 10 matches then this
5270        // should probably be changed to something smarter...
5271
5272        // First we go through and resolve each of the specific items
5273        // that were supplied, taking care of removing any corresponding
5274        // duplicate items in the generic resolve list.
5275        if (specifics != null) {
5276            for (int i=0; i<specifics.length; i++) {
5277                final Intent sintent = specifics[i];
5278                if (sintent == null) {
5279                    continue;
5280                }
5281
5282                if (DEBUG_INTENT_MATCHING) {
5283                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5284                }
5285
5286                String action = sintent.getAction();
5287                if (resultsAction != null && resultsAction.equals(action)) {
5288                    // If this action was explicitly requested, then don't
5289                    // remove things that have it.
5290                    action = null;
5291                }
5292
5293                ResolveInfo ri = null;
5294                ActivityInfo ai = null;
5295
5296                ComponentName comp = sintent.getComponent();
5297                if (comp == null) {
5298                    ri = resolveIntent(
5299                        sintent,
5300                        specificTypes != null ? specificTypes[i] : null,
5301                            flags, userId);
5302                    if (ri == null) {
5303                        continue;
5304                    }
5305                    if (ri == mResolveInfo) {
5306                        // ACK!  Must do something better with this.
5307                    }
5308                    ai = ri.activityInfo;
5309                    comp = new ComponentName(ai.applicationInfo.packageName,
5310                            ai.name);
5311                } else {
5312                    ai = getActivityInfo(comp, flags, userId);
5313                    if (ai == null) {
5314                        continue;
5315                    }
5316                }
5317
5318                // Look for any generic query activities that are duplicates
5319                // of this specific one, and remove them from the results.
5320                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5321                N = results.size();
5322                int j;
5323                for (j=specificsPos; j<N; j++) {
5324                    ResolveInfo sri = results.get(j);
5325                    if ((sri.activityInfo.name.equals(comp.getClassName())
5326                            && sri.activityInfo.applicationInfo.packageName.equals(
5327                                    comp.getPackageName()))
5328                        || (action != null && sri.filter.matchAction(action))) {
5329                        results.remove(j);
5330                        if (DEBUG_INTENT_MATCHING) Log.v(
5331                            TAG, "Removing duplicate item from " + j
5332                            + " due to specific " + specificsPos);
5333                        if (ri == null) {
5334                            ri = sri;
5335                        }
5336                        j--;
5337                        N--;
5338                    }
5339                }
5340
5341                // Add this specific item to its proper place.
5342                if (ri == null) {
5343                    ri = new ResolveInfo();
5344                    ri.activityInfo = ai;
5345                }
5346                results.add(specificsPos, ri);
5347                ri.specificIndex = i;
5348                specificsPos++;
5349            }
5350        }
5351
5352        // Now we go through the remaining generic results and remove any
5353        // duplicate actions that are found here.
5354        N = results.size();
5355        for (int i=specificsPos; i<N-1; i++) {
5356            final ResolveInfo rii = results.get(i);
5357            if (rii.filter == null) {
5358                continue;
5359            }
5360
5361            // Iterate over all of the actions of this result's intent
5362            // filter...  typically this should be just one.
5363            final Iterator<String> it = rii.filter.actionsIterator();
5364            if (it == null) {
5365                continue;
5366            }
5367            while (it.hasNext()) {
5368                final String action = it.next();
5369                if (resultsAction != null && resultsAction.equals(action)) {
5370                    // If this action was explicitly requested, then don't
5371                    // remove things that have it.
5372                    continue;
5373                }
5374                for (int j=i+1; j<N; j++) {
5375                    final ResolveInfo rij = results.get(j);
5376                    if (rij.filter != null && rij.filter.hasAction(action)) {
5377                        results.remove(j);
5378                        if (DEBUG_INTENT_MATCHING) Log.v(
5379                            TAG, "Removing duplicate item from " + j
5380                            + " due to action " + action + " at " + i);
5381                        j--;
5382                        N--;
5383                    }
5384                }
5385            }
5386
5387            // If the caller didn't request filter information, drop it now
5388            // so we don't have to marshall/unmarshall it.
5389            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5390                rii.filter = null;
5391            }
5392        }
5393
5394        // Filter out the caller activity if so requested.
5395        if (caller != null) {
5396            N = results.size();
5397            for (int i=0; i<N; i++) {
5398                ActivityInfo ainfo = results.get(i).activityInfo;
5399                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5400                        && caller.getClassName().equals(ainfo.name)) {
5401                    results.remove(i);
5402                    break;
5403                }
5404            }
5405        }
5406
5407        // If the caller didn't request filter information,
5408        // drop them now so we don't have to
5409        // marshall/unmarshall it.
5410        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5411            N = results.size();
5412            for (int i=0; i<N; i++) {
5413                results.get(i).filter = null;
5414            }
5415        }
5416
5417        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5418        return results;
5419    }
5420
5421    @Override
5422    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5423            int userId) {
5424        if (!sUserManager.exists(userId)) return Collections.emptyList();
5425        flags = augmentFlagsForUser(flags, userId);
5426        ComponentName comp = intent.getComponent();
5427        if (comp == null) {
5428            if (intent.getSelector() != null) {
5429                intent = intent.getSelector();
5430                comp = intent.getComponent();
5431            }
5432        }
5433        if (comp != null) {
5434            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5435            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5436            if (ai != null) {
5437                ResolveInfo ri = new ResolveInfo();
5438                ri.activityInfo = ai;
5439                list.add(ri);
5440            }
5441            return list;
5442        }
5443
5444        // reader
5445        synchronized (mPackages) {
5446            String pkgName = intent.getPackage();
5447            if (pkgName == null) {
5448                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5449            }
5450            final PackageParser.Package pkg = mPackages.get(pkgName);
5451            if (pkg != null) {
5452                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5453                        userId);
5454            }
5455            return null;
5456        }
5457    }
5458
5459    @Override
5460    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5461        if (!sUserManager.exists(userId)) return null;
5462        flags = augmentFlagsForUser(flags, userId);
5463        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5464        if (query != null) {
5465            if (query.size() >= 1) {
5466                // If there is more than one service with the same priority,
5467                // just arbitrarily pick the first one.
5468                return query.get(0);
5469            }
5470        }
5471        return null;
5472    }
5473
5474    @Override
5475    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5476            int userId) {
5477        if (!sUserManager.exists(userId)) return Collections.emptyList();
5478        flags = augmentFlagsForUser(flags, userId);
5479        ComponentName comp = intent.getComponent();
5480        if (comp == null) {
5481            if (intent.getSelector() != null) {
5482                intent = intent.getSelector();
5483                comp = intent.getComponent();
5484            }
5485        }
5486        if (comp != null) {
5487            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5488            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5489            if (si != null) {
5490                final ResolveInfo ri = new ResolveInfo();
5491                ri.serviceInfo = si;
5492                list.add(ri);
5493            }
5494            return list;
5495        }
5496
5497        // reader
5498        synchronized (mPackages) {
5499            String pkgName = intent.getPackage();
5500            if (pkgName == null) {
5501                return mServices.queryIntent(intent, resolvedType, flags, userId);
5502            }
5503            final PackageParser.Package pkg = mPackages.get(pkgName);
5504            if (pkg != null) {
5505                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5506                        userId);
5507            }
5508            return null;
5509        }
5510    }
5511
5512    @Override
5513    public List<ResolveInfo> queryIntentContentProviders(
5514            Intent intent, String resolvedType, int flags, int userId) {
5515        if (!sUserManager.exists(userId)) return Collections.emptyList();
5516        flags = augmentFlagsForUser(flags, userId);
5517        ComponentName comp = intent.getComponent();
5518        if (comp == null) {
5519            if (intent.getSelector() != null) {
5520                intent = intent.getSelector();
5521                comp = intent.getComponent();
5522            }
5523        }
5524        if (comp != null) {
5525            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5526            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5527            if (pi != null) {
5528                final ResolveInfo ri = new ResolveInfo();
5529                ri.providerInfo = pi;
5530                list.add(ri);
5531            }
5532            return list;
5533        }
5534
5535        // reader
5536        synchronized (mPackages) {
5537            String pkgName = intent.getPackage();
5538            if (pkgName == null) {
5539                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5540            }
5541            final PackageParser.Package pkg = mPackages.get(pkgName);
5542            if (pkg != null) {
5543                return mProviders.queryIntentForPackage(
5544                        intent, resolvedType, flags, pkg.providers, userId);
5545            }
5546            return null;
5547        }
5548    }
5549
5550    @Override
5551    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5552        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5553
5554        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5555
5556        // writer
5557        synchronized (mPackages) {
5558            ArrayList<PackageInfo> list;
5559            if (listUninstalled) {
5560                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5561                for (PackageSetting ps : mSettings.mPackages.values()) {
5562                    PackageInfo pi;
5563                    if (ps.pkg != null) {
5564                        pi = generatePackageInfo(ps.pkg, flags, userId);
5565                    } else {
5566                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5567                    }
5568                    if (pi != null) {
5569                        list.add(pi);
5570                    }
5571                }
5572            } else {
5573                list = new ArrayList<PackageInfo>(mPackages.size());
5574                for (PackageParser.Package p : mPackages.values()) {
5575                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5576                    if (pi != null) {
5577                        list.add(pi);
5578                    }
5579                }
5580            }
5581
5582            return new ParceledListSlice<PackageInfo>(list);
5583        }
5584    }
5585
5586    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5587            String[] permissions, boolean[] tmp, int flags, int userId) {
5588        int numMatch = 0;
5589        final PermissionsState permissionsState = ps.getPermissionsState();
5590        for (int i=0; i<permissions.length; i++) {
5591            final String permission = permissions[i];
5592            if (permissionsState.hasPermission(permission, userId)) {
5593                tmp[i] = true;
5594                numMatch++;
5595            } else {
5596                tmp[i] = false;
5597            }
5598        }
5599        if (numMatch == 0) {
5600            return;
5601        }
5602        PackageInfo pi;
5603        if (ps.pkg != null) {
5604            pi = generatePackageInfo(ps.pkg, flags, userId);
5605        } else {
5606            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5607        }
5608        // The above might return null in cases of uninstalled apps or install-state
5609        // skew across users/profiles.
5610        if (pi != null) {
5611            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5612                if (numMatch == permissions.length) {
5613                    pi.requestedPermissions = permissions;
5614                } else {
5615                    pi.requestedPermissions = new String[numMatch];
5616                    numMatch = 0;
5617                    for (int i=0; i<permissions.length; i++) {
5618                        if (tmp[i]) {
5619                            pi.requestedPermissions[numMatch] = permissions[i];
5620                            numMatch++;
5621                        }
5622                    }
5623                }
5624            }
5625            list.add(pi);
5626        }
5627    }
5628
5629    @Override
5630    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5631            String[] permissions, int flags, int userId) {
5632        if (!sUserManager.exists(userId)) return null;
5633        flags = augmentFlagsForUser(flags, userId);
5634        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5635
5636        // writer
5637        synchronized (mPackages) {
5638            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5639            boolean[] tmpBools = new boolean[permissions.length];
5640            if (listUninstalled) {
5641                for (PackageSetting ps : mSettings.mPackages.values()) {
5642                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5643                }
5644            } else {
5645                for (PackageParser.Package pkg : mPackages.values()) {
5646                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5647                    if (ps != null) {
5648                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5649                                userId);
5650                    }
5651                }
5652            }
5653
5654            return new ParceledListSlice<PackageInfo>(list);
5655        }
5656    }
5657
5658    @Override
5659    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5660        if (!sUserManager.exists(userId)) return null;
5661        flags = augmentFlagsForUser(flags, userId);
5662        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5663
5664        // writer
5665        synchronized (mPackages) {
5666            ArrayList<ApplicationInfo> list;
5667            if (listUninstalled) {
5668                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5669                for (PackageSetting ps : mSettings.mPackages.values()) {
5670                    ApplicationInfo ai;
5671                    if (ps.pkg != null) {
5672                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5673                                ps.readUserState(userId), userId);
5674                    } else {
5675                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5676                    }
5677                    if (ai != null) {
5678                        list.add(ai);
5679                    }
5680                }
5681            } else {
5682                list = new ArrayList<ApplicationInfo>(mPackages.size());
5683                for (PackageParser.Package p : mPackages.values()) {
5684                    if (p.mExtras != null) {
5685                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5686                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5687                        if (ai != null) {
5688                            list.add(ai);
5689                        }
5690                    }
5691                }
5692            }
5693
5694            return new ParceledListSlice<ApplicationInfo>(list);
5695        }
5696    }
5697
5698    public List<ApplicationInfo> getPersistentApplications(int flags) {
5699        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5700
5701        // reader
5702        synchronized (mPackages) {
5703            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5704            final int userId = UserHandle.getCallingUserId();
5705            while (i.hasNext()) {
5706                final PackageParser.Package p = i.next();
5707                if (p.applicationInfo != null
5708                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5709                        && (!mSafeMode || isSystemApp(p))) {
5710                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5711                    if (ps != null) {
5712                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5713                                ps.readUserState(userId), userId);
5714                        if (ai != null) {
5715                            finalList.add(ai);
5716                        }
5717                    }
5718                }
5719            }
5720        }
5721
5722        return finalList;
5723    }
5724
5725    @Override
5726    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5727        if (!sUserManager.exists(userId)) return null;
5728        flags = augmentFlagsForUser(flags, userId);
5729        // reader
5730        synchronized (mPackages) {
5731            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5732            PackageSetting ps = provider != null
5733                    ? mSettings.mPackages.get(provider.owner.packageName)
5734                    : null;
5735            return ps != null
5736                    && mSettings.isEnabledAndVisibleLPr(provider.info, flags, userId)
5737                    && (!mSafeMode || (provider.info.applicationInfo.flags
5738                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5739                    ? PackageParser.generateProviderInfo(provider, flags,
5740                            ps.readUserState(userId), userId)
5741                    : null;
5742        }
5743    }
5744
5745    /**
5746     * @deprecated
5747     */
5748    @Deprecated
5749    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5750        // reader
5751        synchronized (mPackages) {
5752            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5753                    .entrySet().iterator();
5754            final int userId = UserHandle.getCallingUserId();
5755            while (i.hasNext()) {
5756                Map.Entry<String, PackageParser.Provider> entry = i.next();
5757                PackageParser.Provider p = entry.getValue();
5758                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5759
5760                if (ps != null && p.syncable
5761                        && (!mSafeMode || (p.info.applicationInfo.flags
5762                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5763                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5764                            ps.readUserState(userId), userId);
5765                    if (info != null) {
5766                        outNames.add(entry.getKey());
5767                        outInfo.add(info);
5768                    }
5769                }
5770            }
5771        }
5772    }
5773
5774    @Override
5775    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
5776            int uid, int flags) {
5777        final int userId = processName != null ? UserHandle.getUserId(uid)
5778                : UserHandle.getCallingUserId();
5779        if (!sUserManager.exists(userId)) return null;
5780        flags = augmentFlagsForUser(flags, userId);
5781
5782        ArrayList<ProviderInfo> finalList = null;
5783        // reader
5784        synchronized (mPackages) {
5785            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5786            while (i.hasNext()) {
5787                final PackageParser.Provider p = i.next();
5788                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5789                if (ps != null && p.info.authority != null
5790                        && (processName == null
5791                                || (p.info.processName.equals(processName)
5792                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5793                        && mSettings.isEnabledAndVisibleLPr(p.info, flags, userId)
5794                        && (!mSafeMode
5795                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5796                    if (finalList == null) {
5797                        finalList = new ArrayList<ProviderInfo>(3);
5798                    }
5799                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5800                            ps.readUserState(userId), userId);
5801                    if (info != null) {
5802                        finalList.add(info);
5803                    }
5804                }
5805            }
5806        }
5807
5808        if (finalList != null) {
5809            Collections.sort(finalList, mProviderInitOrderSorter);
5810            return new ParceledListSlice<ProviderInfo>(finalList);
5811        }
5812
5813        return null;
5814    }
5815
5816    @Override
5817    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5818            int flags) {
5819        // reader
5820        synchronized (mPackages) {
5821            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5822            return PackageParser.generateInstrumentationInfo(i, flags);
5823        }
5824    }
5825
5826    @Override
5827    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5828            int flags) {
5829        ArrayList<InstrumentationInfo> finalList =
5830            new ArrayList<InstrumentationInfo>();
5831
5832        // reader
5833        synchronized (mPackages) {
5834            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5835            while (i.hasNext()) {
5836                final PackageParser.Instrumentation p = i.next();
5837                if (targetPackage == null
5838                        || targetPackage.equals(p.info.targetPackage)) {
5839                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5840                            flags);
5841                    if (ii != null) {
5842                        finalList.add(ii);
5843                    }
5844                }
5845            }
5846        }
5847
5848        return finalList;
5849    }
5850
5851    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5852        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5853        if (overlays == null) {
5854            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5855            return;
5856        }
5857        for (PackageParser.Package opkg : overlays.values()) {
5858            // Not much to do if idmap fails: we already logged the error
5859            // and we certainly don't want to abort installation of pkg simply
5860            // because an overlay didn't fit properly. For these reasons,
5861            // ignore the return value of createIdmapForPackagePairLI.
5862            createIdmapForPackagePairLI(pkg, opkg);
5863        }
5864    }
5865
5866    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5867            PackageParser.Package opkg) {
5868        if (!opkg.mTrustedOverlay) {
5869            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5870                    opkg.baseCodePath + ": overlay not trusted");
5871            return false;
5872        }
5873        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5874        if (overlaySet == null) {
5875            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5876                    opkg.baseCodePath + " but target package has no known overlays");
5877            return false;
5878        }
5879        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5880        // TODO: generate idmap for split APKs
5881        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5882            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5883                    + opkg.baseCodePath);
5884            return false;
5885        }
5886        PackageParser.Package[] overlayArray =
5887            overlaySet.values().toArray(new PackageParser.Package[0]);
5888        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5889            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5890                return p1.mOverlayPriority - p2.mOverlayPriority;
5891            }
5892        };
5893        Arrays.sort(overlayArray, cmp);
5894
5895        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5896        int i = 0;
5897        for (PackageParser.Package p : overlayArray) {
5898            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5899        }
5900        return true;
5901    }
5902
5903    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5904        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
5905        try {
5906            scanDirLI(dir, parseFlags, scanFlags, currentTime);
5907        } finally {
5908            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5909        }
5910    }
5911
5912    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5913        final File[] files = dir.listFiles();
5914        if (ArrayUtils.isEmpty(files)) {
5915            Log.d(TAG, "No files in app dir " + dir);
5916            return;
5917        }
5918
5919        if (DEBUG_PACKAGE_SCANNING) {
5920            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5921                    + " flags=0x" + Integer.toHexString(parseFlags));
5922        }
5923
5924        for (File file : files) {
5925            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5926                    && !PackageInstallerService.isStageName(file.getName());
5927            if (!isPackage) {
5928                // Ignore entries which are not packages
5929                continue;
5930            }
5931            try {
5932                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5933                        scanFlags, currentTime, null);
5934            } catch (PackageManagerException e) {
5935                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5936
5937                // Delete invalid userdata apps
5938                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5939                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5940                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5941                    if (file.isDirectory()) {
5942                        mInstaller.rmPackageDir(file.getAbsolutePath());
5943                    } else {
5944                        file.delete();
5945                    }
5946                }
5947            }
5948        }
5949    }
5950
5951    private static File getSettingsProblemFile() {
5952        File dataDir = Environment.getDataDirectory();
5953        File systemDir = new File(dataDir, "system");
5954        File fname = new File(systemDir, "uiderrors.txt");
5955        return fname;
5956    }
5957
5958    static void reportSettingsProblem(int priority, String msg) {
5959        logCriticalInfo(priority, msg);
5960    }
5961
5962    static void logCriticalInfo(int priority, String msg) {
5963        Slog.println(priority, TAG, msg);
5964        EventLogTags.writePmCriticalInfo(msg);
5965        try {
5966            File fname = getSettingsProblemFile();
5967            FileOutputStream out = new FileOutputStream(fname, true);
5968            PrintWriter pw = new FastPrintWriter(out);
5969            SimpleDateFormat formatter = new SimpleDateFormat();
5970            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5971            pw.println(dateString + ": " + msg);
5972            pw.close();
5973            FileUtils.setPermissions(
5974                    fname.toString(),
5975                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5976                    -1, -1);
5977        } catch (java.io.IOException e) {
5978        }
5979    }
5980
5981    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5982            PackageParser.Package pkg, File srcFile, int parseFlags)
5983            throws PackageManagerException {
5984        if (ps != null
5985                && ps.codePath.equals(srcFile)
5986                && ps.timeStamp == srcFile.lastModified()
5987                && !isCompatSignatureUpdateNeeded(pkg)
5988                && !isRecoverSignatureUpdateNeeded(pkg)) {
5989            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5990            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5991            ArraySet<PublicKey> signingKs;
5992            synchronized (mPackages) {
5993                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5994            }
5995            if (ps.signatures.mSignatures != null
5996                    && ps.signatures.mSignatures.length != 0
5997                    && signingKs != null) {
5998                // Optimization: reuse the existing cached certificates
5999                // if the package appears to be unchanged.
6000                pkg.mSignatures = ps.signatures.mSignatures;
6001                pkg.mSigningKeys = signingKs;
6002                return;
6003            }
6004
6005            Slog.w(TAG, "PackageSetting for " + ps.name
6006                    + " is missing signatures.  Collecting certs again to recover them.");
6007        } else {
6008            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6009        }
6010
6011        try {
6012            pp.collectCertificates(pkg, parseFlags);
6013            pp.collectManifestDigest(pkg);
6014        } catch (PackageParserException e) {
6015            throw PackageManagerException.from(e);
6016        }
6017    }
6018
6019    /**
6020     *  Traces a package scan.
6021     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6022     */
6023    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
6024            long currentTime, UserHandle user) throws PackageManagerException {
6025        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6026        try {
6027            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6028        } finally {
6029            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6030        }
6031    }
6032
6033    /**
6034     *  Scans a package and returns the newly parsed package.
6035     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6036     */
6037    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6038            long currentTime, UserHandle user) throws PackageManagerException {
6039        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6040        parseFlags |= mDefParseFlags;
6041        PackageParser pp = new PackageParser();
6042        pp.setSeparateProcesses(mSeparateProcesses);
6043        pp.setOnlyCoreApps(mOnlyCore);
6044        pp.setDisplayMetrics(mMetrics);
6045
6046        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6047            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6048        }
6049
6050        final PackageParser.Package pkg;
6051        try {
6052            pkg = pp.parsePackage(scanFile, parseFlags);
6053        } catch (PackageParserException e) {
6054            throw PackageManagerException.from(e);
6055        }
6056
6057        PackageSetting ps = null;
6058        PackageSetting updatedPkg;
6059        // reader
6060        synchronized (mPackages) {
6061            // Look to see if we already know about this package.
6062            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6063            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6064                // This package has been renamed to its original name.  Let's
6065                // use that.
6066                ps = mSettings.peekPackageLPr(oldName);
6067            }
6068            // If there was no original package, see one for the real package name.
6069            if (ps == null) {
6070                ps = mSettings.peekPackageLPr(pkg.packageName);
6071            }
6072            // Check to see if this package could be hiding/updating a system
6073            // package.  Must look for it either under the original or real
6074            // package name depending on our state.
6075            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6076            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6077        }
6078        boolean updatedPkgBetter = false;
6079        // First check if this is a system package that may involve an update
6080        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6081            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6082            // it needs to drop FLAG_PRIVILEGED.
6083            if (locationIsPrivileged(scanFile)) {
6084                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6085            } else {
6086                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6087            }
6088
6089            if (ps != null && !ps.codePath.equals(scanFile)) {
6090                // The path has changed from what was last scanned...  check the
6091                // version of the new path against what we have stored to determine
6092                // what to do.
6093                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6094                if (pkg.mVersionCode <= ps.versionCode) {
6095                    // The system package has been updated and the code path does not match
6096                    // Ignore entry. Skip it.
6097                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6098                            + " ignored: updated version " + ps.versionCode
6099                            + " better than this " + pkg.mVersionCode);
6100                    if (!updatedPkg.codePath.equals(scanFile)) {
6101                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
6102                                + ps.name + " changing from " + updatedPkg.codePathString
6103                                + " to " + scanFile);
6104                        updatedPkg.codePath = scanFile;
6105                        updatedPkg.codePathString = scanFile.toString();
6106                        updatedPkg.resourcePath = scanFile;
6107                        updatedPkg.resourcePathString = scanFile.toString();
6108                    }
6109                    updatedPkg.pkg = pkg;
6110                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6111                            "Package " + ps.name + " at " + scanFile
6112                                    + " ignored: updated version " + ps.versionCode
6113                                    + " better than this " + pkg.mVersionCode);
6114                } else {
6115                    // The current app on the system partition is better than
6116                    // what we have updated to on the data partition; switch
6117                    // back to the system partition version.
6118                    // At this point, its safely assumed that package installation for
6119                    // apps in system partition will go through. If not there won't be a working
6120                    // version of the app
6121                    // writer
6122                    synchronized (mPackages) {
6123                        // Just remove the loaded entries from package lists.
6124                        mPackages.remove(ps.name);
6125                    }
6126
6127                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6128                            + " reverting from " + ps.codePathString
6129                            + ": new version " + pkg.mVersionCode
6130                            + " better than installed " + ps.versionCode);
6131
6132                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6133                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6134                    synchronized (mInstallLock) {
6135                        args.cleanUpResourcesLI();
6136                    }
6137                    synchronized (mPackages) {
6138                        mSettings.enableSystemPackageLPw(ps.name);
6139                    }
6140                    updatedPkgBetter = true;
6141                }
6142            }
6143        }
6144
6145        if (updatedPkg != null) {
6146            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6147            // initially
6148            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
6149
6150            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6151            // flag set initially
6152            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6153                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6154            }
6155        }
6156
6157        // Verify certificates against what was last scanned
6158        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
6159
6160        /*
6161         * A new system app appeared, but we already had a non-system one of the
6162         * same name installed earlier.
6163         */
6164        boolean shouldHideSystemApp = false;
6165        if (updatedPkg == null && ps != null
6166                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6167            /*
6168             * Check to make sure the signatures match first. If they don't,
6169             * wipe the installed application and its data.
6170             */
6171            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6172                    != PackageManager.SIGNATURE_MATCH) {
6173                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6174                        + " signatures don't match existing userdata copy; removing");
6175                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
6176                ps = null;
6177            } else {
6178                /*
6179                 * If the newly-added system app is an older version than the
6180                 * already installed version, hide it. It will be scanned later
6181                 * and re-added like an update.
6182                 */
6183                if (pkg.mVersionCode <= ps.versionCode) {
6184                    shouldHideSystemApp = true;
6185                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6186                            + " but new version " + pkg.mVersionCode + " better than installed "
6187                            + ps.versionCode + "; hiding system");
6188                } else {
6189                    /*
6190                     * The newly found system app is a newer version that the
6191                     * one previously installed. Simply remove the
6192                     * already-installed application and replace it with our own
6193                     * while keeping the application data.
6194                     */
6195                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6196                            + " reverting from " + ps.codePathString + ": new version "
6197                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6198                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6199                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6200                    synchronized (mInstallLock) {
6201                        args.cleanUpResourcesLI();
6202                    }
6203                }
6204            }
6205        }
6206
6207        // The apk is forward locked (not public) if its code and resources
6208        // are kept in different files. (except for app in either system or
6209        // vendor path).
6210        // TODO grab this value from PackageSettings
6211        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6212            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6213                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
6214            }
6215        }
6216
6217        // TODO: extend to support forward-locked splits
6218        String resourcePath = null;
6219        String baseResourcePath = null;
6220        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6221            if (ps != null && ps.resourcePathString != null) {
6222                resourcePath = ps.resourcePathString;
6223                baseResourcePath = ps.resourcePathString;
6224            } else {
6225                // Should not happen at all. Just log an error.
6226                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
6227            }
6228        } else {
6229            resourcePath = pkg.codePath;
6230            baseResourcePath = pkg.baseCodePath;
6231        }
6232
6233        // Set application objects path explicitly.
6234        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
6235        pkg.applicationInfo.setCodePath(pkg.codePath);
6236        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
6237        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
6238        pkg.applicationInfo.setResourcePath(resourcePath);
6239        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
6240        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
6241
6242        // Note that we invoke the following method only if we are about to unpack an application
6243        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6244                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6245
6246        /*
6247         * If the system app should be overridden by a previously installed
6248         * data, hide the system app now and let the /data/app scan pick it up
6249         * again.
6250         */
6251        if (shouldHideSystemApp) {
6252            synchronized (mPackages) {
6253                mSettings.disableSystemPackageLPw(pkg.packageName);
6254            }
6255        }
6256
6257        return scannedPkg;
6258    }
6259
6260    private static String fixProcessName(String defProcessName,
6261            String processName, int uid) {
6262        if (processName == null) {
6263            return defProcessName;
6264        }
6265        return processName;
6266    }
6267
6268    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6269            throws PackageManagerException {
6270        if (pkgSetting.signatures.mSignatures != null) {
6271            // Already existing package. Make sure signatures match
6272            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6273                    == PackageManager.SIGNATURE_MATCH;
6274            if (!match) {
6275                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6276                        == PackageManager.SIGNATURE_MATCH;
6277            }
6278            if (!match) {
6279                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6280                        == PackageManager.SIGNATURE_MATCH;
6281            }
6282            if (!match) {
6283                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6284                        + pkg.packageName + " signatures do not match the "
6285                        + "previously installed version; ignoring!");
6286            }
6287        }
6288
6289        // Check for shared user signatures
6290        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6291            // Already existing package. Make sure signatures match
6292            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6293                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6294            if (!match) {
6295                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6296                        == PackageManager.SIGNATURE_MATCH;
6297            }
6298            if (!match) {
6299                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6300                        == PackageManager.SIGNATURE_MATCH;
6301            }
6302            if (!match) {
6303                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6304                        "Package " + pkg.packageName
6305                        + " has no signatures that match those in shared user "
6306                        + pkgSetting.sharedUser.name + "; ignoring!");
6307            }
6308        }
6309    }
6310
6311    /**
6312     * Enforces that only the system UID or root's UID can call a method exposed
6313     * via Binder.
6314     *
6315     * @param message used as message if SecurityException is thrown
6316     * @throws SecurityException if the caller is not system or root
6317     */
6318    private static final void enforceSystemOrRoot(String message) {
6319        final int uid = Binder.getCallingUid();
6320        if (uid != Process.SYSTEM_UID && uid != 0) {
6321            throw new SecurityException(message);
6322        }
6323    }
6324
6325    @Override
6326    public void performFstrimIfNeeded() {
6327        enforceSystemOrRoot("Only the system can request fstrim");
6328
6329        // Before everything else, see whether we need to fstrim.
6330        try {
6331            IMountService ms = PackageHelper.getMountService();
6332            if (ms != null) {
6333                final boolean isUpgrade = isUpgrade();
6334                boolean doTrim = isUpgrade;
6335                if (doTrim) {
6336                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6337                } else {
6338                    final long interval = android.provider.Settings.Global.getLong(
6339                            mContext.getContentResolver(),
6340                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6341                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6342                    if (interval > 0) {
6343                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6344                        if (timeSinceLast > interval) {
6345                            doTrim = true;
6346                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6347                                    + "; running immediately");
6348                        }
6349                    }
6350                }
6351                if (doTrim) {
6352                    if (!isFirstBoot()) {
6353                        try {
6354                            ActivityManagerNative.getDefault().showBootMessage(
6355                                    mContext.getResources().getString(
6356                                            R.string.android_upgrading_fstrim), true);
6357                        } catch (RemoteException e) {
6358                        }
6359                    }
6360                    ms.runMaintenance();
6361                }
6362            } else {
6363                Slog.e(TAG, "Mount service unavailable!");
6364            }
6365        } catch (RemoteException e) {
6366            // Can't happen; MountService is local
6367        }
6368    }
6369
6370    private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) {
6371        List<ResolveInfo> ris = null;
6372        try {
6373            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6374                    intent, null, 0, userId);
6375        } catch (RemoteException e) {
6376        }
6377        ArraySet<String> pkgNames = new ArraySet<String>();
6378        if (ris != null) {
6379            for (ResolveInfo ri : ris) {
6380                pkgNames.add(ri.activityInfo.packageName);
6381            }
6382        }
6383        return pkgNames;
6384    }
6385
6386    @Override
6387    public void notifyPackageUse(String packageName) {
6388        synchronized (mPackages) {
6389            PackageParser.Package p = mPackages.get(packageName);
6390            if (p == null) {
6391                return;
6392            }
6393            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6394        }
6395    }
6396
6397    @Override
6398    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6399        return performDexOptTraced(packageName, instructionSet);
6400    }
6401
6402    public boolean performDexOpt(String packageName, String instructionSet) {
6403        return performDexOptTraced(packageName, instructionSet);
6404    }
6405
6406    private boolean performDexOptTraced(String packageName, String instructionSet) {
6407        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6408        try {
6409            return performDexOptInternal(packageName, instructionSet);
6410        } finally {
6411            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6412        }
6413    }
6414
6415    private boolean performDexOptInternal(String packageName, String instructionSet) {
6416        PackageParser.Package p;
6417        final String targetInstructionSet;
6418        synchronized (mPackages) {
6419            p = mPackages.get(packageName);
6420            if (p == null) {
6421                return false;
6422            }
6423            mPackageUsage.write(false);
6424
6425            targetInstructionSet = instructionSet != null ? instructionSet :
6426                    getPrimaryInstructionSet(p.applicationInfo);
6427            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6428                return false;
6429            }
6430        }
6431        long callingId = Binder.clearCallingIdentity();
6432        try {
6433            synchronized (mInstallLock) {
6434                final String[] instructionSets = new String[] { targetInstructionSet };
6435                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6436                        true /* inclDependencies */);
6437                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6438            }
6439        } finally {
6440            Binder.restoreCallingIdentity(callingId);
6441        }
6442    }
6443
6444    public ArraySet<String> getPackagesThatNeedDexOpt() {
6445        ArraySet<String> pkgs = null;
6446        synchronized (mPackages) {
6447            for (PackageParser.Package p : mPackages.values()) {
6448                if (DEBUG_DEXOPT) {
6449                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6450                }
6451                if (!p.mDexOptPerformed.isEmpty()) {
6452                    continue;
6453                }
6454                if (pkgs == null) {
6455                    pkgs = new ArraySet<String>();
6456                }
6457                pkgs.add(p.packageName);
6458            }
6459        }
6460        return pkgs;
6461    }
6462
6463    public void shutdown() {
6464        mPackageUsage.write(true);
6465    }
6466
6467    @Override
6468    public void forceDexOpt(String packageName) {
6469        enforceSystemOrRoot("forceDexOpt");
6470
6471        PackageParser.Package pkg;
6472        synchronized (mPackages) {
6473            pkg = mPackages.get(packageName);
6474            if (pkg == null) {
6475                throw new IllegalArgumentException("Missing package: " + packageName);
6476            }
6477        }
6478
6479        synchronized (mInstallLock) {
6480            final String[] instructionSets = new String[] {
6481                    getPrimaryInstructionSet(pkg.applicationInfo) };
6482
6483            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6484
6485            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6486                    true /* inclDependencies */);
6487
6488            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6489            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6490                throw new IllegalStateException("Failed to dexopt: " + res);
6491            }
6492        }
6493    }
6494
6495    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6496        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6497            Slog.w(TAG, "Unable to update from " + oldPkg.name
6498                    + " to " + newPkg.packageName
6499                    + ": old package not in system partition");
6500            return false;
6501        } else if (mPackages.get(oldPkg.name) != null) {
6502            Slog.w(TAG, "Unable to update from " + oldPkg.name
6503                    + " to " + newPkg.packageName
6504                    + ": old package still exists");
6505            return false;
6506        }
6507        return true;
6508    }
6509
6510    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6511        int[] users = sUserManager.getUserIds();
6512        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6513        if (res < 0) {
6514            return res;
6515        }
6516        for (int user : users) {
6517            if (user != 0) {
6518                res = mInstaller.createUserData(volumeUuid, packageName,
6519                        UserHandle.getUid(user, uid), user, seinfo);
6520                if (res < 0) {
6521                    return res;
6522                }
6523            }
6524        }
6525        return res;
6526    }
6527
6528    private int removeDataDirsLI(String volumeUuid, String packageName) {
6529        int[] users = sUserManager.getUserIds();
6530        int res = 0;
6531        for (int user : users) {
6532            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6533            if (resInner < 0) {
6534                res = resInner;
6535            }
6536        }
6537
6538        return res;
6539    }
6540
6541    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6542        int[] users = sUserManager.getUserIds();
6543        int res = 0;
6544        for (int user : users) {
6545            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6546            if (resInner < 0) {
6547                res = resInner;
6548            }
6549        }
6550        return res;
6551    }
6552
6553    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6554            PackageParser.Package changingLib) {
6555        if (file.path != null) {
6556            usesLibraryFiles.add(file.path);
6557            return;
6558        }
6559        PackageParser.Package p = mPackages.get(file.apk);
6560        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6561            // If we are doing this while in the middle of updating a library apk,
6562            // then we need to make sure to use that new apk for determining the
6563            // dependencies here.  (We haven't yet finished committing the new apk
6564            // to the package manager state.)
6565            if (p == null || p.packageName.equals(changingLib.packageName)) {
6566                p = changingLib;
6567            }
6568        }
6569        if (p != null) {
6570            usesLibraryFiles.addAll(p.getAllCodePaths());
6571        }
6572    }
6573
6574    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6575            PackageParser.Package changingLib) throws PackageManagerException {
6576        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6577            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6578            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6579            for (int i=0; i<N; i++) {
6580                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6581                if (file == null) {
6582                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6583                            "Package " + pkg.packageName + " requires unavailable shared library "
6584                            + pkg.usesLibraries.get(i) + "; failing!");
6585                }
6586                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6587            }
6588            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6589            for (int i=0; i<N; i++) {
6590                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6591                if (file == null) {
6592                    Slog.w(TAG, "Package " + pkg.packageName
6593                            + " desires unavailable shared library "
6594                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6595                } else {
6596                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6597                }
6598            }
6599            N = usesLibraryFiles.size();
6600            if (N > 0) {
6601                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6602            } else {
6603                pkg.usesLibraryFiles = null;
6604            }
6605        }
6606    }
6607
6608    private static boolean hasString(List<String> list, List<String> which) {
6609        if (list == null) {
6610            return false;
6611        }
6612        for (int i=list.size()-1; i>=0; i--) {
6613            for (int j=which.size()-1; j>=0; j--) {
6614                if (which.get(j).equals(list.get(i))) {
6615                    return true;
6616                }
6617            }
6618        }
6619        return false;
6620    }
6621
6622    private void updateAllSharedLibrariesLPw() {
6623        for (PackageParser.Package pkg : mPackages.values()) {
6624            try {
6625                updateSharedLibrariesLPw(pkg, null);
6626            } catch (PackageManagerException e) {
6627                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6628            }
6629        }
6630    }
6631
6632    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6633            PackageParser.Package changingPkg) {
6634        ArrayList<PackageParser.Package> res = null;
6635        for (PackageParser.Package pkg : mPackages.values()) {
6636            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6637                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6638                if (res == null) {
6639                    res = new ArrayList<PackageParser.Package>();
6640                }
6641                res.add(pkg);
6642                try {
6643                    updateSharedLibrariesLPw(pkg, changingPkg);
6644                } catch (PackageManagerException e) {
6645                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6646                }
6647            }
6648        }
6649        return res;
6650    }
6651
6652    /**
6653     * Derive the value of the {@code cpuAbiOverride} based on the provided
6654     * value and an optional stored value from the package settings.
6655     */
6656    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6657        String cpuAbiOverride = null;
6658
6659        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6660            cpuAbiOverride = null;
6661        } else if (abiOverride != null) {
6662            cpuAbiOverride = abiOverride;
6663        } else if (settings != null) {
6664            cpuAbiOverride = settings.cpuAbiOverrideString;
6665        }
6666
6667        return cpuAbiOverride;
6668    }
6669
6670    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
6671            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6672        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6673        try {
6674            return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
6675        } finally {
6676            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6677        }
6678    }
6679
6680    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6681            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6682        boolean success = false;
6683        try {
6684            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6685                    currentTime, user);
6686            success = true;
6687            return res;
6688        } finally {
6689            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6690                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6691            }
6692        }
6693    }
6694
6695    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6696            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6697        final File scanFile = new File(pkg.codePath);
6698        if (pkg.applicationInfo.getCodePath() == null ||
6699                pkg.applicationInfo.getResourcePath() == null) {
6700            // Bail out. The resource and code paths haven't been set.
6701            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6702                    "Code and resource paths haven't been set correctly");
6703        }
6704
6705        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6706            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6707        } else {
6708            // Only allow system apps to be flagged as core apps.
6709            pkg.coreApp = false;
6710        }
6711
6712        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6713            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6714        }
6715
6716        if (mCustomResolverComponentName != null &&
6717                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6718            setUpCustomResolverActivity(pkg);
6719        }
6720
6721        if (pkg.packageName.equals("android")) {
6722            synchronized (mPackages) {
6723                if (mAndroidApplication != null) {
6724                    Slog.w(TAG, "*************************************************");
6725                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6726                    Slog.w(TAG, " file=" + scanFile);
6727                    Slog.w(TAG, "*************************************************");
6728                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6729                            "Core android package being redefined.  Skipping.");
6730                }
6731
6732                // Set up information for our fall-back user intent resolution activity.
6733                mPlatformPackage = pkg;
6734                pkg.mVersionCode = mSdkVersion;
6735                mAndroidApplication = pkg.applicationInfo;
6736
6737                if (!mResolverReplaced) {
6738                    mResolveActivity.applicationInfo = mAndroidApplication;
6739                    mResolveActivity.name = ResolverActivity.class.getName();
6740                    mResolveActivity.packageName = mAndroidApplication.packageName;
6741                    mResolveActivity.processName = "system:ui";
6742                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6743                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6744                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6745                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6746                    mResolveActivity.exported = true;
6747                    mResolveActivity.enabled = true;
6748                    mResolveInfo.activityInfo = mResolveActivity;
6749                    mResolveInfo.priority = 0;
6750                    mResolveInfo.preferredOrder = 0;
6751                    mResolveInfo.match = 0;
6752                    mResolveComponentName = new ComponentName(
6753                            mAndroidApplication.packageName, mResolveActivity.name);
6754                }
6755            }
6756        }
6757
6758        if (DEBUG_PACKAGE_SCANNING) {
6759            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6760                Log.d(TAG, "Scanning package " + pkg.packageName);
6761        }
6762
6763        if (mPackages.containsKey(pkg.packageName)
6764                || mSharedLibraries.containsKey(pkg.packageName)) {
6765            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6766                    "Application package " + pkg.packageName
6767                    + " already installed.  Skipping duplicate.");
6768        }
6769
6770        // If we're only installing presumed-existing packages, require that the
6771        // scanned APK is both already known and at the path previously established
6772        // for it.  Previously unknown packages we pick up normally, but if we have an
6773        // a priori expectation about this package's install presence, enforce it.
6774        // With a singular exception for new system packages. When an OTA contains
6775        // a new system package, we allow the codepath to change from a system location
6776        // to the user-installed location. If we don't allow this change, any newer,
6777        // user-installed version of the application will be ignored.
6778        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6779            if (mExpectingBetter.containsKey(pkg.packageName)) {
6780                logCriticalInfo(Log.WARN,
6781                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6782            } else {
6783                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6784                if (known != null) {
6785                    if (DEBUG_PACKAGE_SCANNING) {
6786                        Log.d(TAG, "Examining " + pkg.codePath
6787                                + " and requiring known paths " + known.codePathString
6788                                + " & " + known.resourcePathString);
6789                    }
6790                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6791                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6792                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6793                                "Application package " + pkg.packageName
6794                                + " found at " + pkg.applicationInfo.getCodePath()
6795                                + " but expected at " + known.codePathString + "; ignoring.");
6796                    }
6797                }
6798            }
6799        }
6800
6801        // Initialize package source and resource directories
6802        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6803        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6804
6805        SharedUserSetting suid = null;
6806        PackageSetting pkgSetting = null;
6807
6808        if (!isSystemApp(pkg)) {
6809            // Only system apps can use these features.
6810            pkg.mOriginalPackages = null;
6811            pkg.mRealPackage = null;
6812            pkg.mAdoptPermissions = null;
6813        }
6814
6815        // writer
6816        synchronized (mPackages) {
6817            if (pkg.mSharedUserId != null) {
6818                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6819                if (suid == null) {
6820                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6821                            "Creating application package " + pkg.packageName
6822                            + " for shared user failed");
6823                }
6824                if (DEBUG_PACKAGE_SCANNING) {
6825                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6826                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6827                                + "): packages=" + suid.packages);
6828                }
6829            }
6830
6831            // Check if we are renaming from an original package name.
6832            PackageSetting origPackage = null;
6833            String realName = null;
6834            if (pkg.mOriginalPackages != null) {
6835                // This package may need to be renamed to a previously
6836                // installed name.  Let's check on that...
6837                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6838                if (pkg.mOriginalPackages.contains(renamed)) {
6839                    // This package had originally been installed as the
6840                    // original name, and we have already taken care of
6841                    // transitioning to the new one.  Just update the new
6842                    // one to continue using the old name.
6843                    realName = pkg.mRealPackage;
6844                    if (!pkg.packageName.equals(renamed)) {
6845                        // Callers into this function may have already taken
6846                        // care of renaming the package; only do it here if
6847                        // it is not already done.
6848                        pkg.setPackageName(renamed);
6849                    }
6850
6851                } else {
6852                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6853                        if ((origPackage = mSettings.peekPackageLPr(
6854                                pkg.mOriginalPackages.get(i))) != null) {
6855                            // We do have the package already installed under its
6856                            // original name...  should we use it?
6857                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6858                                // New package is not compatible with original.
6859                                origPackage = null;
6860                                continue;
6861                            } else if (origPackage.sharedUser != null) {
6862                                // Make sure uid is compatible between packages.
6863                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6864                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6865                                            + " to " + pkg.packageName + ": old uid "
6866                                            + origPackage.sharedUser.name
6867                                            + " differs from " + pkg.mSharedUserId);
6868                                    origPackage = null;
6869                                    continue;
6870                                }
6871                            } else {
6872                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6873                                        + pkg.packageName + " to old name " + origPackage.name);
6874                            }
6875                            break;
6876                        }
6877                    }
6878                }
6879            }
6880
6881            if (mTransferedPackages.contains(pkg.packageName)) {
6882                Slog.w(TAG, "Package " + pkg.packageName
6883                        + " was transferred to another, but its .apk remains");
6884            }
6885
6886            // Just create the setting, don't add it yet. For already existing packages
6887            // the PkgSetting exists already and doesn't have to be created.
6888            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6889                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6890                    pkg.applicationInfo.primaryCpuAbi,
6891                    pkg.applicationInfo.secondaryCpuAbi,
6892                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6893                    user, false);
6894            if (pkgSetting == null) {
6895                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6896                        "Creating application package " + pkg.packageName + " failed");
6897            }
6898
6899            if (pkgSetting.origPackage != null) {
6900                // If we are first transitioning from an original package,
6901                // fix up the new package's name now.  We need to do this after
6902                // looking up the package under its new name, so getPackageLP
6903                // can take care of fiddling things correctly.
6904                pkg.setPackageName(origPackage.name);
6905
6906                // File a report about this.
6907                String msg = "New package " + pkgSetting.realName
6908                        + " renamed to replace old package " + pkgSetting.name;
6909                reportSettingsProblem(Log.WARN, msg);
6910
6911                // Make a note of it.
6912                mTransferedPackages.add(origPackage.name);
6913
6914                // No longer need to retain this.
6915                pkgSetting.origPackage = null;
6916            }
6917
6918            if (realName != null) {
6919                // Make a note of it.
6920                mTransferedPackages.add(pkg.packageName);
6921            }
6922
6923            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6924                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6925            }
6926
6927            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6928                // Check all shared libraries and map to their actual file path.
6929                // We only do this here for apps not on a system dir, because those
6930                // are the only ones that can fail an install due to this.  We
6931                // will take care of the system apps by updating all of their
6932                // library paths after the scan is done.
6933                updateSharedLibrariesLPw(pkg, null);
6934            }
6935
6936            if (mFoundPolicyFile) {
6937                SELinuxMMAC.assignSeinfoValue(pkg);
6938            }
6939
6940            pkg.applicationInfo.uid = pkgSetting.appId;
6941            pkg.mExtras = pkgSetting;
6942            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6943                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6944                    // We just determined the app is signed correctly, so bring
6945                    // over the latest parsed certs.
6946                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6947                } else {
6948                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6949                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6950                                "Package " + pkg.packageName + " upgrade keys do not match the "
6951                                + "previously installed version");
6952                    } else {
6953                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6954                        String msg = "System package " + pkg.packageName
6955                            + " signature changed; retaining data.";
6956                        reportSettingsProblem(Log.WARN, msg);
6957                    }
6958                }
6959            } else {
6960                try {
6961                    verifySignaturesLP(pkgSetting, pkg);
6962                    // We just determined the app is signed correctly, so bring
6963                    // over the latest parsed certs.
6964                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6965                } catch (PackageManagerException e) {
6966                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6967                        throw e;
6968                    }
6969                    // The signature has changed, but this package is in the system
6970                    // image...  let's recover!
6971                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6972                    // However...  if this package is part of a shared user, but it
6973                    // doesn't match the signature of the shared user, let's fail.
6974                    // What this means is that you can't change the signatures
6975                    // associated with an overall shared user, which doesn't seem all
6976                    // that unreasonable.
6977                    if (pkgSetting.sharedUser != null) {
6978                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6979                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6980                            throw new PackageManagerException(
6981                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6982                                            "Signature mismatch for shared user : "
6983                                            + pkgSetting.sharedUser);
6984                        }
6985                    }
6986                    // File a report about this.
6987                    String msg = "System package " + pkg.packageName
6988                        + " signature changed; retaining data.";
6989                    reportSettingsProblem(Log.WARN, msg);
6990                }
6991            }
6992            // Verify that this new package doesn't have any content providers
6993            // that conflict with existing packages.  Only do this if the
6994            // package isn't already installed, since we don't want to break
6995            // things that are installed.
6996            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6997                final int N = pkg.providers.size();
6998                int i;
6999                for (i=0; i<N; i++) {
7000                    PackageParser.Provider p = pkg.providers.get(i);
7001                    if (p.info.authority != null) {
7002                        String names[] = p.info.authority.split(";");
7003                        for (int j = 0; j < names.length; j++) {
7004                            if (mProvidersByAuthority.containsKey(names[j])) {
7005                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7006                                final String otherPackageName =
7007                                        ((other != null && other.getComponentName() != null) ?
7008                                                other.getComponentName().getPackageName() : "?");
7009                                throw new PackageManagerException(
7010                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
7011                                                "Can't install because provider name " + names[j]
7012                                                + " (in package " + pkg.applicationInfo.packageName
7013                                                + ") is already used by " + otherPackageName);
7014                            }
7015                        }
7016                    }
7017                }
7018            }
7019
7020            if (pkg.mAdoptPermissions != null) {
7021                // This package wants to adopt ownership of permissions from
7022                // another package.
7023                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
7024                    final String origName = pkg.mAdoptPermissions.get(i);
7025                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
7026                    if (orig != null) {
7027                        if (verifyPackageUpdateLPr(orig, pkg)) {
7028                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
7029                                    + pkg.packageName);
7030                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
7031                        }
7032                    }
7033                }
7034            }
7035        }
7036
7037        final String pkgName = pkg.packageName;
7038
7039        final long scanFileTime = scanFile.lastModified();
7040        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
7041        pkg.applicationInfo.processName = fixProcessName(
7042                pkg.applicationInfo.packageName,
7043                pkg.applicationInfo.processName,
7044                pkg.applicationInfo.uid);
7045
7046        if (pkg != mPlatformPackage) {
7047            // This is a normal package, need to make its data directory.
7048            final File dataPath = Environment.getDataUserCredentialEncryptedPackageDirectory(
7049                    pkg.volumeUuid, UserHandle.USER_SYSTEM, pkg.packageName);
7050
7051            boolean uidError = false;
7052            if (dataPath.exists()) {
7053                int currentUid = 0;
7054                try {
7055                    StructStat stat = Os.stat(dataPath.getPath());
7056                    currentUid = stat.st_uid;
7057                } catch (ErrnoException e) {
7058                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
7059                }
7060
7061                // If we have mismatched owners for the data path, we have a problem.
7062                if (currentUid != pkg.applicationInfo.uid) {
7063                    boolean recovered = false;
7064                    if (currentUid == 0) {
7065                        // The directory somehow became owned by root.  Wow.
7066                        // This is probably because the system was stopped while
7067                        // installd was in the middle of messing with its libs
7068                        // directory.  Ask installd to fix that.
7069                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
7070                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
7071                        if (ret >= 0) {
7072                            recovered = true;
7073                            String msg = "Package " + pkg.packageName
7074                                    + " unexpectedly changed to uid 0; recovered to " +
7075                                    + pkg.applicationInfo.uid;
7076                            reportSettingsProblem(Log.WARN, msg);
7077                        }
7078                    }
7079                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
7080                            || (scanFlags&SCAN_BOOTING) != 0)) {
7081                        // If this is a system app, we can at least delete its
7082                        // current data so the application will still work.
7083                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
7084                        if (ret >= 0) {
7085                            // TODO: Kill the processes first
7086                            // Old data gone!
7087                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
7088                                    ? "System package " : "Third party package ";
7089                            String msg = prefix + pkg.packageName
7090                                    + " has changed from uid: "
7091                                    + currentUid + " to "
7092                                    + pkg.applicationInfo.uid + "; old data erased";
7093                            reportSettingsProblem(Log.WARN, msg);
7094                            recovered = true;
7095
7096                            // And now re-install the app.
7097                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7098                                    pkg.applicationInfo.seinfo);
7099                            if (ret == -1) {
7100                                // Ack should not happen!
7101                                msg = prefix + pkg.packageName
7102                                        + " could not have data directory re-created after delete.";
7103                                reportSettingsProblem(Log.WARN, msg);
7104                                throw new PackageManagerException(
7105                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
7106                            }
7107                        }
7108                        if (!recovered) {
7109                            mHasSystemUidErrors = true;
7110                        }
7111                    } else if (!recovered) {
7112                        // If we allow this install to proceed, we will be broken.
7113                        // Abort, abort!
7114                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
7115                                "scanPackageLI");
7116                    }
7117                    if (!recovered) {
7118                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
7119                            + pkg.applicationInfo.uid + "/fs_"
7120                            + currentUid;
7121                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
7122                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
7123                        String msg = "Package " + pkg.packageName
7124                                + " has mismatched uid: "
7125                                + currentUid + " on disk, "
7126                                + pkg.applicationInfo.uid + " in settings";
7127                        // writer
7128                        synchronized (mPackages) {
7129                            mSettings.mReadMessages.append(msg);
7130                            mSettings.mReadMessages.append('\n');
7131                            uidError = true;
7132                            if (!pkgSetting.uidError) {
7133                                reportSettingsProblem(Log.ERROR, msg);
7134                            }
7135                        }
7136                    }
7137                }
7138
7139                if (mShouldRestoreconData) {
7140                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
7141                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
7142                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
7143                }
7144            } else {
7145                if (DEBUG_PACKAGE_SCANNING) {
7146                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7147                        Log.v(TAG, "Want this data dir: " + dataPath);
7148                }
7149                //invoke installer to do the actual installation
7150                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7151                        pkg.applicationInfo.seinfo);
7152                if (ret < 0) {
7153                    // Error from installer
7154                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7155                            "Unable to create data dirs [errorCode=" + ret + "]");
7156                }
7157            }
7158
7159            // Get all of our default paths setup
7160            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
7161
7162            pkgSetting.uidError = uidError;
7163        }
7164
7165        final String path = scanFile.getPath();
7166        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7167
7168        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7169            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7170
7171            // Some system apps still use directory structure for native libraries
7172            // in which case we might end up not detecting abi solely based on apk
7173            // structure. Try to detect abi based on directory structure.
7174            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7175                    pkg.applicationInfo.primaryCpuAbi == null) {
7176                setBundledAppAbisAndRoots(pkg, pkgSetting);
7177                setNativeLibraryPaths(pkg);
7178            }
7179
7180        } else {
7181            if ((scanFlags & SCAN_MOVE) != 0) {
7182                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7183                // but we already have this packages package info in the PackageSetting. We just
7184                // use that and derive the native library path based on the new codepath.
7185                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7186                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7187            }
7188
7189            // Set native library paths again. For moves, the path will be updated based on the
7190            // ABIs we've determined above. For non-moves, the path will be updated based on the
7191            // ABIs we determined during compilation, but the path will depend on the final
7192            // package path (after the rename away from the stage path).
7193            setNativeLibraryPaths(pkg);
7194        }
7195
7196        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
7197        final int[] userIds = sUserManager.getUserIds();
7198        synchronized (mInstallLock) {
7199            // Make sure all user data directories are ready to roll; we're okay
7200            // if they already exist
7201            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
7202                for (int userId : userIds) {
7203                    if (userId != UserHandle.USER_SYSTEM) {
7204                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
7205                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
7206                                pkg.applicationInfo.seinfo);
7207                    }
7208                }
7209            }
7210
7211            // Create a native library symlink only if we have native libraries
7212            // and if the native libraries are 32 bit libraries. We do not provide
7213            // this symlink for 64 bit libraries.
7214            if (pkg.applicationInfo.primaryCpuAbi != null &&
7215                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
7216                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib");
7217                try {
7218                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
7219                    for (int userId : userIds) {
7220                        if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
7221                                nativeLibPath, userId) < 0) {
7222                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7223                                    "Failed linking native library dir (user=" + userId + ")");
7224                        }
7225                    }
7226                } finally {
7227                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7228                }
7229            }
7230        }
7231
7232        // This is a special case for the "system" package, where the ABI is
7233        // dictated by the zygote configuration (and init.rc). We should keep track
7234        // of this ABI so that we can deal with "normal" applications that run under
7235        // the same UID correctly.
7236        if (mPlatformPackage == pkg) {
7237            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7238                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7239        }
7240
7241        // If there's a mismatch between the abi-override in the package setting
7242        // and the abiOverride specified for the install. Warn about this because we
7243        // would've already compiled the app without taking the package setting into
7244        // account.
7245        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7246            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7247                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7248                        " for package: " + pkg.packageName);
7249            }
7250        }
7251
7252        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7253        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7254        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7255
7256        // Copy the derived override back to the parsed package, so that we can
7257        // update the package settings accordingly.
7258        pkg.cpuAbiOverride = cpuAbiOverride;
7259
7260        if (DEBUG_ABI_SELECTION) {
7261            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7262                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7263                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7264        }
7265
7266        // Push the derived path down into PackageSettings so we know what to
7267        // clean up at uninstall time.
7268        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7269
7270        if (DEBUG_ABI_SELECTION) {
7271            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7272                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7273                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7274        }
7275
7276        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7277            // We don't do this here during boot because we can do it all
7278            // at once after scanning all existing packages.
7279            //
7280            // We also do this *before* we perform dexopt on this package, so that
7281            // we can avoid redundant dexopts, and also to make sure we've got the
7282            // code and package path correct.
7283            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7284                    pkg, true /* boot complete */);
7285        }
7286
7287        if (mFactoryTest && pkg.requestedPermissions.contains(
7288                android.Manifest.permission.FACTORY_TEST)) {
7289            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7290        }
7291
7292        ArrayList<PackageParser.Package> clientLibPkgs = null;
7293
7294        // writer
7295        synchronized (mPackages) {
7296            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7297                // Only system apps can add new shared libraries.
7298                if (pkg.libraryNames != null) {
7299                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7300                        String name = pkg.libraryNames.get(i);
7301                        boolean allowed = false;
7302                        if (pkg.isUpdatedSystemApp()) {
7303                            // New library entries can only be added through the
7304                            // system image.  This is important to get rid of a lot
7305                            // of nasty edge cases: for example if we allowed a non-
7306                            // system update of the app to add a library, then uninstalling
7307                            // the update would make the library go away, and assumptions
7308                            // we made such as through app install filtering would now
7309                            // have allowed apps on the device which aren't compatible
7310                            // with it.  Better to just have the restriction here, be
7311                            // conservative, and create many fewer cases that can negatively
7312                            // impact the user experience.
7313                            final PackageSetting sysPs = mSettings
7314                                    .getDisabledSystemPkgLPr(pkg.packageName);
7315                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7316                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7317                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7318                                        allowed = true;
7319                                        break;
7320                                    }
7321                                }
7322                            }
7323                        } else {
7324                            allowed = true;
7325                        }
7326                        if (allowed) {
7327                            if (!mSharedLibraries.containsKey(name)) {
7328                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7329                            } else if (!name.equals(pkg.packageName)) {
7330                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7331                                        + name + " already exists; skipping");
7332                            }
7333                        } else {
7334                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7335                                    + name + " that is not declared on system image; skipping");
7336                        }
7337                    }
7338                    if ((scanFlags & SCAN_BOOTING) == 0) {
7339                        // If we are not booting, we need to update any applications
7340                        // that are clients of our shared library.  If we are booting,
7341                        // this will all be done once the scan is complete.
7342                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7343                    }
7344                }
7345            }
7346        }
7347
7348        // Request the ActivityManager to kill the process(only for existing packages)
7349        // so that we do not end up in a confused state while the user is still using the older
7350        // version of the application while the new one gets installed.
7351        if ((scanFlags & SCAN_REPLACING) != 0) {
7352            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
7353
7354            killApplication(pkg.applicationInfo.packageName,
7355                        pkg.applicationInfo.uid, "replace pkg");
7356
7357            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7358        }
7359
7360        // Also need to kill any apps that are dependent on the library.
7361        if (clientLibPkgs != null) {
7362            for (int i=0; i<clientLibPkgs.size(); i++) {
7363                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7364                killApplication(clientPkg.applicationInfo.packageName,
7365                        clientPkg.applicationInfo.uid, "update lib");
7366            }
7367        }
7368
7369        // Make sure we're not adding any bogus keyset info
7370        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7371        ksms.assertScannedPackageValid(pkg);
7372
7373        // writer
7374        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
7375
7376        boolean createIdmapFailed = false;
7377        synchronized (mPackages) {
7378            // We don't expect installation to fail beyond this point
7379
7380            // Add the new setting to mSettings
7381            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7382            // Add the new setting to mPackages
7383            mPackages.put(pkg.applicationInfo.packageName, pkg);
7384            // Make sure we don't accidentally delete its data.
7385            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7386            while (iter.hasNext()) {
7387                PackageCleanItem item = iter.next();
7388                if (pkgName.equals(item.packageName)) {
7389                    iter.remove();
7390                }
7391            }
7392
7393            // Take care of first install / last update times.
7394            if (currentTime != 0) {
7395                if (pkgSetting.firstInstallTime == 0) {
7396                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7397                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7398                    pkgSetting.lastUpdateTime = currentTime;
7399                }
7400            } else if (pkgSetting.firstInstallTime == 0) {
7401                // We need *something*.  Take time time stamp of the file.
7402                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7403            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7404                if (scanFileTime != pkgSetting.timeStamp) {
7405                    // A package on the system image has changed; consider this
7406                    // to be an update.
7407                    pkgSetting.lastUpdateTime = scanFileTime;
7408                }
7409            }
7410
7411            // Add the package's KeySets to the global KeySetManagerService
7412            ksms.addScannedPackageLPw(pkg);
7413
7414            int N = pkg.providers.size();
7415            StringBuilder r = null;
7416            int i;
7417            for (i=0; i<N; i++) {
7418                PackageParser.Provider p = pkg.providers.get(i);
7419                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7420                        p.info.processName, pkg.applicationInfo.uid);
7421                mProviders.addProvider(p);
7422                p.syncable = p.info.isSyncable;
7423                if (p.info.authority != null) {
7424                    String names[] = p.info.authority.split(";");
7425                    p.info.authority = null;
7426                    for (int j = 0; j < names.length; j++) {
7427                        if (j == 1 && p.syncable) {
7428                            // We only want the first authority for a provider to possibly be
7429                            // syncable, so if we already added this provider using a different
7430                            // authority clear the syncable flag. We copy the provider before
7431                            // changing it because the mProviders object contains a reference
7432                            // to a provider that we don't want to change.
7433                            // Only do this for the second authority since the resulting provider
7434                            // object can be the same for all future authorities for this provider.
7435                            p = new PackageParser.Provider(p);
7436                            p.syncable = false;
7437                        }
7438                        if (!mProvidersByAuthority.containsKey(names[j])) {
7439                            mProvidersByAuthority.put(names[j], p);
7440                            if (p.info.authority == null) {
7441                                p.info.authority = names[j];
7442                            } else {
7443                                p.info.authority = p.info.authority + ";" + names[j];
7444                            }
7445                            if (DEBUG_PACKAGE_SCANNING) {
7446                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7447                                    Log.d(TAG, "Registered content provider: " + names[j]
7448                                            + ", className = " + p.info.name + ", isSyncable = "
7449                                            + p.info.isSyncable);
7450                            }
7451                        } else {
7452                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7453                            Slog.w(TAG, "Skipping provider name " + names[j] +
7454                                    " (in package " + pkg.applicationInfo.packageName +
7455                                    "): name already used by "
7456                                    + ((other != null && other.getComponentName() != null)
7457                                            ? other.getComponentName().getPackageName() : "?"));
7458                        }
7459                    }
7460                }
7461                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7462                    if (r == null) {
7463                        r = new StringBuilder(256);
7464                    } else {
7465                        r.append(' ');
7466                    }
7467                    r.append(p.info.name);
7468                }
7469            }
7470            if (r != null) {
7471                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7472            }
7473
7474            N = pkg.services.size();
7475            r = null;
7476            for (i=0; i<N; i++) {
7477                PackageParser.Service s = pkg.services.get(i);
7478                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7479                        s.info.processName, pkg.applicationInfo.uid);
7480                mServices.addService(s);
7481                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7482                    if (r == null) {
7483                        r = new StringBuilder(256);
7484                    } else {
7485                        r.append(' ');
7486                    }
7487                    r.append(s.info.name);
7488                }
7489            }
7490            if (r != null) {
7491                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7492            }
7493
7494            N = pkg.receivers.size();
7495            r = null;
7496            for (i=0; i<N; i++) {
7497                PackageParser.Activity a = pkg.receivers.get(i);
7498                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7499                        a.info.processName, pkg.applicationInfo.uid);
7500                mReceivers.addActivity(a, "receiver");
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(a.info.name);
7508                }
7509            }
7510            if (r != null) {
7511                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7512            }
7513
7514            N = pkg.activities.size();
7515            r = null;
7516            for (i=0; i<N; i++) {
7517                PackageParser.Activity a = pkg.activities.get(i);
7518                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7519                        a.info.processName, pkg.applicationInfo.uid);
7520                mActivities.addActivity(a, "activity");
7521                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7522                    if (r == null) {
7523                        r = new StringBuilder(256);
7524                    } else {
7525                        r.append(' ');
7526                    }
7527                    r.append(a.info.name);
7528                }
7529            }
7530            if (r != null) {
7531                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7532            }
7533
7534            N = pkg.permissionGroups.size();
7535            r = null;
7536            for (i=0; i<N; i++) {
7537                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7538                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7539                if (cur == null) {
7540                    mPermissionGroups.put(pg.info.name, pg);
7541                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7542                        if (r == null) {
7543                            r = new StringBuilder(256);
7544                        } else {
7545                            r.append(' ');
7546                        }
7547                        r.append(pg.info.name);
7548                    }
7549                } else {
7550                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7551                            + pg.info.packageName + " ignored: original from "
7552                            + cur.info.packageName);
7553                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7554                        if (r == null) {
7555                            r = new StringBuilder(256);
7556                        } else {
7557                            r.append(' ');
7558                        }
7559                        r.append("DUP:");
7560                        r.append(pg.info.name);
7561                    }
7562                }
7563            }
7564            if (r != null) {
7565                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7566            }
7567
7568            N = pkg.permissions.size();
7569            r = null;
7570            for (i=0; i<N; i++) {
7571                PackageParser.Permission p = pkg.permissions.get(i);
7572
7573                // Assume by default that we did not install this permission into the system.
7574                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7575
7576                // Now that permission groups have a special meaning, we ignore permission
7577                // groups for legacy apps to prevent unexpected behavior. In particular,
7578                // permissions for one app being granted to someone just becuase they happen
7579                // to be in a group defined by another app (before this had no implications).
7580                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7581                    p.group = mPermissionGroups.get(p.info.group);
7582                    // Warn for a permission in an unknown group.
7583                    if (p.info.group != null && p.group == null) {
7584                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7585                                + p.info.packageName + " in an unknown group " + p.info.group);
7586                    }
7587                }
7588
7589                ArrayMap<String, BasePermission> permissionMap =
7590                        p.tree ? mSettings.mPermissionTrees
7591                                : mSettings.mPermissions;
7592                BasePermission bp = permissionMap.get(p.info.name);
7593
7594                // Allow system apps to redefine non-system permissions
7595                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7596                    final boolean currentOwnerIsSystem = (bp.perm != null
7597                            && isSystemApp(bp.perm.owner));
7598                    if (isSystemApp(p.owner)) {
7599                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7600                            // It's a built-in permission and no owner, take ownership now
7601                            bp.packageSetting = pkgSetting;
7602                            bp.perm = p;
7603                            bp.uid = pkg.applicationInfo.uid;
7604                            bp.sourcePackage = p.info.packageName;
7605                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7606                        } else if (!currentOwnerIsSystem) {
7607                            String msg = "New decl " + p.owner + " of permission  "
7608                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7609                            reportSettingsProblem(Log.WARN, msg);
7610                            bp = null;
7611                        }
7612                    }
7613                }
7614
7615                if (bp == null) {
7616                    bp = new BasePermission(p.info.name, p.info.packageName,
7617                            BasePermission.TYPE_NORMAL);
7618                    permissionMap.put(p.info.name, bp);
7619                }
7620
7621                if (bp.perm == null) {
7622                    if (bp.sourcePackage == null
7623                            || bp.sourcePackage.equals(p.info.packageName)) {
7624                        BasePermission tree = findPermissionTreeLP(p.info.name);
7625                        if (tree == null
7626                                || tree.sourcePackage.equals(p.info.packageName)) {
7627                            bp.packageSetting = pkgSetting;
7628                            bp.perm = p;
7629                            bp.uid = pkg.applicationInfo.uid;
7630                            bp.sourcePackage = p.info.packageName;
7631                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
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(p.info.name);
7639                            }
7640                        } else {
7641                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7642                                    + p.info.packageName + " ignored: base tree "
7643                                    + tree.name + " is from package "
7644                                    + tree.sourcePackage);
7645                        }
7646                    } else {
7647                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7648                                + p.info.packageName + " ignored: original from "
7649                                + bp.sourcePackage);
7650                    }
7651                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7652                    if (r == null) {
7653                        r = new StringBuilder(256);
7654                    } else {
7655                        r.append(' ');
7656                    }
7657                    r.append("DUP:");
7658                    r.append(p.info.name);
7659                }
7660                if (bp.perm == p) {
7661                    bp.protectionLevel = p.info.protectionLevel;
7662                }
7663            }
7664
7665            if (r != null) {
7666                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7667            }
7668
7669            N = pkg.instrumentation.size();
7670            r = null;
7671            for (i=0; i<N; i++) {
7672                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7673                a.info.packageName = pkg.applicationInfo.packageName;
7674                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7675                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7676                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7677                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7678                a.info.dataDir = pkg.applicationInfo.dataDir;
7679                a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir;
7680                a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir;
7681
7682                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7683                // need other information about the application, like the ABI and what not ?
7684                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7685                mInstrumentation.put(a.getComponentName(), a);
7686                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7687                    if (r == null) {
7688                        r = new StringBuilder(256);
7689                    } else {
7690                        r.append(' ');
7691                    }
7692                    r.append(a.info.name);
7693                }
7694            }
7695            if (r != null) {
7696                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7697            }
7698
7699            if (pkg.protectedBroadcasts != null) {
7700                N = pkg.protectedBroadcasts.size();
7701                for (i=0; i<N; i++) {
7702                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7703                }
7704            }
7705
7706            pkgSetting.setTimeStamp(scanFileTime);
7707
7708            // Create idmap files for pairs of (packages, overlay packages).
7709            // Note: "android", ie framework-res.apk, is handled by native layers.
7710            if (pkg.mOverlayTarget != null) {
7711                // This is an overlay package.
7712                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7713                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7714                        mOverlays.put(pkg.mOverlayTarget,
7715                                new ArrayMap<String, PackageParser.Package>());
7716                    }
7717                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7718                    map.put(pkg.packageName, pkg);
7719                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7720                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7721                        createIdmapFailed = true;
7722                    }
7723                }
7724            } else if (mOverlays.containsKey(pkg.packageName) &&
7725                    !pkg.packageName.equals("android")) {
7726                // This is a regular package, with one or more known overlay packages.
7727                createIdmapsForPackageLI(pkg);
7728            }
7729        }
7730
7731        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7732
7733        if (createIdmapFailed) {
7734            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7735                    "scanPackageLI failed to createIdmap");
7736        }
7737        return pkg;
7738    }
7739
7740    /**
7741     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7742     * is derived purely on the basis of the contents of {@code scanFile} and
7743     * {@code cpuAbiOverride}.
7744     *
7745     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7746     */
7747    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7748                                 String cpuAbiOverride, boolean extractLibs)
7749            throws PackageManagerException {
7750        // TODO: We can probably be smarter about this stuff. For installed apps,
7751        // we can calculate this information at install time once and for all. For
7752        // system apps, we can probably assume that this information doesn't change
7753        // after the first boot scan. As things stand, we do lots of unnecessary work.
7754
7755        // Give ourselves some initial paths; we'll come back for another
7756        // pass once we've determined ABI below.
7757        setNativeLibraryPaths(pkg);
7758
7759        // We would never need to extract libs for forward-locked and external packages,
7760        // since the container service will do it for us. We shouldn't attempt to
7761        // extract libs from system app when it was not updated.
7762        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
7763                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
7764            extractLibs = false;
7765        }
7766
7767        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7768        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7769
7770        NativeLibraryHelper.Handle handle = null;
7771        try {
7772            handle = NativeLibraryHelper.Handle.create(pkg);
7773            // TODO(multiArch): This can be null for apps that didn't go through the
7774            // usual installation process. We can calculate it again, like we
7775            // do during install time.
7776            //
7777            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7778            // unnecessary.
7779            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7780
7781            // Null out the abis so that they can be recalculated.
7782            pkg.applicationInfo.primaryCpuAbi = null;
7783            pkg.applicationInfo.secondaryCpuAbi = null;
7784            if (isMultiArch(pkg.applicationInfo)) {
7785                // Warn if we've set an abiOverride for multi-lib packages..
7786                // By definition, we need to copy both 32 and 64 bit libraries for
7787                // such packages.
7788                if (pkg.cpuAbiOverride != null
7789                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7790                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7791                }
7792
7793                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7794                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7795                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7796                    if (extractLibs) {
7797                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7798                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7799                                useIsaSpecificSubdirs);
7800                    } else {
7801                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7802                    }
7803                }
7804
7805                maybeThrowExceptionForMultiArchCopy(
7806                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7807
7808                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7809                    if (extractLibs) {
7810                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7811                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7812                                useIsaSpecificSubdirs);
7813                    } else {
7814                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7815                    }
7816                }
7817
7818                maybeThrowExceptionForMultiArchCopy(
7819                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7820
7821                if (abi64 >= 0) {
7822                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7823                }
7824
7825                if (abi32 >= 0) {
7826                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7827                    if (abi64 >= 0) {
7828                        pkg.applicationInfo.secondaryCpuAbi = abi;
7829                    } else {
7830                        pkg.applicationInfo.primaryCpuAbi = abi;
7831                    }
7832                }
7833            } else {
7834                String[] abiList = (cpuAbiOverride != null) ?
7835                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7836
7837                // Enable gross and lame hacks for apps that are built with old
7838                // SDK tools. We must scan their APKs for renderscript bitcode and
7839                // not launch them if it's present. Don't bother checking on devices
7840                // that don't have 64 bit support.
7841                boolean needsRenderScriptOverride = false;
7842                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7843                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7844                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7845                    needsRenderScriptOverride = true;
7846                }
7847
7848                final int copyRet;
7849                if (extractLibs) {
7850                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7851                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7852                } else {
7853                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7854                }
7855
7856                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7857                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7858                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7859                }
7860
7861                if (copyRet >= 0) {
7862                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7863                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7864                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7865                } else if (needsRenderScriptOverride) {
7866                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7867                }
7868            }
7869        } catch (IOException ioe) {
7870            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7871        } finally {
7872            IoUtils.closeQuietly(handle);
7873        }
7874
7875        // Now that we've calculated the ABIs and determined if it's an internal app,
7876        // we will go ahead and populate the nativeLibraryPath.
7877        setNativeLibraryPaths(pkg);
7878    }
7879
7880    /**
7881     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7882     * i.e, so that all packages can be run inside a single process if required.
7883     *
7884     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7885     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7886     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7887     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7888     * updating a package that belongs to a shared user.
7889     *
7890     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7891     * adds unnecessary complexity.
7892     */
7893    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7894            PackageParser.Package scannedPackage, boolean bootComplete) {
7895        String requiredInstructionSet = null;
7896        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7897            requiredInstructionSet = VMRuntime.getInstructionSet(
7898                     scannedPackage.applicationInfo.primaryCpuAbi);
7899        }
7900
7901        PackageSetting requirer = null;
7902        for (PackageSetting ps : packagesForUser) {
7903            // If packagesForUser contains scannedPackage, we skip it. This will happen
7904            // when scannedPackage is an update of an existing package. Without this check,
7905            // we will never be able to change the ABI of any package belonging to a shared
7906            // user, even if it's compatible with other packages.
7907            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7908                if (ps.primaryCpuAbiString == null) {
7909                    continue;
7910                }
7911
7912                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7913                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7914                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7915                    // this but there's not much we can do.
7916                    String errorMessage = "Instruction set mismatch, "
7917                            + ((requirer == null) ? "[caller]" : requirer)
7918                            + " requires " + requiredInstructionSet + " whereas " + ps
7919                            + " requires " + instructionSet;
7920                    Slog.w(TAG, errorMessage);
7921                }
7922
7923                if (requiredInstructionSet == null) {
7924                    requiredInstructionSet = instructionSet;
7925                    requirer = ps;
7926                }
7927            }
7928        }
7929
7930        if (requiredInstructionSet != null) {
7931            String adjustedAbi;
7932            if (requirer != null) {
7933                // requirer != null implies that either scannedPackage was null or that scannedPackage
7934                // did not require an ABI, in which case we have to adjust scannedPackage to match
7935                // the ABI of the set (which is the same as requirer's ABI)
7936                adjustedAbi = requirer.primaryCpuAbiString;
7937                if (scannedPackage != null) {
7938                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7939                }
7940            } else {
7941                // requirer == null implies that we're updating all ABIs in the set to
7942                // match scannedPackage.
7943                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7944            }
7945
7946            for (PackageSetting ps : packagesForUser) {
7947                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7948                    if (ps.primaryCpuAbiString != null) {
7949                        continue;
7950                    }
7951
7952                    ps.primaryCpuAbiString = adjustedAbi;
7953                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7954                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7955                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7956                        mInstaller.rmdex(ps.codePathString,
7957                                getDexCodeInstructionSet(getPreferredInstructionSet()));
7958                    }
7959                }
7960            }
7961        }
7962    }
7963
7964    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7965        synchronized (mPackages) {
7966            mResolverReplaced = true;
7967            // Set up information for custom user intent resolution activity.
7968            mResolveActivity.applicationInfo = pkg.applicationInfo;
7969            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7970            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7971            mResolveActivity.processName = pkg.applicationInfo.packageName;
7972            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7973            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7974                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7975            mResolveActivity.theme = 0;
7976            mResolveActivity.exported = true;
7977            mResolveActivity.enabled = true;
7978            mResolveInfo.activityInfo = mResolveActivity;
7979            mResolveInfo.priority = 0;
7980            mResolveInfo.preferredOrder = 0;
7981            mResolveInfo.match = 0;
7982            mResolveComponentName = mCustomResolverComponentName;
7983            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7984                    mResolveComponentName);
7985        }
7986    }
7987
7988    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
7989        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
7990
7991        // Set up information for ephemeral installer activity
7992        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
7993        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
7994        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
7995        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
7996        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7997        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7998                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7999        mEphemeralInstallerActivity.theme = 0;
8000        mEphemeralInstallerActivity.exported = true;
8001        mEphemeralInstallerActivity.enabled = true;
8002        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8003        mEphemeralInstallerInfo.priority = 0;
8004        mEphemeralInstallerInfo.preferredOrder = 0;
8005        mEphemeralInstallerInfo.match = 0;
8006
8007        if (DEBUG_EPHEMERAL) {
8008            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8009        }
8010    }
8011
8012    private static String calculateBundledApkRoot(final String codePathString) {
8013        final File codePath = new File(codePathString);
8014        final File codeRoot;
8015        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
8016            codeRoot = Environment.getRootDirectory();
8017        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
8018            codeRoot = Environment.getOemDirectory();
8019        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
8020            codeRoot = Environment.getVendorDirectory();
8021        } else {
8022            // Unrecognized code path; take its top real segment as the apk root:
8023            // e.g. /something/app/blah.apk => /something
8024            try {
8025                File f = codePath.getCanonicalFile();
8026                File parent = f.getParentFile();    // non-null because codePath is a file
8027                File tmp;
8028                while ((tmp = parent.getParentFile()) != null) {
8029                    f = parent;
8030                    parent = tmp;
8031                }
8032                codeRoot = f;
8033                Slog.w(TAG, "Unrecognized code path "
8034                        + codePath + " - using " + codeRoot);
8035            } catch (IOException e) {
8036                // Can't canonicalize the code path -- shenanigans?
8037                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8038                return Environment.getRootDirectory().getPath();
8039            }
8040        }
8041        return codeRoot.getPath();
8042    }
8043
8044    /**
8045     * Derive and set the location of native libraries for the given package,
8046     * which varies depending on where and how the package was installed.
8047     */
8048    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8049        final ApplicationInfo info = pkg.applicationInfo;
8050        final String codePath = pkg.codePath;
8051        final File codeFile = new File(codePath);
8052        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8053        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8054
8055        info.nativeLibraryRootDir = null;
8056        info.nativeLibraryRootRequiresIsa = false;
8057        info.nativeLibraryDir = null;
8058        info.secondaryNativeLibraryDir = null;
8059
8060        if (isApkFile(codeFile)) {
8061            // Monolithic install
8062            if (bundledApp) {
8063                // If "/system/lib64/apkname" exists, assume that is the per-package
8064                // native library directory to use; otherwise use "/system/lib/apkname".
8065                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8066                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8067                        getPrimaryInstructionSet(info));
8068
8069                // This is a bundled system app so choose the path based on the ABI.
8070                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8071                // is just the default path.
8072                final String apkName = deriveCodePathName(codePath);
8073                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8074                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8075                        apkName).getAbsolutePath();
8076
8077                if (info.secondaryCpuAbi != null) {
8078                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8079                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8080                            secondaryLibDir, apkName).getAbsolutePath();
8081                }
8082            } else if (asecApp) {
8083                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8084                        .getAbsolutePath();
8085            } else {
8086                final String apkName = deriveCodePathName(codePath);
8087                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8088                        .getAbsolutePath();
8089            }
8090
8091            info.nativeLibraryRootRequiresIsa = false;
8092            info.nativeLibraryDir = info.nativeLibraryRootDir;
8093        } else {
8094            // Cluster install
8095            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8096            info.nativeLibraryRootRequiresIsa = true;
8097
8098            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8099                    getPrimaryInstructionSet(info)).getAbsolutePath();
8100
8101            if (info.secondaryCpuAbi != null) {
8102                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8103                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8104            }
8105        }
8106    }
8107
8108    /**
8109     * Calculate the abis and roots for a bundled app. These can uniquely
8110     * be determined from the contents of the system partition, i.e whether
8111     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8112     * of this information, and instead assume that the system was built
8113     * sensibly.
8114     */
8115    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8116                                           PackageSetting pkgSetting) {
8117        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8118
8119        // If "/system/lib64/apkname" exists, assume that is the per-package
8120        // native library directory to use; otherwise use "/system/lib/apkname".
8121        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8122        setBundledAppAbi(pkg, apkRoot, apkName);
8123        // pkgSetting might be null during rescan following uninstall of updates
8124        // to a bundled app, so accommodate that possibility.  The settings in
8125        // that case will be established later from the parsed package.
8126        //
8127        // If the settings aren't null, sync them up with what we've just derived.
8128        // note that apkRoot isn't stored in the package settings.
8129        if (pkgSetting != null) {
8130            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8131            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8132        }
8133    }
8134
8135    /**
8136     * Deduces the ABI of a bundled app and sets the relevant fields on the
8137     * parsed pkg object.
8138     *
8139     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8140     *        under which system libraries are installed.
8141     * @param apkName the name of the installed package.
8142     */
8143    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8144        final File codeFile = new File(pkg.codePath);
8145
8146        final boolean has64BitLibs;
8147        final boolean has32BitLibs;
8148        if (isApkFile(codeFile)) {
8149            // Monolithic install
8150            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8151            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8152        } else {
8153            // Cluster install
8154            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8155            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8156                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8157                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8158                has64BitLibs = (new File(rootDir, isa)).exists();
8159            } else {
8160                has64BitLibs = false;
8161            }
8162            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8163                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8164                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8165                has32BitLibs = (new File(rootDir, isa)).exists();
8166            } else {
8167                has32BitLibs = false;
8168            }
8169        }
8170
8171        if (has64BitLibs && !has32BitLibs) {
8172            // The package has 64 bit libs, but not 32 bit libs. Its primary
8173            // ABI should be 64 bit. We can safely assume here that the bundled
8174            // native libraries correspond to the most preferred ABI in the list.
8175
8176            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8177            pkg.applicationInfo.secondaryCpuAbi = null;
8178        } else if (has32BitLibs && !has64BitLibs) {
8179            // The package has 32 bit libs but not 64 bit libs. Its primary
8180            // ABI should be 32 bit.
8181
8182            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8183            pkg.applicationInfo.secondaryCpuAbi = null;
8184        } else if (has32BitLibs && has64BitLibs) {
8185            // The application has both 64 and 32 bit bundled libraries. We check
8186            // here that the app declares multiArch support, and warn if it doesn't.
8187            //
8188            // We will be lenient here and record both ABIs. The primary will be the
8189            // ABI that's higher on the list, i.e, a device that's configured to prefer
8190            // 64 bit apps will see a 64 bit primary ABI,
8191
8192            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8193                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
8194            }
8195
8196            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8197                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8198                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8199            } else {
8200                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8201                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8202            }
8203        } else {
8204            pkg.applicationInfo.primaryCpuAbi = null;
8205            pkg.applicationInfo.secondaryCpuAbi = null;
8206        }
8207    }
8208
8209    private void killApplication(String pkgName, int appId, String reason) {
8210        // Request the ActivityManager to kill the process(only for existing packages)
8211        // so that we do not end up in a confused state while the user is still using the older
8212        // version of the application while the new one gets installed.
8213        IActivityManager am = ActivityManagerNative.getDefault();
8214        if (am != null) {
8215            try {
8216                am.killApplicationWithAppId(pkgName, appId, reason);
8217            } catch (RemoteException e) {
8218            }
8219        }
8220    }
8221
8222    void removePackageLI(PackageSetting ps, boolean chatty) {
8223        if (DEBUG_INSTALL) {
8224            if (chatty)
8225                Log.d(TAG, "Removing package " + ps.name);
8226        }
8227
8228        // writer
8229        synchronized (mPackages) {
8230            mPackages.remove(ps.name);
8231            final PackageParser.Package pkg = ps.pkg;
8232            if (pkg != null) {
8233                cleanPackageDataStructuresLILPw(pkg, chatty);
8234            }
8235        }
8236    }
8237
8238    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8239        if (DEBUG_INSTALL) {
8240            if (chatty)
8241                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8242        }
8243
8244        // writer
8245        synchronized (mPackages) {
8246            mPackages.remove(pkg.applicationInfo.packageName);
8247            cleanPackageDataStructuresLILPw(pkg, chatty);
8248        }
8249    }
8250
8251    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8252        int N = pkg.providers.size();
8253        StringBuilder r = null;
8254        int i;
8255        for (i=0; i<N; i++) {
8256            PackageParser.Provider p = pkg.providers.get(i);
8257            mProviders.removeProvider(p);
8258            if (p.info.authority == null) {
8259
8260                /* There was another ContentProvider with this authority when
8261                 * this app was installed so this authority is null,
8262                 * Ignore it as we don't have to unregister the provider.
8263                 */
8264                continue;
8265            }
8266            String names[] = p.info.authority.split(";");
8267            for (int j = 0; j < names.length; j++) {
8268                if (mProvidersByAuthority.get(names[j]) == p) {
8269                    mProvidersByAuthority.remove(names[j]);
8270                    if (DEBUG_REMOVE) {
8271                        if (chatty)
8272                            Log.d(TAG, "Unregistered content provider: " + names[j]
8273                                    + ", className = " + p.info.name + ", isSyncable = "
8274                                    + p.info.isSyncable);
8275                    }
8276                }
8277            }
8278            if (DEBUG_REMOVE && chatty) {
8279                if (r == null) {
8280                    r = new StringBuilder(256);
8281                } else {
8282                    r.append(' ');
8283                }
8284                r.append(p.info.name);
8285            }
8286        }
8287        if (r != null) {
8288            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8289        }
8290
8291        N = pkg.services.size();
8292        r = null;
8293        for (i=0; i<N; i++) {
8294            PackageParser.Service s = pkg.services.get(i);
8295            mServices.removeService(s);
8296            if (chatty) {
8297                if (r == null) {
8298                    r = new StringBuilder(256);
8299                } else {
8300                    r.append(' ');
8301                }
8302                r.append(s.info.name);
8303            }
8304        }
8305        if (r != null) {
8306            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8307        }
8308
8309        N = pkg.receivers.size();
8310        r = null;
8311        for (i=0; i<N; i++) {
8312            PackageParser.Activity a = pkg.receivers.get(i);
8313            mReceivers.removeActivity(a, "receiver");
8314            if (DEBUG_REMOVE && chatty) {
8315                if (r == null) {
8316                    r = new StringBuilder(256);
8317                } else {
8318                    r.append(' ');
8319                }
8320                r.append(a.info.name);
8321            }
8322        }
8323        if (r != null) {
8324            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8325        }
8326
8327        N = pkg.activities.size();
8328        r = null;
8329        for (i=0; i<N; i++) {
8330            PackageParser.Activity a = pkg.activities.get(i);
8331            mActivities.removeActivity(a, "activity");
8332            if (DEBUG_REMOVE && chatty) {
8333                if (r == null) {
8334                    r = new StringBuilder(256);
8335                } else {
8336                    r.append(' ');
8337                }
8338                r.append(a.info.name);
8339            }
8340        }
8341        if (r != null) {
8342            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8343        }
8344
8345        N = pkg.permissions.size();
8346        r = null;
8347        for (i=0; i<N; i++) {
8348            PackageParser.Permission p = pkg.permissions.get(i);
8349            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8350            if (bp == null) {
8351                bp = mSettings.mPermissionTrees.get(p.info.name);
8352            }
8353            if (bp != null && bp.perm == p) {
8354                bp.perm = null;
8355                if (DEBUG_REMOVE && chatty) {
8356                    if (r == null) {
8357                        r = new StringBuilder(256);
8358                    } else {
8359                        r.append(' ');
8360                    }
8361                    r.append(p.info.name);
8362                }
8363            }
8364            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8365                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8366                if (appOpPerms != null) {
8367                    appOpPerms.remove(pkg.packageName);
8368                }
8369            }
8370        }
8371        if (r != null) {
8372            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8373        }
8374
8375        N = pkg.requestedPermissions.size();
8376        r = null;
8377        for (i=0; i<N; i++) {
8378            String perm = pkg.requestedPermissions.get(i);
8379            BasePermission bp = mSettings.mPermissions.get(perm);
8380            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8381                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8382                if (appOpPerms != null) {
8383                    appOpPerms.remove(pkg.packageName);
8384                    if (appOpPerms.isEmpty()) {
8385                        mAppOpPermissionPackages.remove(perm);
8386                    }
8387                }
8388            }
8389        }
8390        if (r != null) {
8391            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8392        }
8393
8394        N = pkg.instrumentation.size();
8395        r = null;
8396        for (i=0; i<N; i++) {
8397            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8398            mInstrumentation.remove(a.getComponentName());
8399            if (DEBUG_REMOVE && chatty) {
8400                if (r == null) {
8401                    r = new StringBuilder(256);
8402                } else {
8403                    r.append(' ');
8404                }
8405                r.append(a.info.name);
8406            }
8407        }
8408        if (r != null) {
8409            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8410        }
8411
8412        r = null;
8413        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8414            // Only system apps can hold shared libraries.
8415            if (pkg.libraryNames != null) {
8416                for (i=0; i<pkg.libraryNames.size(); i++) {
8417                    String name = pkg.libraryNames.get(i);
8418                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8419                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8420                        mSharedLibraries.remove(name);
8421                        if (DEBUG_REMOVE && chatty) {
8422                            if (r == null) {
8423                                r = new StringBuilder(256);
8424                            } else {
8425                                r.append(' ');
8426                            }
8427                            r.append(name);
8428                        }
8429                    }
8430                }
8431            }
8432        }
8433        if (r != null) {
8434            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8435        }
8436    }
8437
8438    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8439        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8440            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8441                return true;
8442            }
8443        }
8444        return false;
8445    }
8446
8447    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8448    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8449    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8450
8451    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
8452            int flags) {
8453        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
8454        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
8455    }
8456
8457    private void updatePermissionsLPw(String changingPkg,
8458            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
8459        // Make sure there are no dangling permission trees.
8460        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8461        while (it.hasNext()) {
8462            final BasePermission bp = it.next();
8463            if (bp.packageSetting == null) {
8464                // We may not yet have parsed the package, so just see if
8465                // we still know about its settings.
8466                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8467            }
8468            if (bp.packageSetting == null) {
8469                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8470                        + " from package " + bp.sourcePackage);
8471                it.remove();
8472            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8473                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8474                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8475                            + " from package " + bp.sourcePackage);
8476                    flags |= UPDATE_PERMISSIONS_ALL;
8477                    it.remove();
8478                }
8479            }
8480        }
8481
8482        // Make sure all dynamic permissions have been assigned to a package,
8483        // and make sure there are no dangling permissions.
8484        it = mSettings.mPermissions.values().iterator();
8485        while (it.hasNext()) {
8486            final BasePermission bp = it.next();
8487            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8488                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8489                        + bp.name + " pkg=" + bp.sourcePackage
8490                        + " info=" + bp.pendingInfo);
8491                if (bp.packageSetting == null && bp.pendingInfo != null) {
8492                    final BasePermission tree = findPermissionTreeLP(bp.name);
8493                    if (tree != null && tree.perm != null) {
8494                        bp.packageSetting = tree.packageSetting;
8495                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8496                                new PermissionInfo(bp.pendingInfo));
8497                        bp.perm.info.packageName = tree.perm.info.packageName;
8498                        bp.perm.info.name = bp.name;
8499                        bp.uid = tree.uid;
8500                    }
8501                }
8502            }
8503            if (bp.packageSetting == null) {
8504                // We may not yet have parsed the package, so just see if
8505                // we still know about its settings.
8506                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8507            }
8508            if (bp.packageSetting == null) {
8509                Slog.w(TAG, "Removing dangling permission: " + bp.name
8510                        + " from package " + bp.sourcePackage);
8511                it.remove();
8512            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8513                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8514                    Slog.i(TAG, "Removing old permission: " + bp.name
8515                            + " from package " + bp.sourcePackage);
8516                    flags |= UPDATE_PERMISSIONS_ALL;
8517                    it.remove();
8518                }
8519            }
8520        }
8521
8522        // Now update the permissions for all packages, in particular
8523        // replace the granted permissions of the system packages.
8524        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8525            for (PackageParser.Package pkg : mPackages.values()) {
8526                if (pkg != pkgInfo) {
8527                    // Only replace for packages on requested volume
8528                    final String volumeUuid = getVolumeUuidForPackage(pkg);
8529                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
8530                            && Objects.equals(replaceVolumeUuid, volumeUuid);
8531                    grantPermissionsLPw(pkg, replace, changingPkg);
8532                }
8533            }
8534        }
8535
8536        if (pkgInfo != null) {
8537            // Only replace for packages on requested volume
8538            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
8539            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
8540                    && Objects.equals(replaceVolumeUuid, volumeUuid);
8541            grantPermissionsLPw(pkgInfo, replace, changingPkg);
8542        }
8543    }
8544
8545    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8546            String packageOfInterest) {
8547        // IMPORTANT: There are two types of permissions: install and runtime.
8548        // Install time permissions are granted when the app is installed to
8549        // all device users and users added in the future. Runtime permissions
8550        // are granted at runtime explicitly to specific users. Normal and signature
8551        // protected permissions are install time permissions. Dangerous permissions
8552        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8553        // otherwise they are runtime permissions. This function does not manage
8554        // runtime permissions except for the case an app targeting Lollipop MR1
8555        // being upgraded to target a newer SDK, in which case dangerous permissions
8556        // are transformed from install time to runtime ones.
8557
8558        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8559        if (ps == null) {
8560            return;
8561        }
8562
8563        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
8564
8565        PermissionsState permissionsState = ps.getPermissionsState();
8566        PermissionsState origPermissions = permissionsState;
8567
8568        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8569
8570        boolean runtimePermissionsRevoked = false;
8571        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8572
8573        boolean changedInstallPermission = false;
8574
8575        if (replace) {
8576            ps.installPermissionsFixed = false;
8577            if (!ps.isSharedUser()) {
8578                origPermissions = new PermissionsState(permissionsState);
8579                permissionsState.reset();
8580            } else {
8581                // We need to know only about runtime permission changes since the
8582                // calling code always writes the install permissions state but
8583                // the runtime ones are written only if changed. The only cases of
8584                // changed runtime permissions here are promotion of an install to
8585                // runtime and revocation of a runtime from a shared user.
8586                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
8587                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
8588                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
8589                    runtimePermissionsRevoked = true;
8590                }
8591            }
8592        }
8593
8594        permissionsState.setGlobalGids(mGlobalGids);
8595
8596        final int N = pkg.requestedPermissions.size();
8597        for (int i=0; i<N; i++) {
8598            final String name = pkg.requestedPermissions.get(i);
8599            final BasePermission bp = mSettings.mPermissions.get(name);
8600
8601            if (DEBUG_INSTALL) {
8602                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8603            }
8604
8605            if (bp == null || bp.packageSetting == null) {
8606                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8607                    Slog.w(TAG, "Unknown permission " + name
8608                            + " in package " + pkg.packageName);
8609                }
8610                continue;
8611            }
8612
8613            final String perm = bp.name;
8614            boolean allowedSig = false;
8615            int grant = GRANT_DENIED;
8616
8617            // Keep track of app op permissions.
8618            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8619                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8620                if (pkgs == null) {
8621                    pkgs = new ArraySet<>();
8622                    mAppOpPermissionPackages.put(bp.name, pkgs);
8623                }
8624                pkgs.add(pkg.packageName);
8625            }
8626
8627            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8628            switch (level) {
8629                case PermissionInfo.PROTECTION_NORMAL: {
8630                    // For all apps normal permissions are install time ones.
8631                    grant = GRANT_INSTALL;
8632                } break;
8633
8634                case PermissionInfo.PROTECTION_DANGEROUS: {
8635                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8636                        // For legacy apps dangerous permissions are install time ones.
8637                        grant = GRANT_INSTALL_LEGACY;
8638                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8639                        // For legacy apps that became modern, install becomes runtime.
8640                        grant = GRANT_UPGRADE;
8641                    } else if (mPromoteSystemApps
8642                            && isSystemApp(ps)
8643                            && mExistingSystemPackages.contains(ps.name)) {
8644                        // For legacy system apps, install becomes runtime.
8645                        // We cannot check hasInstallPermission() for system apps since those
8646                        // permissions were granted implicitly and not persisted pre-M.
8647                        grant = GRANT_UPGRADE;
8648                    } else {
8649                        // For modern apps keep runtime permissions unchanged.
8650                        grant = GRANT_RUNTIME;
8651                    }
8652                } break;
8653
8654                case PermissionInfo.PROTECTION_SIGNATURE: {
8655                    // For all apps signature permissions are install time ones.
8656                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8657                    if (allowedSig) {
8658                        grant = GRANT_INSTALL;
8659                    }
8660                } break;
8661            }
8662
8663            if (DEBUG_INSTALL) {
8664                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8665            }
8666
8667            if (grant != GRANT_DENIED) {
8668                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8669                    // If this is an existing, non-system package, then
8670                    // we can't add any new permissions to it.
8671                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8672                        // Except...  if this is a permission that was added
8673                        // to the platform (note: need to only do this when
8674                        // updating the platform).
8675                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8676                            grant = GRANT_DENIED;
8677                        }
8678                    }
8679                }
8680
8681                switch (grant) {
8682                    case GRANT_INSTALL: {
8683                        // Revoke this as runtime permission to handle the case of
8684                        // a runtime permission being downgraded to an install one.
8685                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8686                            if (origPermissions.getRuntimePermissionState(
8687                                    bp.name, userId) != null) {
8688                                // Revoke the runtime permission and clear the flags.
8689                                origPermissions.revokeRuntimePermission(bp, userId);
8690                                origPermissions.updatePermissionFlags(bp, userId,
8691                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8692                                // If we revoked a permission permission, we have to write.
8693                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8694                                        changedRuntimePermissionUserIds, userId);
8695                            }
8696                        }
8697                        // Grant an install permission.
8698                        if (permissionsState.grantInstallPermission(bp) !=
8699                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8700                            changedInstallPermission = true;
8701                        }
8702                    } break;
8703
8704                    case GRANT_INSTALL_LEGACY: {
8705                        // Grant an install permission.
8706                        if (permissionsState.grantInstallPermission(bp) !=
8707                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8708                            changedInstallPermission = true;
8709                        }
8710                    } break;
8711
8712                    case GRANT_RUNTIME: {
8713                        // Grant previously granted runtime permissions.
8714                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8715                            PermissionState permissionState = origPermissions
8716                                    .getRuntimePermissionState(bp.name, userId);
8717                            final int flags = permissionState != null
8718                                    ? permissionState.getFlags() : 0;
8719                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8720                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8721                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8722                                    // If we cannot put the permission as it was, we have to write.
8723                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8724                                            changedRuntimePermissionUserIds, userId);
8725                                }
8726                            }
8727                            // Propagate the permission flags.
8728                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8729                        }
8730                    } break;
8731
8732                    case GRANT_UPGRADE: {
8733                        // Grant runtime permissions for a previously held install permission.
8734                        PermissionState permissionState = origPermissions
8735                                .getInstallPermissionState(bp.name);
8736                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8737
8738                        if (origPermissions.revokeInstallPermission(bp)
8739                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8740                            // We will be transferring the permission flags, so clear them.
8741                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8742                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8743                            changedInstallPermission = true;
8744                        }
8745
8746                        // If the permission is not to be promoted to runtime we ignore it and
8747                        // also its other flags as they are not applicable to install permissions.
8748                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8749                            for (int userId : currentUserIds) {
8750                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8751                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8752                                    // Transfer the permission flags.
8753                                    permissionsState.updatePermissionFlags(bp, userId,
8754                                            flags, flags);
8755                                    // If we granted the permission, we have to write.
8756                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8757                                            changedRuntimePermissionUserIds, userId);
8758                                }
8759                            }
8760                        }
8761                    } break;
8762
8763                    default: {
8764                        if (packageOfInterest == null
8765                                || packageOfInterest.equals(pkg.packageName)) {
8766                            Slog.w(TAG, "Not granting permission " + perm
8767                                    + " to package " + pkg.packageName
8768                                    + " because it was previously installed without");
8769                        }
8770                    } break;
8771                }
8772            } else {
8773                if (permissionsState.revokeInstallPermission(bp) !=
8774                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8775                    // Also drop the permission flags.
8776                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8777                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8778                    changedInstallPermission = true;
8779                    Slog.i(TAG, "Un-granting permission " + perm
8780                            + " from package " + pkg.packageName
8781                            + " (protectionLevel=" + bp.protectionLevel
8782                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8783                            + ")");
8784                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8785                    // Don't print warning for app op permissions, since it is fine for them
8786                    // not to be granted, there is a UI for the user to decide.
8787                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8788                        Slog.w(TAG, "Not granting permission " + perm
8789                                + " to package " + pkg.packageName
8790                                + " (protectionLevel=" + bp.protectionLevel
8791                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8792                                + ")");
8793                    }
8794                }
8795            }
8796        }
8797
8798        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8799                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8800            // This is the first that we have heard about this package, so the
8801            // permissions we have now selected are fixed until explicitly
8802            // changed.
8803            ps.installPermissionsFixed = true;
8804        }
8805
8806        // Persist the runtime permissions state for users with changes. If permissions
8807        // were revoked because no app in the shared user declares them we have to
8808        // write synchronously to avoid losing runtime permissions state.
8809        for (int userId : changedRuntimePermissionUserIds) {
8810            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
8811        }
8812
8813        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8814    }
8815
8816    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8817        boolean allowed = false;
8818        final int NP = PackageParser.NEW_PERMISSIONS.length;
8819        for (int ip=0; ip<NP; ip++) {
8820            final PackageParser.NewPermissionInfo npi
8821                    = PackageParser.NEW_PERMISSIONS[ip];
8822            if (npi.name.equals(perm)
8823                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8824                allowed = true;
8825                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8826                        + pkg.packageName);
8827                break;
8828            }
8829        }
8830        return allowed;
8831    }
8832
8833    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8834            BasePermission bp, PermissionsState origPermissions) {
8835        boolean allowed;
8836        allowed = (compareSignatures(
8837                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8838                        == PackageManager.SIGNATURE_MATCH)
8839                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8840                        == PackageManager.SIGNATURE_MATCH);
8841        if (!allowed && (bp.protectionLevel
8842                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8843            if (isSystemApp(pkg)) {
8844                // For updated system applications, a system permission
8845                // is granted only if it had been defined by the original application.
8846                if (pkg.isUpdatedSystemApp()) {
8847                    final PackageSetting sysPs = mSettings
8848                            .getDisabledSystemPkgLPr(pkg.packageName);
8849                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8850                        // If the original was granted this permission, we take
8851                        // that grant decision as read and propagate it to the
8852                        // update.
8853                        if (sysPs.isPrivileged()) {
8854                            allowed = true;
8855                        }
8856                    } else {
8857                        // The system apk may have been updated with an older
8858                        // version of the one on the data partition, but which
8859                        // granted a new system permission that it didn't have
8860                        // before.  In this case we do want to allow the app to
8861                        // now get the new permission if the ancestral apk is
8862                        // privileged to get it.
8863                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8864                            for (int j=0;
8865                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8866                                if (perm.equals(
8867                                        sysPs.pkg.requestedPermissions.get(j))) {
8868                                    allowed = true;
8869                                    break;
8870                                }
8871                            }
8872                        }
8873                    }
8874                } else {
8875                    allowed = isPrivilegedApp(pkg);
8876                }
8877            }
8878        }
8879        if (!allowed) {
8880            if (!allowed && (bp.protectionLevel
8881                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8882                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
8883                // If this was a previously normal/dangerous permission that got moved
8884                // to a system permission as part of the runtime permission redesign, then
8885                // we still want to blindly grant it to old apps.
8886                allowed = true;
8887            }
8888            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8889                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8890                // If this permission is to be granted to the system installer and
8891                // this app is an installer, then it gets the permission.
8892                allowed = true;
8893            }
8894            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8895                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8896                // If this permission is to be granted to the system verifier and
8897                // this app is a verifier, then it gets the permission.
8898                allowed = true;
8899            }
8900            if (!allowed && (bp.protectionLevel
8901                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8902                    && isSystemApp(pkg)) {
8903                // Any pre-installed system app is allowed to get this permission.
8904                allowed = true;
8905            }
8906            if (!allowed && (bp.protectionLevel
8907                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8908                // For development permissions, a development permission
8909                // is granted only if it was already granted.
8910                allowed = origPermissions.hasInstallPermission(perm);
8911            }
8912        }
8913        return allowed;
8914    }
8915
8916    final class ActivityIntentResolver
8917            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8918        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8919                boolean defaultOnly, int userId) {
8920            if (!sUserManager.exists(userId)) return null;
8921            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8922            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8923        }
8924
8925        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8926                int userId) {
8927            if (!sUserManager.exists(userId)) return null;
8928            mFlags = flags;
8929            return super.queryIntent(intent, resolvedType,
8930                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8931        }
8932
8933        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8934                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8935            if (!sUserManager.exists(userId)) return null;
8936            if (packageActivities == null) {
8937                return null;
8938            }
8939            mFlags = flags;
8940            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8941            final int N = packageActivities.size();
8942            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8943                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8944
8945            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8946            for (int i = 0; i < N; ++i) {
8947                intentFilters = packageActivities.get(i).intents;
8948                if (intentFilters != null && intentFilters.size() > 0) {
8949                    PackageParser.ActivityIntentInfo[] array =
8950                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8951                    intentFilters.toArray(array);
8952                    listCut.add(array);
8953                }
8954            }
8955            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8956        }
8957
8958        public final void addActivity(PackageParser.Activity a, String type) {
8959            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8960            mActivities.put(a.getComponentName(), a);
8961            if (DEBUG_SHOW_INFO)
8962                Log.v(
8963                TAG, "  " + type + " " +
8964                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8965            if (DEBUG_SHOW_INFO)
8966                Log.v(TAG, "    Class=" + a.info.name);
8967            final int NI = a.intents.size();
8968            for (int j=0; j<NI; j++) {
8969                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8970                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8971                    intent.setPriority(0);
8972                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8973                            + a.className + " with priority > 0, forcing to 0");
8974                }
8975                if (DEBUG_SHOW_INFO) {
8976                    Log.v(TAG, "    IntentFilter:");
8977                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8978                }
8979                if (!intent.debugCheck()) {
8980                    Log.w(TAG, "==> For Activity " + a.info.name);
8981                }
8982                addFilter(intent);
8983            }
8984        }
8985
8986        public final void removeActivity(PackageParser.Activity a, String type) {
8987            mActivities.remove(a.getComponentName());
8988            if (DEBUG_SHOW_INFO) {
8989                Log.v(TAG, "  " + type + " "
8990                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8991                                : a.info.name) + ":");
8992                Log.v(TAG, "    Class=" + a.info.name);
8993            }
8994            final int NI = a.intents.size();
8995            for (int j=0; j<NI; j++) {
8996                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8997                if (DEBUG_SHOW_INFO) {
8998                    Log.v(TAG, "    IntentFilter:");
8999                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9000                }
9001                removeFilter(intent);
9002            }
9003        }
9004
9005        @Override
9006        protected boolean allowFilterResult(
9007                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
9008            ActivityInfo filterAi = filter.activity.info;
9009            for (int i=dest.size()-1; i>=0; i--) {
9010                ActivityInfo destAi = dest.get(i).activityInfo;
9011                if (destAi.name == filterAi.name
9012                        && destAi.packageName == filterAi.packageName) {
9013                    return false;
9014                }
9015            }
9016            return true;
9017        }
9018
9019        @Override
9020        protected ActivityIntentInfo[] newArray(int size) {
9021            return new ActivityIntentInfo[size];
9022        }
9023
9024        @Override
9025        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
9026            if (!sUserManager.exists(userId)) return true;
9027            PackageParser.Package p = filter.activity.owner;
9028            if (p != null) {
9029                PackageSetting ps = (PackageSetting)p.mExtras;
9030                if (ps != null) {
9031                    // System apps are never considered stopped for purposes of
9032                    // filtering, because there may be no way for the user to
9033                    // actually re-launch them.
9034                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
9035                            && ps.getStopped(userId);
9036                }
9037            }
9038            return false;
9039        }
9040
9041        @Override
9042        protected boolean isPackageForFilter(String packageName,
9043                PackageParser.ActivityIntentInfo info) {
9044            return packageName.equals(info.activity.owner.packageName);
9045        }
9046
9047        @Override
9048        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
9049                int match, int userId) {
9050            if (!sUserManager.exists(userId)) return null;
9051            if (!mSettings.isEnabledAndVisibleLPr(info.activity.info, mFlags, userId)) {
9052                return null;
9053            }
9054            final PackageParser.Activity activity = info.activity;
9055            if (mSafeMode && (activity.info.applicationInfo.flags
9056                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9057                return null;
9058            }
9059            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
9060            if (ps == null) {
9061                return null;
9062            }
9063            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
9064                    ps.readUserState(userId), userId);
9065            if (ai == null) {
9066                return null;
9067            }
9068            final ResolveInfo res = new ResolveInfo();
9069            res.activityInfo = ai;
9070            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9071                res.filter = info;
9072            }
9073            if (info != null) {
9074                res.handleAllWebDataURI = info.handleAllWebDataURI();
9075            }
9076            res.priority = info.getPriority();
9077            res.preferredOrder = activity.owner.mPreferredOrder;
9078            //System.out.println("Result: " + res.activityInfo.className +
9079            //                   " = " + res.priority);
9080            res.match = match;
9081            res.isDefault = info.hasDefault;
9082            res.labelRes = info.labelRes;
9083            res.nonLocalizedLabel = info.nonLocalizedLabel;
9084            if (userNeedsBadging(userId)) {
9085                res.noResourceId = true;
9086            } else {
9087                res.icon = info.icon;
9088            }
9089            res.iconResourceId = info.icon;
9090            res.system = res.activityInfo.applicationInfo.isSystemApp();
9091            return res;
9092        }
9093
9094        @Override
9095        protected void sortResults(List<ResolveInfo> results) {
9096            Collections.sort(results, mResolvePrioritySorter);
9097        }
9098
9099        @Override
9100        protected void dumpFilter(PrintWriter out, String prefix,
9101                PackageParser.ActivityIntentInfo filter) {
9102            out.print(prefix); out.print(
9103                    Integer.toHexString(System.identityHashCode(filter.activity)));
9104                    out.print(' ');
9105                    filter.activity.printComponentShortName(out);
9106                    out.print(" filter ");
9107                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9108        }
9109
9110        @Override
9111        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9112            return filter.activity;
9113        }
9114
9115        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9116            PackageParser.Activity activity = (PackageParser.Activity)label;
9117            out.print(prefix); out.print(
9118                    Integer.toHexString(System.identityHashCode(activity)));
9119                    out.print(' ');
9120                    activity.printComponentShortName(out);
9121            if (count > 1) {
9122                out.print(" ("); out.print(count); out.print(" filters)");
9123            }
9124            out.println();
9125        }
9126
9127//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9128//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9129//            final List<ResolveInfo> retList = Lists.newArrayList();
9130//            while (i.hasNext()) {
9131//                final ResolveInfo resolveInfo = i.next();
9132//                if (isEnabledLP(resolveInfo.activityInfo)) {
9133//                    retList.add(resolveInfo);
9134//                }
9135//            }
9136//            return retList;
9137//        }
9138
9139        // Keys are String (activity class name), values are Activity.
9140        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9141                = new ArrayMap<ComponentName, PackageParser.Activity>();
9142        private int mFlags;
9143    }
9144
9145    private final class ServiceIntentResolver
9146            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9147        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9148                boolean defaultOnly, int userId) {
9149            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9150            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9151        }
9152
9153        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9154                int userId) {
9155            if (!sUserManager.exists(userId)) return null;
9156            mFlags = flags;
9157            return super.queryIntent(intent, resolvedType,
9158                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9159        }
9160
9161        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9162                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9163            if (!sUserManager.exists(userId)) return null;
9164            if (packageServices == null) {
9165                return null;
9166            }
9167            mFlags = flags;
9168            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9169            final int N = packageServices.size();
9170            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9171                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9172
9173            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9174            for (int i = 0; i < N; ++i) {
9175                intentFilters = packageServices.get(i).intents;
9176                if (intentFilters != null && intentFilters.size() > 0) {
9177                    PackageParser.ServiceIntentInfo[] array =
9178                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9179                    intentFilters.toArray(array);
9180                    listCut.add(array);
9181                }
9182            }
9183            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9184        }
9185
9186        public final void addService(PackageParser.Service s) {
9187            mServices.put(s.getComponentName(), s);
9188            if (DEBUG_SHOW_INFO) {
9189                Log.v(TAG, "  "
9190                        + (s.info.nonLocalizedLabel != null
9191                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9192                Log.v(TAG, "    Class=" + s.info.name);
9193            }
9194            final int NI = s.intents.size();
9195            int j;
9196            for (j=0; j<NI; j++) {
9197                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9198                if (DEBUG_SHOW_INFO) {
9199                    Log.v(TAG, "    IntentFilter:");
9200                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9201                }
9202                if (!intent.debugCheck()) {
9203                    Log.w(TAG, "==> For Service " + s.info.name);
9204                }
9205                addFilter(intent);
9206            }
9207        }
9208
9209        public final void removeService(PackageParser.Service s) {
9210            mServices.remove(s.getComponentName());
9211            if (DEBUG_SHOW_INFO) {
9212                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9213                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9214                Log.v(TAG, "    Class=" + s.info.name);
9215            }
9216            final int NI = s.intents.size();
9217            int j;
9218            for (j=0; j<NI; j++) {
9219                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9220                if (DEBUG_SHOW_INFO) {
9221                    Log.v(TAG, "    IntentFilter:");
9222                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9223                }
9224                removeFilter(intent);
9225            }
9226        }
9227
9228        @Override
9229        protected boolean allowFilterResult(
9230                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9231            ServiceInfo filterSi = filter.service.info;
9232            for (int i=dest.size()-1; i>=0; i--) {
9233                ServiceInfo destAi = dest.get(i).serviceInfo;
9234                if (destAi.name == filterSi.name
9235                        && destAi.packageName == filterSi.packageName) {
9236                    return false;
9237                }
9238            }
9239            return true;
9240        }
9241
9242        @Override
9243        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9244            return new PackageParser.ServiceIntentInfo[size];
9245        }
9246
9247        @Override
9248        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9249            if (!sUserManager.exists(userId)) return true;
9250            PackageParser.Package p = filter.service.owner;
9251            if (p != null) {
9252                PackageSetting ps = (PackageSetting)p.mExtras;
9253                if (ps != null) {
9254                    // System apps are never considered stopped for purposes of
9255                    // filtering, because there may be no way for the user to
9256                    // actually re-launch them.
9257                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9258                            && ps.getStopped(userId);
9259                }
9260            }
9261            return false;
9262        }
9263
9264        @Override
9265        protected boolean isPackageForFilter(String packageName,
9266                PackageParser.ServiceIntentInfo info) {
9267            return packageName.equals(info.service.owner.packageName);
9268        }
9269
9270        @Override
9271        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9272                int match, int userId) {
9273            if (!sUserManager.exists(userId)) return null;
9274            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9275            if (!mSettings.isEnabledAndVisibleLPr(info.service.info, mFlags, userId)) {
9276                return null;
9277            }
9278            final PackageParser.Service service = info.service;
9279            if (mSafeMode && (service.info.applicationInfo.flags
9280                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9281                return null;
9282            }
9283            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9284            if (ps == null) {
9285                return null;
9286            }
9287            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9288                    ps.readUserState(userId), userId);
9289            if (si == null) {
9290                return null;
9291            }
9292            final ResolveInfo res = new ResolveInfo();
9293            res.serviceInfo = si;
9294            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9295                res.filter = filter;
9296            }
9297            res.priority = info.getPriority();
9298            res.preferredOrder = service.owner.mPreferredOrder;
9299            res.match = match;
9300            res.isDefault = info.hasDefault;
9301            res.labelRes = info.labelRes;
9302            res.nonLocalizedLabel = info.nonLocalizedLabel;
9303            res.icon = info.icon;
9304            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9305            return res;
9306        }
9307
9308        @Override
9309        protected void sortResults(List<ResolveInfo> results) {
9310            Collections.sort(results, mResolvePrioritySorter);
9311        }
9312
9313        @Override
9314        protected void dumpFilter(PrintWriter out, String prefix,
9315                PackageParser.ServiceIntentInfo filter) {
9316            out.print(prefix); out.print(
9317                    Integer.toHexString(System.identityHashCode(filter.service)));
9318                    out.print(' ');
9319                    filter.service.printComponentShortName(out);
9320                    out.print(" filter ");
9321                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9322        }
9323
9324        @Override
9325        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9326            return filter.service;
9327        }
9328
9329        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9330            PackageParser.Service service = (PackageParser.Service)label;
9331            out.print(prefix); out.print(
9332                    Integer.toHexString(System.identityHashCode(service)));
9333                    out.print(' ');
9334                    service.printComponentShortName(out);
9335            if (count > 1) {
9336                out.print(" ("); out.print(count); out.print(" filters)");
9337            }
9338            out.println();
9339        }
9340
9341//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9342//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9343//            final List<ResolveInfo> retList = Lists.newArrayList();
9344//            while (i.hasNext()) {
9345//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9346//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9347//                    retList.add(resolveInfo);
9348//                }
9349//            }
9350//            return retList;
9351//        }
9352
9353        // Keys are String (activity class name), values are Activity.
9354        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9355                = new ArrayMap<ComponentName, PackageParser.Service>();
9356        private int mFlags;
9357    };
9358
9359    private final class ProviderIntentResolver
9360            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9361        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9362                boolean defaultOnly, int userId) {
9363            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9364            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9365        }
9366
9367        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9368                int userId) {
9369            if (!sUserManager.exists(userId))
9370                return null;
9371            mFlags = flags;
9372            return super.queryIntent(intent, resolvedType,
9373                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9374        }
9375
9376        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9377                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9378            if (!sUserManager.exists(userId))
9379                return null;
9380            if (packageProviders == null) {
9381                return null;
9382            }
9383            mFlags = flags;
9384            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9385            final int N = packageProviders.size();
9386            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9387                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9388
9389            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9390            for (int i = 0; i < N; ++i) {
9391                intentFilters = packageProviders.get(i).intents;
9392                if (intentFilters != null && intentFilters.size() > 0) {
9393                    PackageParser.ProviderIntentInfo[] array =
9394                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9395                    intentFilters.toArray(array);
9396                    listCut.add(array);
9397                }
9398            }
9399            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9400        }
9401
9402        public final void addProvider(PackageParser.Provider p) {
9403            if (mProviders.containsKey(p.getComponentName())) {
9404                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9405                return;
9406            }
9407
9408            mProviders.put(p.getComponentName(), p);
9409            if (DEBUG_SHOW_INFO) {
9410                Log.v(TAG, "  "
9411                        + (p.info.nonLocalizedLabel != null
9412                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9413                Log.v(TAG, "    Class=" + p.info.name);
9414            }
9415            final int NI = p.intents.size();
9416            int j;
9417            for (j = 0; j < NI; j++) {
9418                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9419                if (DEBUG_SHOW_INFO) {
9420                    Log.v(TAG, "    IntentFilter:");
9421                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9422                }
9423                if (!intent.debugCheck()) {
9424                    Log.w(TAG, "==> For Provider " + p.info.name);
9425                }
9426                addFilter(intent);
9427            }
9428        }
9429
9430        public final void removeProvider(PackageParser.Provider p) {
9431            mProviders.remove(p.getComponentName());
9432            if (DEBUG_SHOW_INFO) {
9433                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9434                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9435                Log.v(TAG, "    Class=" + p.info.name);
9436            }
9437            final int NI = p.intents.size();
9438            int j;
9439            for (j = 0; j < NI; j++) {
9440                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9441                if (DEBUG_SHOW_INFO) {
9442                    Log.v(TAG, "    IntentFilter:");
9443                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9444                }
9445                removeFilter(intent);
9446            }
9447        }
9448
9449        @Override
9450        protected boolean allowFilterResult(
9451                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9452            ProviderInfo filterPi = filter.provider.info;
9453            for (int i = dest.size() - 1; i >= 0; i--) {
9454                ProviderInfo destPi = dest.get(i).providerInfo;
9455                if (destPi.name == filterPi.name
9456                        && destPi.packageName == filterPi.packageName) {
9457                    return false;
9458                }
9459            }
9460            return true;
9461        }
9462
9463        @Override
9464        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9465            return new PackageParser.ProviderIntentInfo[size];
9466        }
9467
9468        @Override
9469        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9470            if (!sUserManager.exists(userId))
9471                return true;
9472            PackageParser.Package p = filter.provider.owner;
9473            if (p != null) {
9474                PackageSetting ps = (PackageSetting) p.mExtras;
9475                if (ps != null) {
9476                    // System apps are never considered stopped for purposes of
9477                    // filtering, because there may be no way for the user to
9478                    // actually re-launch them.
9479                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9480                            && ps.getStopped(userId);
9481                }
9482            }
9483            return false;
9484        }
9485
9486        @Override
9487        protected boolean isPackageForFilter(String packageName,
9488                PackageParser.ProviderIntentInfo info) {
9489            return packageName.equals(info.provider.owner.packageName);
9490        }
9491
9492        @Override
9493        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9494                int match, int userId) {
9495            if (!sUserManager.exists(userId))
9496                return null;
9497            final PackageParser.ProviderIntentInfo info = filter;
9498            if (!mSettings.isEnabledAndVisibleLPr(info.provider.info, mFlags, userId)) {
9499                return null;
9500            }
9501            final PackageParser.Provider provider = info.provider;
9502            if (mSafeMode && (provider.info.applicationInfo.flags
9503                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9504                return null;
9505            }
9506            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9507            if (ps == null) {
9508                return null;
9509            }
9510            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9511                    ps.readUserState(userId), userId);
9512            if (pi == null) {
9513                return null;
9514            }
9515            final ResolveInfo res = new ResolveInfo();
9516            res.providerInfo = pi;
9517            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9518                res.filter = filter;
9519            }
9520            res.priority = info.getPriority();
9521            res.preferredOrder = provider.owner.mPreferredOrder;
9522            res.match = match;
9523            res.isDefault = info.hasDefault;
9524            res.labelRes = info.labelRes;
9525            res.nonLocalizedLabel = info.nonLocalizedLabel;
9526            res.icon = info.icon;
9527            res.system = res.providerInfo.applicationInfo.isSystemApp();
9528            return res;
9529        }
9530
9531        @Override
9532        protected void sortResults(List<ResolveInfo> results) {
9533            Collections.sort(results, mResolvePrioritySorter);
9534        }
9535
9536        @Override
9537        protected void dumpFilter(PrintWriter out, String prefix,
9538                PackageParser.ProviderIntentInfo filter) {
9539            out.print(prefix);
9540            out.print(
9541                    Integer.toHexString(System.identityHashCode(filter.provider)));
9542            out.print(' ');
9543            filter.provider.printComponentShortName(out);
9544            out.print(" filter ");
9545            out.println(Integer.toHexString(System.identityHashCode(filter)));
9546        }
9547
9548        @Override
9549        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9550            return filter.provider;
9551        }
9552
9553        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9554            PackageParser.Provider provider = (PackageParser.Provider)label;
9555            out.print(prefix); out.print(
9556                    Integer.toHexString(System.identityHashCode(provider)));
9557                    out.print(' ');
9558                    provider.printComponentShortName(out);
9559            if (count > 1) {
9560                out.print(" ("); out.print(count); out.print(" filters)");
9561            }
9562            out.println();
9563        }
9564
9565        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9566                = new ArrayMap<ComponentName, PackageParser.Provider>();
9567        private int mFlags;
9568    }
9569
9570    private static final class EphemeralIntentResolver
9571            extends IntentResolver<IntentFilter, ResolveInfo> {
9572        @Override
9573        protected IntentFilter[] newArray(int size) {
9574            return new IntentFilter[size];
9575        }
9576
9577        @Override
9578        protected boolean isPackageForFilter(String packageName, IntentFilter info) {
9579            return true;
9580        }
9581
9582        @Override
9583        protected ResolveInfo newResult(IntentFilter info, int match, int userId) {
9584            if (!sUserManager.exists(userId)) return null;
9585            final ResolveInfo res = new ResolveInfo();
9586            res.filter = info;
9587            return res;
9588        }
9589    }
9590
9591    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9592            new Comparator<ResolveInfo>() {
9593        public int compare(ResolveInfo r1, ResolveInfo r2) {
9594            int v1 = r1.priority;
9595            int v2 = r2.priority;
9596            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9597            if (v1 != v2) {
9598                return (v1 > v2) ? -1 : 1;
9599            }
9600            v1 = r1.preferredOrder;
9601            v2 = r2.preferredOrder;
9602            if (v1 != v2) {
9603                return (v1 > v2) ? -1 : 1;
9604            }
9605            if (r1.isDefault != r2.isDefault) {
9606                return r1.isDefault ? -1 : 1;
9607            }
9608            v1 = r1.match;
9609            v2 = r2.match;
9610            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9611            if (v1 != v2) {
9612                return (v1 > v2) ? -1 : 1;
9613            }
9614            if (r1.system != r2.system) {
9615                return r1.system ? -1 : 1;
9616            }
9617            return 0;
9618        }
9619    };
9620
9621    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9622            new Comparator<ProviderInfo>() {
9623        public int compare(ProviderInfo p1, ProviderInfo p2) {
9624            final int v1 = p1.initOrder;
9625            final int v2 = p2.initOrder;
9626            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9627        }
9628    };
9629
9630    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
9631            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
9632            final int[] userIds) {
9633        mHandler.post(new Runnable() {
9634            @Override
9635            public void run() {
9636                try {
9637                    final IActivityManager am = ActivityManagerNative.getDefault();
9638                    if (am == null) return;
9639                    final int[] resolvedUserIds;
9640                    if (userIds == null) {
9641                        resolvedUserIds = am.getRunningUserIds();
9642                    } else {
9643                        resolvedUserIds = userIds;
9644                    }
9645                    for (int id : resolvedUserIds) {
9646                        final Intent intent = new Intent(action,
9647                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9648                        if (extras != null) {
9649                            intent.putExtras(extras);
9650                        }
9651                        if (targetPkg != null) {
9652                            intent.setPackage(targetPkg);
9653                        }
9654                        // Modify the UID when posting to other users
9655                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9656                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9657                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9658                            intent.putExtra(Intent.EXTRA_UID, uid);
9659                        }
9660                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9661                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
9662                        if (DEBUG_BROADCASTS) {
9663                            RuntimeException here = new RuntimeException("here");
9664                            here.fillInStackTrace();
9665                            Slog.d(TAG, "Sending to user " + id + ": "
9666                                    + intent.toShortString(false, true, false, false)
9667                                    + " " + intent.getExtras(), here);
9668                        }
9669                        am.broadcastIntent(null, intent, null, finishedReceiver,
9670                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9671                                null, finishedReceiver != null, false, id);
9672                    }
9673                } catch (RemoteException ex) {
9674                }
9675            }
9676        });
9677    }
9678
9679    /**
9680     * Check if the external storage media is available. This is true if there
9681     * is a mounted external storage medium or if the external storage is
9682     * emulated.
9683     */
9684    private boolean isExternalMediaAvailable() {
9685        return mMediaMounted || Environment.isExternalStorageEmulated();
9686    }
9687
9688    @Override
9689    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9690        // writer
9691        synchronized (mPackages) {
9692            if (!isExternalMediaAvailable()) {
9693                // If the external storage is no longer mounted at this point,
9694                // the caller may not have been able to delete all of this
9695                // packages files and can not delete any more.  Bail.
9696                return null;
9697            }
9698            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9699            if (lastPackage != null) {
9700                pkgs.remove(lastPackage);
9701            }
9702            if (pkgs.size() > 0) {
9703                return pkgs.get(0);
9704            }
9705        }
9706        return null;
9707    }
9708
9709    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9710        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9711                userId, andCode ? 1 : 0, packageName);
9712        if (mSystemReady) {
9713            msg.sendToTarget();
9714        } else {
9715            if (mPostSystemReadyMessages == null) {
9716                mPostSystemReadyMessages = new ArrayList<>();
9717            }
9718            mPostSystemReadyMessages.add(msg);
9719        }
9720    }
9721
9722    void startCleaningPackages() {
9723        // reader
9724        synchronized (mPackages) {
9725            if (!isExternalMediaAvailable()) {
9726                return;
9727            }
9728            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9729                return;
9730            }
9731        }
9732        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9733        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9734        IActivityManager am = ActivityManagerNative.getDefault();
9735        if (am != null) {
9736            try {
9737                am.startService(null, intent, null, mContext.getOpPackageName(),
9738                        UserHandle.USER_SYSTEM);
9739            } catch (RemoteException e) {
9740            }
9741        }
9742    }
9743
9744    @Override
9745    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9746            int installFlags, String installerPackageName, VerificationParams verificationParams,
9747            String packageAbiOverride) {
9748        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9749                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9750    }
9751
9752    @Override
9753    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9754            int installFlags, String installerPackageName, VerificationParams verificationParams,
9755            String packageAbiOverride, int userId) {
9756        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9757
9758        final int callingUid = Binder.getCallingUid();
9759        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9760
9761        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9762            try {
9763                if (observer != null) {
9764                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9765                }
9766            } catch (RemoteException re) {
9767            }
9768            return;
9769        }
9770
9771        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9772            installFlags |= PackageManager.INSTALL_FROM_ADB;
9773
9774        } else {
9775            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9776            // about installerPackageName.
9777
9778            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9779            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9780        }
9781
9782        UserHandle user;
9783        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9784            user = UserHandle.ALL;
9785        } else {
9786            user = new UserHandle(userId);
9787        }
9788
9789        // Only system components can circumvent runtime permissions when installing.
9790        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9791                && mContext.checkCallingOrSelfPermission(Manifest.permission
9792                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9793            throw new SecurityException("You need the "
9794                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9795                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9796        }
9797
9798        verificationParams.setInstallerUid(callingUid);
9799
9800        final File originFile = new File(originPath);
9801        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9802
9803        final Message msg = mHandler.obtainMessage(INIT_COPY);
9804        final InstallParams params = new InstallParams(origin, null, observer, installFlags,
9805                installerPackageName, null, verificationParams, user, packageAbiOverride, null);
9806        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
9807        msg.obj = params;
9808
9809        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
9810                System.identityHashCode(msg.obj));
9811        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
9812                System.identityHashCode(msg.obj));
9813
9814        mHandler.sendMessage(msg);
9815    }
9816
9817    void installStage(String packageName, File stagedDir, String stagedCid,
9818            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
9819            String installerPackageName, int installerUid, UserHandle user) {
9820        final VerificationParams verifParams = new VerificationParams(
9821                null, sessionParams.originatingUri, sessionParams.referrerUri,
9822                sessionParams.originatingUid, null);
9823        verifParams.setInstallerUid(installerUid);
9824
9825        final OriginInfo origin;
9826        if (stagedDir != null) {
9827            origin = OriginInfo.fromStagedFile(stagedDir);
9828        } else {
9829            origin = OriginInfo.fromStagedContainer(stagedCid);
9830        }
9831
9832        final Message msg = mHandler.obtainMessage(INIT_COPY);
9833        final InstallParams params = new InstallParams(origin, null, observer,
9834                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
9835                verifParams, user, sessionParams.abiOverride,
9836                sessionParams.grantedRuntimePermissions);
9837        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
9838        msg.obj = params;
9839
9840        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
9841                System.identityHashCode(msg.obj));
9842        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
9843                System.identityHashCode(msg.obj));
9844
9845        mHandler.sendMessage(msg);
9846    }
9847
9848    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9849        Bundle extras = new Bundle(1);
9850        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9851
9852        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9853                packageName, extras, 0, null, null, new int[] {userId});
9854        try {
9855            IActivityManager am = ActivityManagerNative.getDefault();
9856            final boolean isSystem =
9857                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9858            if (isSystem && am.isUserRunning(userId, 0)) {
9859                // The just-installed/enabled app is bundled on the system, so presumed
9860                // to be able to run automatically without needing an explicit launch.
9861                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9862                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9863                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9864                        .setPackage(packageName);
9865                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9866                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9867            }
9868        } catch (RemoteException e) {
9869            // shouldn't happen
9870            Slog.w(TAG, "Unable to bootstrap installed package", e);
9871        }
9872    }
9873
9874    @Override
9875    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9876            int userId) {
9877        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9878        PackageSetting pkgSetting;
9879        final int uid = Binder.getCallingUid();
9880        enforceCrossUserPermission(uid, userId, true, true,
9881                "setApplicationHiddenSetting for user " + userId);
9882
9883        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9884            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9885            return false;
9886        }
9887
9888        long callingId = Binder.clearCallingIdentity();
9889        try {
9890            boolean sendAdded = false;
9891            boolean sendRemoved = false;
9892            // writer
9893            synchronized (mPackages) {
9894                pkgSetting = mSettings.mPackages.get(packageName);
9895                if (pkgSetting == null) {
9896                    return false;
9897                }
9898                if (pkgSetting.getHidden(userId) != hidden) {
9899                    pkgSetting.setHidden(hidden, userId);
9900                    mSettings.writePackageRestrictionsLPr(userId);
9901                    if (hidden) {
9902                        sendRemoved = true;
9903                    } else {
9904                        sendAdded = true;
9905                    }
9906                }
9907            }
9908            if (sendAdded) {
9909                sendPackageAddedForUser(packageName, pkgSetting, userId);
9910                return true;
9911            }
9912            if (sendRemoved) {
9913                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9914                        "hiding pkg");
9915                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9916                return true;
9917            }
9918        } finally {
9919            Binder.restoreCallingIdentity(callingId);
9920        }
9921        return false;
9922    }
9923
9924    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9925            int userId) {
9926        final PackageRemovedInfo info = new PackageRemovedInfo();
9927        info.removedPackage = packageName;
9928        info.removedUsers = new int[] {userId};
9929        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9930        info.sendBroadcast(false, false, false);
9931    }
9932
9933    /**
9934     * Returns true if application is not found or there was an error. Otherwise it returns
9935     * the hidden state of the package for the given user.
9936     */
9937    @Override
9938    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9939        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9940        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9941                false, "getApplicationHidden for user " + userId);
9942        PackageSetting pkgSetting;
9943        long callingId = Binder.clearCallingIdentity();
9944        try {
9945            // writer
9946            synchronized (mPackages) {
9947                pkgSetting = mSettings.mPackages.get(packageName);
9948                if (pkgSetting == null) {
9949                    return true;
9950                }
9951                return pkgSetting.getHidden(userId);
9952            }
9953        } finally {
9954            Binder.restoreCallingIdentity(callingId);
9955        }
9956    }
9957
9958    /**
9959     * @hide
9960     */
9961    @Override
9962    public int installExistingPackageAsUser(String packageName, int userId) {
9963        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9964                null);
9965        PackageSetting pkgSetting;
9966        final int uid = Binder.getCallingUid();
9967        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9968                + userId);
9969        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9970            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9971        }
9972
9973        long callingId = Binder.clearCallingIdentity();
9974        try {
9975            boolean sendAdded = false;
9976
9977            // writer
9978            synchronized (mPackages) {
9979                pkgSetting = mSettings.mPackages.get(packageName);
9980                if (pkgSetting == null) {
9981                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9982                }
9983                if (!pkgSetting.getInstalled(userId)) {
9984                    pkgSetting.setInstalled(true, userId);
9985                    pkgSetting.setHidden(false, userId);
9986                    mSettings.writePackageRestrictionsLPr(userId);
9987                    sendAdded = true;
9988                }
9989            }
9990
9991            if (sendAdded) {
9992                sendPackageAddedForUser(packageName, pkgSetting, userId);
9993            }
9994        } finally {
9995            Binder.restoreCallingIdentity(callingId);
9996        }
9997
9998        return PackageManager.INSTALL_SUCCEEDED;
9999    }
10000
10001    boolean isUserRestricted(int userId, String restrictionKey) {
10002        Bundle restrictions = sUserManager.getUserRestrictions(userId);
10003        if (restrictions.getBoolean(restrictionKey, false)) {
10004            Log.w(TAG, "User is restricted: " + restrictionKey);
10005            return true;
10006        }
10007        return false;
10008    }
10009
10010    @Override
10011    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
10012        mContext.enforceCallingOrSelfPermission(
10013                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10014                "Only package verification agents can verify applications");
10015
10016        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10017        final PackageVerificationResponse response = new PackageVerificationResponse(
10018                verificationCode, Binder.getCallingUid());
10019        msg.arg1 = id;
10020        msg.obj = response;
10021        mHandler.sendMessage(msg);
10022    }
10023
10024    @Override
10025    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
10026            long millisecondsToDelay) {
10027        mContext.enforceCallingOrSelfPermission(
10028                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10029                "Only package verification agents can extend verification timeouts");
10030
10031        final PackageVerificationState state = mPendingVerification.get(id);
10032        final PackageVerificationResponse response = new PackageVerificationResponse(
10033                verificationCodeAtTimeout, Binder.getCallingUid());
10034
10035        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
10036            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
10037        }
10038        if (millisecondsToDelay < 0) {
10039            millisecondsToDelay = 0;
10040        }
10041        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
10042                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
10043            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
10044        }
10045
10046        if ((state != null) && !state.timeoutExtended()) {
10047            state.extendTimeout();
10048
10049            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10050            msg.arg1 = id;
10051            msg.obj = response;
10052            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
10053        }
10054    }
10055
10056    private void broadcastPackageVerified(int verificationId, Uri packageUri,
10057            int verificationCode, UserHandle user) {
10058        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
10059        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
10060        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10061        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10062        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
10063
10064        mContext.sendBroadcastAsUser(intent, user,
10065                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
10066    }
10067
10068    private ComponentName matchComponentForVerifier(String packageName,
10069            List<ResolveInfo> receivers) {
10070        ActivityInfo targetReceiver = null;
10071
10072        final int NR = receivers.size();
10073        for (int i = 0; i < NR; i++) {
10074            final ResolveInfo info = receivers.get(i);
10075            if (info.activityInfo == null) {
10076                continue;
10077            }
10078
10079            if (packageName.equals(info.activityInfo.packageName)) {
10080                targetReceiver = info.activityInfo;
10081                break;
10082            }
10083        }
10084
10085        if (targetReceiver == null) {
10086            return null;
10087        }
10088
10089        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
10090    }
10091
10092    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
10093            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
10094        if (pkgInfo.verifiers.length == 0) {
10095            return null;
10096        }
10097
10098        final int N = pkgInfo.verifiers.length;
10099        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
10100        for (int i = 0; i < N; i++) {
10101            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
10102
10103            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
10104                    receivers);
10105            if (comp == null) {
10106                continue;
10107            }
10108
10109            final int verifierUid = getUidForVerifier(verifierInfo);
10110            if (verifierUid == -1) {
10111                continue;
10112            }
10113
10114            if (DEBUG_VERIFY) {
10115                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
10116                        + " with the correct signature");
10117            }
10118            sufficientVerifiers.add(comp);
10119            verificationState.addSufficientVerifier(verifierUid);
10120        }
10121
10122        return sufficientVerifiers;
10123    }
10124
10125    private int getUidForVerifier(VerifierInfo verifierInfo) {
10126        synchronized (mPackages) {
10127            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
10128            if (pkg == null) {
10129                return -1;
10130            } else if (pkg.mSignatures.length != 1) {
10131                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10132                        + " has more than one signature; ignoring");
10133                return -1;
10134            }
10135
10136            /*
10137             * If the public key of the package's signature does not match
10138             * our expected public key, then this is a different package and
10139             * we should skip.
10140             */
10141
10142            final byte[] expectedPublicKey;
10143            try {
10144                final Signature verifierSig = pkg.mSignatures[0];
10145                final PublicKey publicKey = verifierSig.getPublicKey();
10146                expectedPublicKey = publicKey.getEncoded();
10147            } catch (CertificateException e) {
10148                return -1;
10149            }
10150
10151            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
10152
10153            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
10154                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10155                        + " does not have the expected public key; ignoring");
10156                return -1;
10157            }
10158
10159            return pkg.applicationInfo.uid;
10160        }
10161    }
10162
10163    @Override
10164    public void finishPackageInstall(int token) {
10165        enforceSystemOrRoot("Only the system is allowed to finish installs");
10166
10167        if (DEBUG_INSTALL) {
10168            Slog.v(TAG, "BM finishing package install for " + token);
10169        }
10170        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10171
10172        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10173        mHandler.sendMessage(msg);
10174    }
10175
10176    /**
10177     * Get the verification agent timeout.
10178     *
10179     * @return verification timeout in milliseconds
10180     */
10181    private long getVerificationTimeout() {
10182        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
10183                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
10184                DEFAULT_VERIFICATION_TIMEOUT);
10185    }
10186
10187    /**
10188     * Get the default verification agent response code.
10189     *
10190     * @return default verification response code
10191     */
10192    private int getDefaultVerificationResponse() {
10193        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10194                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
10195                DEFAULT_VERIFICATION_RESPONSE);
10196    }
10197
10198    /**
10199     * Check whether or not package verification has been enabled.
10200     *
10201     * @return true if verification should be performed
10202     */
10203    private boolean isVerificationEnabled(int userId, int installFlags) {
10204        if (!DEFAULT_VERIFY_ENABLE) {
10205            return false;
10206        }
10207        // TODO: fix b/25118622; don't bypass verification
10208        if (Build.IS_DEBUGGABLE && (installFlags & PackageManager.INSTALL_QUICK) != 0) {
10209            return false;
10210        }
10211
10212        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
10213
10214        // Check if installing from ADB
10215        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
10216            // Do not run verification in a test harness environment
10217            if (ActivityManager.isRunningInTestHarness()) {
10218                return false;
10219            }
10220            if (ensureVerifyAppsEnabled) {
10221                return true;
10222            }
10223            // Check if the developer does not want package verification for ADB installs
10224            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10225                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
10226                return false;
10227            }
10228        }
10229
10230        if (ensureVerifyAppsEnabled) {
10231            return true;
10232        }
10233
10234        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10235                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
10236    }
10237
10238    @Override
10239    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
10240            throws RemoteException {
10241        mContext.enforceCallingOrSelfPermission(
10242                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
10243                "Only intentfilter verification agents can verify applications");
10244
10245        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
10246        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
10247                Binder.getCallingUid(), verificationCode, failedDomains);
10248        msg.arg1 = id;
10249        msg.obj = response;
10250        mHandler.sendMessage(msg);
10251    }
10252
10253    @Override
10254    public int getIntentVerificationStatus(String packageName, int userId) {
10255        synchronized (mPackages) {
10256            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
10257        }
10258    }
10259
10260    @Override
10261    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
10262        mContext.enforceCallingOrSelfPermission(
10263                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10264
10265        boolean result = false;
10266        synchronized (mPackages) {
10267            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10268        }
10269        if (result) {
10270            scheduleWritePackageRestrictionsLocked(userId);
10271        }
10272        return result;
10273    }
10274
10275    @Override
10276    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10277        synchronized (mPackages) {
10278            return mSettings.getIntentFilterVerificationsLPr(packageName);
10279        }
10280    }
10281
10282    @Override
10283    public List<IntentFilter> getAllIntentFilters(String packageName) {
10284        if (TextUtils.isEmpty(packageName)) {
10285            return Collections.<IntentFilter>emptyList();
10286        }
10287        synchronized (mPackages) {
10288            PackageParser.Package pkg = mPackages.get(packageName);
10289            if (pkg == null || pkg.activities == null) {
10290                return Collections.<IntentFilter>emptyList();
10291            }
10292            final int count = pkg.activities.size();
10293            ArrayList<IntentFilter> result = new ArrayList<>();
10294            for (int n=0; n<count; n++) {
10295                PackageParser.Activity activity = pkg.activities.get(n);
10296                if (activity.intents != null || activity.intents.size() > 0) {
10297                    result.addAll(activity.intents);
10298                }
10299            }
10300            return result;
10301        }
10302    }
10303
10304    @Override
10305    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10306        mContext.enforceCallingOrSelfPermission(
10307                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10308
10309        synchronized (mPackages) {
10310            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10311            if (packageName != null) {
10312                result |= updateIntentVerificationStatus(packageName,
10313                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10314                        userId);
10315                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10316                        packageName, userId);
10317            }
10318            return result;
10319        }
10320    }
10321
10322    @Override
10323    public String getDefaultBrowserPackageName(int userId) {
10324        synchronized (mPackages) {
10325            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10326        }
10327    }
10328
10329    /**
10330     * Get the "allow unknown sources" setting.
10331     *
10332     * @return the current "allow unknown sources" setting
10333     */
10334    private int getUnknownSourcesSettings() {
10335        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10336                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10337                -1);
10338    }
10339
10340    @Override
10341    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10342        final int uid = Binder.getCallingUid();
10343        // writer
10344        synchronized (mPackages) {
10345            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10346            if (targetPackageSetting == null) {
10347                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10348            }
10349
10350            PackageSetting installerPackageSetting;
10351            if (installerPackageName != null) {
10352                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10353                if (installerPackageSetting == null) {
10354                    throw new IllegalArgumentException("Unknown installer package: "
10355                            + installerPackageName);
10356                }
10357            } else {
10358                installerPackageSetting = null;
10359            }
10360
10361            Signature[] callerSignature;
10362            Object obj = mSettings.getUserIdLPr(uid);
10363            if (obj != null) {
10364                if (obj instanceof SharedUserSetting) {
10365                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10366                } else if (obj instanceof PackageSetting) {
10367                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10368                } else {
10369                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10370                }
10371            } else {
10372                throw new SecurityException("Unknown calling uid " + uid);
10373            }
10374
10375            // Verify: can't set installerPackageName to a package that is
10376            // not signed with the same cert as the caller.
10377            if (installerPackageSetting != null) {
10378                if (compareSignatures(callerSignature,
10379                        installerPackageSetting.signatures.mSignatures)
10380                        != PackageManager.SIGNATURE_MATCH) {
10381                    throw new SecurityException(
10382                            "Caller does not have same cert as new installer package "
10383                            + installerPackageName);
10384                }
10385            }
10386
10387            // Verify: if target already has an installer package, it must
10388            // be signed with the same cert as the caller.
10389            if (targetPackageSetting.installerPackageName != null) {
10390                PackageSetting setting = mSettings.mPackages.get(
10391                        targetPackageSetting.installerPackageName);
10392                // If the currently set package isn't valid, then it's always
10393                // okay to change it.
10394                if (setting != null) {
10395                    if (compareSignatures(callerSignature,
10396                            setting.signatures.mSignatures)
10397                            != PackageManager.SIGNATURE_MATCH) {
10398                        throw new SecurityException(
10399                                "Caller does not have same cert as old installer package "
10400                                + targetPackageSetting.installerPackageName);
10401                    }
10402                }
10403            }
10404
10405            // Okay!
10406            targetPackageSetting.installerPackageName = installerPackageName;
10407            scheduleWriteSettingsLocked();
10408        }
10409    }
10410
10411    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10412        // Queue up an async operation since the package installation may take a little while.
10413        mHandler.post(new Runnable() {
10414            public void run() {
10415                mHandler.removeCallbacks(this);
10416                 // Result object to be returned
10417                PackageInstalledInfo res = new PackageInstalledInfo();
10418                res.returnCode = currentStatus;
10419                res.uid = -1;
10420                res.pkg = null;
10421                res.removedInfo = new PackageRemovedInfo();
10422                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10423                    args.doPreInstall(res.returnCode);
10424                    synchronized (mInstallLock) {
10425                        installPackageTracedLI(args, res);
10426                    }
10427                    args.doPostInstall(res.returnCode, res.uid);
10428                }
10429
10430                // A restore should be performed at this point if (a) the install
10431                // succeeded, (b) the operation is not an update, and (c) the new
10432                // package has not opted out of backup participation.
10433                final boolean update = res.removedInfo.removedPackage != null;
10434                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10435                boolean doRestore = !update
10436                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10437
10438                // Set up the post-install work request bookkeeping.  This will be used
10439                // and cleaned up by the post-install event handling regardless of whether
10440                // there's a restore pass performed.  Token values are >= 1.
10441                int token;
10442                if (mNextInstallToken < 0) mNextInstallToken = 1;
10443                token = mNextInstallToken++;
10444
10445                PostInstallData data = new PostInstallData(args, res);
10446                mRunningInstalls.put(token, data);
10447                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10448
10449                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10450                    // Pass responsibility to the Backup Manager.  It will perform a
10451                    // restore if appropriate, then pass responsibility back to the
10452                    // Package Manager to run the post-install observer callbacks
10453                    // and broadcasts.
10454                    IBackupManager bm = IBackupManager.Stub.asInterface(
10455                            ServiceManager.getService(Context.BACKUP_SERVICE));
10456                    if (bm != null) {
10457                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10458                                + " to BM for possible restore");
10459                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10460                        try {
10461                            // TODO: http://b/22388012
10462                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
10463                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10464                            } else {
10465                                doRestore = false;
10466                            }
10467                        } catch (RemoteException e) {
10468                            // can't happen; the backup manager is local
10469                        } catch (Exception e) {
10470                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10471                            doRestore = false;
10472                        }
10473                    } else {
10474                        Slog.e(TAG, "Backup Manager not found!");
10475                        doRestore = false;
10476                    }
10477                }
10478
10479                if (!doRestore) {
10480                    // No restore possible, or the Backup Manager was mysteriously not
10481                    // available -- just fire the post-install work request directly.
10482                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10483
10484                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
10485
10486                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10487                    mHandler.sendMessage(msg);
10488                }
10489            }
10490        });
10491    }
10492
10493    private abstract class HandlerParams {
10494        private static final int MAX_RETRIES = 4;
10495
10496        /**
10497         * Number of times startCopy() has been attempted and had a non-fatal
10498         * error.
10499         */
10500        private int mRetries = 0;
10501
10502        /** User handle for the user requesting the information or installation. */
10503        private final UserHandle mUser;
10504        String traceMethod;
10505        int traceCookie;
10506
10507        HandlerParams(UserHandle user) {
10508            mUser = user;
10509        }
10510
10511        UserHandle getUser() {
10512            return mUser;
10513        }
10514
10515        HandlerParams setTraceMethod(String traceMethod) {
10516            this.traceMethod = traceMethod;
10517            return this;
10518        }
10519
10520        HandlerParams setTraceCookie(int traceCookie) {
10521            this.traceCookie = traceCookie;
10522            return this;
10523        }
10524
10525        final boolean startCopy() {
10526            boolean res;
10527            try {
10528                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10529
10530                if (++mRetries > MAX_RETRIES) {
10531                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10532                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10533                    handleServiceError();
10534                    return false;
10535                } else {
10536                    handleStartCopy();
10537                    res = true;
10538                }
10539            } catch (RemoteException e) {
10540                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10541                mHandler.sendEmptyMessage(MCS_RECONNECT);
10542                res = false;
10543            }
10544            handleReturnCode();
10545            return res;
10546        }
10547
10548        final void serviceError() {
10549            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10550            handleServiceError();
10551            handleReturnCode();
10552        }
10553
10554        abstract void handleStartCopy() throws RemoteException;
10555        abstract void handleServiceError();
10556        abstract void handleReturnCode();
10557    }
10558
10559    class MeasureParams extends HandlerParams {
10560        private final PackageStats mStats;
10561        private boolean mSuccess;
10562
10563        private final IPackageStatsObserver mObserver;
10564
10565        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10566            super(new UserHandle(stats.userHandle));
10567            mObserver = observer;
10568            mStats = stats;
10569        }
10570
10571        @Override
10572        public String toString() {
10573            return "MeasureParams{"
10574                + Integer.toHexString(System.identityHashCode(this))
10575                + " " + mStats.packageName + "}";
10576        }
10577
10578        @Override
10579        void handleStartCopy() throws RemoteException {
10580            synchronized (mInstallLock) {
10581                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10582            }
10583
10584            if (mSuccess) {
10585                final boolean mounted;
10586                if (Environment.isExternalStorageEmulated()) {
10587                    mounted = true;
10588                } else {
10589                    final String status = Environment.getExternalStorageState();
10590                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10591                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10592                }
10593
10594                if (mounted) {
10595                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10596
10597                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10598                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10599
10600                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10601                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10602
10603                    // Always subtract cache size, since it's a subdirectory
10604                    mStats.externalDataSize -= mStats.externalCacheSize;
10605
10606                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10607                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10608
10609                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10610                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10611                }
10612            }
10613        }
10614
10615        @Override
10616        void handleReturnCode() {
10617            if (mObserver != null) {
10618                try {
10619                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10620                } catch (RemoteException e) {
10621                    Slog.i(TAG, "Observer no longer exists.");
10622                }
10623            }
10624        }
10625
10626        @Override
10627        void handleServiceError() {
10628            Slog.e(TAG, "Could not measure application " + mStats.packageName
10629                            + " external storage");
10630        }
10631    }
10632
10633    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10634            throws RemoteException {
10635        long result = 0;
10636        for (File path : paths) {
10637            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10638        }
10639        return result;
10640    }
10641
10642    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10643        for (File path : paths) {
10644            try {
10645                mcs.clearDirectory(path.getAbsolutePath());
10646            } catch (RemoteException e) {
10647            }
10648        }
10649    }
10650
10651    static class OriginInfo {
10652        /**
10653         * Location where install is coming from, before it has been
10654         * copied/renamed into place. This could be a single monolithic APK
10655         * file, or a cluster directory. This location may be untrusted.
10656         */
10657        final File file;
10658        final String cid;
10659
10660        /**
10661         * Flag indicating that {@link #file} or {@link #cid} has already been
10662         * staged, meaning downstream users don't need to defensively copy the
10663         * contents.
10664         */
10665        final boolean staged;
10666
10667        /**
10668         * Flag indicating that {@link #file} or {@link #cid} is an already
10669         * installed app that is being moved.
10670         */
10671        final boolean existing;
10672
10673        final String resolvedPath;
10674        final File resolvedFile;
10675
10676        static OriginInfo fromNothing() {
10677            return new OriginInfo(null, null, false, false);
10678        }
10679
10680        static OriginInfo fromUntrustedFile(File file) {
10681            return new OriginInfo(file, null, false, false);
10682        }
10683
10684        static OriginInfo fromExistingFile(File file) {
10685            return new OriginInfo(file, null, false, true);
10686        }
10687
10688        static OriginInfo fromStagedFile(File file) {
10689            return new OriginInfo(file, null, true, false);
10690        }
10691
10692        static OriginInfo fromStagedContainer(String cid) {
10693            return new OriginInfo(null, cid, true, false);
10694        }
10695
10696        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10697            this.file = file;
10698            this.cid = cid;
10699            this.staged = staged;
10700            this.existing = existing;
10701
10702            if (cid != null) {
10703                resolvedPath = PackageHelper.getSdDir(cid);
10704                resolvedFile = new File(resolvedPath);
10705            } else if (file != null) {
10706                resolvedPath = file.getAbsolutePath();
10707                resolvedFile = file;
10708            } else {
10709                resolvedPath = null;
10710                resolvedFile = null;
10711            }
10712        }
10713    }
10714
10715    class MoveInfo {
10716        final int moveId;
10717        final String fromUuid;
10718        final String toUuid;
10719        final String packageName;
10720        final String dataAppName;
10721        final int appId;
10722        final String seinfo;
10723
10724        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10725                String dataAppName, int appId, String seinfo) {
10726            this.moveId = moveId;
10727            this.fromUuid = fromUuid;
10728            this.toUuid = toUuid;
10729            this.packageName = packageName;
10730            this.dataAppName = dataAppName;
10731            this.appId = appId;
10732            this.seinfo = seinfo;
10733        }
10734    }
10735
10736    class InstallParams extends HandlerParams {
10737        final OriginInfo origin;
10738        final MoveInfo move;
10739        final IPackageInstallObserver2 observer;
10740        int installFlags;
10741        final String installerPackageName;
10742        final String volumeUuid;
10743        final VerificationParams verificationParams;
10744        private InstallArgs mArgs;
10745        private int mRet;
10746        final String packageAbiOverride;
10747        final String[] grantedRuntimePermissions;
10748
10749        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10750                int installFlags, String installerPackageName, String volumeUuid,
10751                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10752                String[] grantedPermissions) {
10753            super(user);
10754            this.origin = origin;
10755            this.move = move;
10756            this.observer = observer;
10757            this.installFlags = installFlags;
10758            this.installerPackageName = installerPackageName;
10759            this.volumeUuid = volumeUuid;
10760            this.verificationParams = verificationParams;
10761            this.packageAbiOverride = packageAbiOverride;
10762            this.grantedRuntimePermissions = grantedPermissions;
10763        }
10764
10765        @Override
10766        public String toString() {
10767            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10768                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10769        }
10770
10771        public ManifestDigest getManifestDigest() {
10772            if (verificationParams == null) {
10773                return null;
10774            }
10775            return verificationParams.getManifestDigest();
10776        }
10777
10778        private int installLocationPolicy(PackageInfoLite pkgLite) {
10779            String packageName = pkgLite.packageName;
10780            int installLocation = pkgLite.installLocation;
10781            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10782            // reader
10783            synchronized (mPackages) {
10784                PackageParser.Package pkg = mPackages.get(packageName);
10785                if (pkg != null) {
10786                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10787                        // Check for downgrading.
10788                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10789                            try {
10790                                checkDowngrade(pkg, pkgLite);
10791                            } catch (PackageManagerException e) {
10792                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10793                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10794                            }
10795                        }
10796                        // Check for updated system application.
10797                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10798                            if (onSd) {
10799                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10800                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10801                            }
10802                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10803                        } else {
10804                            if (onSd) {
10805                                // Install flag overrides everything.
10806                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10807                            }
10808                            // If current upgrade specifies particular preference
10809                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10810                                // Application explicitly specified internal.
10811                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10812                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10813                                // App explictly prefers external. Let policy decide
10814                            } else {
10815                                // Prefer previous location
10816                                if (isExternal(pkg)) {
10817                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10818                                }
10819                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10820                            }
10821                        }
10822                    } else {
10823                        // Invalid install. Return error code
10824                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10825                    }
10826                }
10827            }
10828            // All the special cases have been taken care of.
10829            // Return result based on recommended install location.
10830            if (onSd) {
10831                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10832            }
10833            return pkgLite.recommendedInstallLocation;
10834        }
10835
10836        /*
10837         * Invoke remote method to get package information and install
10838         * location values. Override install location based on default
10839         * policy if needed and then create install arguments based
10840         * on the install location.
10841         */
10842        public void handleStartCopy() throws RemoteException {
10843            int ret = PackageManager.INSTALL_SUCCEEDED;
10844
10845            // If we're already staged, we've firmly committed to an install location
10846            if (origin.staged) {
10847                if (origin.file != null) {
10848                    installFlags |= PackageManager.INSTALL_INTERNAL;
10849                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10850                } else if (origin.cid != null) {
10851                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10852                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10853                } else {
10854                    throw new IllegalStateException("Invalid stage location");
10855                }
10856            }
10857
10858            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10859            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10860            PackageInfoLite pkgLite = null;
10861
10862            if (onInt && onSd) {
10863                // Check if both bits are set.
10864                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10865                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10866            } else {
10867                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10868                        packageAbiOverride);
10869
10870                /*
10871                 * If we have too little free space, try to free cache
10872                 * before giving up.
10873                 */
10874                if (!origin.staged && pkgLite.recommendedInstallLocation
10875                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10876                    // TODO: focus freeing disk space on the target device
10877                    final StorageManager storage = StorageManager.from(mContext);
10878                    final long lowThreshold = storage.getStorageLowBytes(
10879                            Environment.getDataDirectory());
10880
10881                    final long sizeBytes = mContainerService.calculateInstalledSize(
10882                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10883
10884                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10885                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10886                                installFlags, packageAbiOverride);
10887                    }
10888
10889                    /*
10890                     * The cache free must have deleted the file we
10891                     * downloaded to install.
10892                     *
10893                     * TODO: fix the "freeCache" call to not delete
10894                     *       the file we care about.
10895                     */
10896                    if (pkgLite.recommendedInstallLocation
10897                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10898                        pkgLite.recommendedInstallLocation
10899                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10900                    }
10901                }
10902            }
10903
10904            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10905                int loc = pkgLite.recommendedInstallLocation;
10906                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10907                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10908                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10909                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10910                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10911                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10912                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10913                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10914                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10915                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10916                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10917                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10918                } else {
10919                    // Override with defaults if needed.
10920                    loc = installLocationPolicy(pkgLite);
10921                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10922                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10923                    } else if (!onSd && !onInt) {
10924                        // Override install location with flags
10925                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10926                            // Set the flag to install on external media.
10927                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10928                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10929                        } else {
10930                            // Make sure the flag for installing on external
10931                            // media is unset
10932                            installFlags |= PackageManager.INSTALL_INTERNAL;
10933                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10934                        }
10935                    }
10936                }
10937            }
10938
10939            final InstallArgs args = createInstallArgs(this);
10940            mArgs = args;
10941
10942            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10943                // TODO: http://b/22976637
10944                // Apps installed for "all" users use the device owner to verify the app
10945                UserHandle verifierUser = getUser();
10946                if (verifierUser == UserHandle.ALL) {
10947                    verifierUser = UserHandle.SYSTEM;
10948                }
10949
10950                /*
10951                 * Determine if we have any installed package verifiers. If we
10952                 * do, then we'll defer to them to verify the packages.
10953                 */
10954                final int requiredUid = mRequiredVerifierPackage == null ? -1
10955                        : getPackageUid(mRequiredVerifierPackage, verifierUser.getIdentifier());
10956                if (!origin.existing && requiredUid != -1
10957                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
10958                    final Intent verification = new Intent(
10959                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10960                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10961                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10962                            PACKAGE_MIME_TYPE);
10963                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10964
10965                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10966                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10967                            verifierUser.getIdentifier());
10968
10969                    if (DEBUG_VERIFY) {
10970                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10971                                + verification.toString() + " with " + pkgLite.verifiers.length
10972                                + " optional verifiers");
10973                    }
10974
10975                    final int verificationId = mPendingVerificationToken++;
10976
10977                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10978
10979                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10980                            installerPackageName);
10981
10982                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10983                            installFlags);
10984
10985                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10986                            pkgLite.packageName);
10987
10988                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10989                            pkgLite.versionCode);
10990
10991                    if (verificationParams != null) {
10992                        if (verificationParams.getVerificationURI() != null) {
10993                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10994                                 verificationParams.getVerificationURI());
10995                        }
10996                        if (verificationParams.getOriginatingURI() != null) {
10997                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10998                                  verificationParams.getOriginatingURI());
10999                        }
11000                        if (verificationParams.getReferrer() != null) {
11001                            verification.putExtra(Intent.EXTRA_REFERRER,
11002                                  verificationParams.getReferrer());
11003                        }
11004                        if (verificationParams.getOriginatingUid() >= 0) {
11005                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
11006                                  verificationParams.getOriginatingUid());
11007                        }
11008                        if (verificationParams.getInstallerUid() >= 0) {
11009                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
11010                                  verificationParams.getInstallerUid());
11011                        }
11012                    }
11013
11014                    final PackageVerificationState verificationState = new PackageVerificationState(
11015                            requiredUid, args);
11016
11017                    mPendingVerification.append(verificationId, verificationState);
11018
11019                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
11020                            receivers, verificationState);
11021
11022                    /*
11023                     * If any sufficient verifiers were listed in the package
11024                     * manifest, attempt to ask them.
11025                     */
11026                    if (sufficientVerifiers != null) {
11027                        final int N = sufficientVerifiers.size();
11028                        if (N == 0) {
11029                            Slog.i(TAG, "Additional verifiers required, but none installed.");
11030                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
11031                        } else {
11032                            for (int i = 0; i < N; i++) {
11033                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
11034
11035                                final Intent sufficientIntent = new Intent(verification);
11036                                sufficientIntent.setComponent(verifierComponent);
11037                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
11038                            }
11039                        }
11040                    }
11041
11042                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
11043                            mRequiredVerifierPackage, receivers);
11044                    if (ret == PackageManager.INSTALL_SUCCEEDED
11045                            && mRequiredVerifierPackage != null) {
11046                        Trace.asyncTraceBegin(
11047                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
11048                        /*
11049                         * Send the intent to the required verification agent,
11050                         * but only start the verification timeout after the
11051                         * target BroadcastReceivers have run.
11052                         */
11053                        verification.setComponent(requiredVerifierComponent);
11054                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
11055                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11056                                new BroadcastReceiver() {
11057                                    @Override
11058                                    public void onReceive(Context context, Intent intent) {
11059                                        final Message msg = mHandler
11060                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
11061                                        msg.arg1 = verificationId;
11062                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
11063                                    }
11064                                }, null, 0, null, null);
11065
11066                        /*
11067                         * We don't want the copy to proceed until verification
11068                         * succeeds, so null out this field.
11069                         */
11070                        mArgs = null;
11071                    }
11072                } else {
11073                    /*
11074                     * No package verification is enabled, so immediately start
11075                     * the remote call to initiate copy using temporary file.
11076                     */
11077                    ret = args.copyApk(mContainerService, true);
11078                }
11079            }
11080
11081            mRet = ret;
11082        }
11083
11084        @Override
11085        void handleReturnCode() {
11086            // If mArgs is null, then MCS couldn't be reached. When it
11087            // reconnects, it will try again to install. At that point, this
11088            // will succeed.
11089            if (mArgs != null) {
11090                processPendingInstall(mArgs, mRet);
11091            }
11092        }
11093
11094        @Override
11095        void handleServiceError() {
11096            mArgs = createInstallArgs(this);
11097            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11098        }
11099
11100        public boolean isForwardLocked() {
11101            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11102        }
11103    }
11104
11105    /**
11106     * Used during creation of InstallArgs
11107     *
11108     * @param installFlags package installation flags
11109     * @return true if should be installed on external storage
11110     */
11111    private static boolean installOnExternalAsec(int installFlags) {
11112        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
11113            return false;
11114        }
11115        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
11116            return true;
11117        }
11118        return false;
11119    }
11120
11121    /**
11122     * Used during creation of InstallArgs
11123     *
11124     * @param installFlags package installation flags
11125     * @return true if should be installed as forward locked
11126     */
11127    private static boolean installForwardLocked(int installFlags) {
11128        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11129    }
11130
11131    private InstallArgs createInstallArgs(InstallParams params) {
11132        if (params.move != null) {
11133            return new MoveInstallArgs(params);
11134        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
11135            return new AsecInstallArgs(params);
11136        } else {
11137            return new FileInstallArgs(params);
11138        }
11139    }
11140
11141    /**
11142     * Create args that describe an existing installed package. Typically used
11143     * when cleaning up old installs, or used as a move source.
11144     */
11145    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
11146            String resourcePath, String[] instructionSets) {
11147        final boolean isInAsec;
11148        if (installOnExternalAsec(installFlags)) {
11149            /* Apps on SD card are always in ASEC containers. */
11150            isInAsec = true;
11151        } else if (installForwardLocked(installFlags)
11152                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
11153            /*
11154             * Forward-locked apps are only in ASEC containers if they're the
11155             * new style
11156             */
11157            isInAsec = true;
11158        } else {
11159            isInAsec = false;
11160        }
11161
11162        if (isInAsec) {
11163            return new AsecInstallArgs(codePath, instructionSets,
11164                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
11165        } else {
11166            return new FileInstallArgs(codePath, resourcePath, instructionSets);
11167        }
11168    }
11169
11170    static abstract class InstallArgs {
11171        /** @see InstallParams#origin */
11172        final OriginInfo origin;
11173        /** @see InstallParams#move */
11174        final MoveInfo move;
11175
11176        final IPackageInstallObserver2 observer;
11177        // Always refers to PackageManager flags only
11178        final int installFlags;
11179        final String installerPackageName;
11180        final String volumeUuid;
11181        final ManifestDigest manifestDigest;
11182        final UserHandle user;
11183        final String abiOverride;
11184        final String[] installGrantPermissions;
11185        /** If non-null, drop an async trace when the install completes */
11186        final String traceMethod;
11187        final int traceCookie;
11188
11189        // The list of instruction sets supported by this app. This is currently
11190        // only used during the rmdex() phase to clean up resources. We can get rid of this
11191        // if we move dex files under the common app path.
11192        /* nullable */ String[] instructionSets;
11193
11194        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11195                int installFlags, String installerPackageName, String volumeUuid,
11196                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
11197                String abiOverride, String[] installGrantPermissions,
11198                String traceMethod, int traceCookie) {
11199            this.origin = origin;
11200            this.move = move;
11201            this.installFlags = installFlags;
11202            this.observer = observer;
11203            this.installerPackageName = installerPackageName;
11204            this.volumeUuid = volumeUuid;
11205            this.manifestDigest = manifestDigest;
11206            this.user = user;
11207            this.instructionSets = instructionSets;
11208            this.abiOverride = abiOverride;
11209            this.installGrantPermissions = installGrantPermissions;
11210            this.traceMethod = traceMethod;
11211            this.traceCookie = traceCookie;
11212        }
11213
11214        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
11215        abstract int doPreInstall(int status);
11216
11217        /**
11218         * Rename package into final resting place. All paths on the given
11219         * scanned package should be updated to reflect the rename.
11220         */
11221        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
11222        abstract int doPostInstall(int status, int uid);
11223
11224        /** @see PackageSettingBase#codePathString */
11225        abstract String getCodePath();
11226        /** @see PackageSettingBase#resourcePathString */
11227        abstract String getResourcePath();
11228
11229        // Need installer lock especially for dex file removal.
11230        abstract void cleanUpResourcesLI();
11231        abstract boolean doPostDeleteLI(boolean delete);
11232
11233        /**
11234         * Called before the source arguments are copied. This is used mostly
11235         * for MoveParams when it needs to read the source file to put it in the
11236         * destination.
11237         */
11238        int doPreCopy() {
11239            return PackageManager.INSTALL_SUCCEEDED;
11240        }
11241
11242        /**
11243         * Called after the source arguments are copied. This is used mostly for
11244         * MoveParams when it needs to read the source file to put it in the
11245         * destination.
11246         *
11247         * @return
11248         */
11249        int doPostCopy(int uid) {
11250            return PackageManager.INSTALL_SUCCEEDED;
11251        }
11252
11253        protected boolean isFwdLocked() {
11254            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11255        }
11256
11257        protected boolean isExternalAsec() {
11258            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11259        }
11260
11261        UserHandle getUser() {
11262            return user;
11263        }
11264    }
11265
11266    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
11267        if (!allCodePaths.isEmpty()) {
11268            if (instructionSets == null) {
11269                throw new IllegalStateException("instructionSet == null");
11270            }
11271            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
11272            for (String codePath : allCodePaths) {
11273                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
11274                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
11275                    if (retCode < 0) {
11276                        Slog.w(TAG, "Couldn't remove dex file for package: "
11277                                + " at location " + codePath + ", retcode=" + retCode);
11278                        // we don't consider this to be a failure of the core package deletion
11279                    }
11280                }
11281            }
11282        }
11283    }
11284
11285    /**
11286     * Logic to handle installation of non-ASEC applications, including copying
11287     * and renaming logic.
11288     */
11289    class FileInstallArgs extends InstallArgs {
11290        private File codeFile;
11291        private File resourceFile;
11292
11293        // Example topology:
11294        // /data/app/com.example/base.apk
11295        // /data/app/com.example/split_foo.apk
11296        // /data/app/com.example/lib/arm/libfoo.so
11297        // /data/app/com.example/lib/arm64/libfoo.so
11298        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11299
11300        /** New install */
11301        FileInstallArgs(InstallParams params) {
11302            super(params.origin, params.move, params.observer, params.installFlags,
11303                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11304                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11305                    params.grantedRuntimePermissions,
11306                    params.traceMethod, params.traceCookie);
11307            if (isFwdLocked()) {
11308                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11309            }
11310        }
11311
11312        /** Existing install */
11313        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11314            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
11315                    null, null, null, 0);
11316            this.codeFile = (codePath != null) ? new File(codePath) : null;
11317            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11318        }
11319
11320        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11321            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
11322            try {
11323                return doCopyApk(imcs, temp);
11324            } finally {
11325                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11326            }
11327        }
11328
11329        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11330            if (origin.staged) {
11331                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11332                codeFile = origin.file;
11333                resourceFile = origin.file;
11334                return PackageManager.INSTALL_SUCCEEDED;
11335            }
11336
11337            try {
11338                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
11339                codeFile = tempDir;
11340                resourceFile = tempDir;
11341            } catch (IOException e) {
11342                Slog.w(TAG, "Failed to create copy file: " + e);
11343                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11344            }
11345
11346            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11347                @Override
11348                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11349                    if (!FileUtils.isValidExtFilename(name)) {
11350                        throw new IllegalArgumentException("Invalid filename: " + name);
11351                    }
11352                    try {
11353                        final File file = new File(codeFile, name);
11354                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11355                                O_RDWR | O_CREAT, 0644);
11356                        Os.chmod(file.getAbsolutePath(), 0644);
11357                        return new ParcelFileDescriptor(fd);
11358                    } catch (ErrnoException e) {
11359                        throw new RemoteException("Failed to open: " + e.getMessage());
11360                    }
11361                }
11362            };
11363
11364            int ret = PackageManager.INSTALL_SUCCEEDED;
11365            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11366            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11367                Slog.e(TAG, "Failed to copy package");
11368                return ret;
11369            }
11370
11371            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11372            NativeLibraryHelper.Handle handle = null;
11373            try {
11374                handle = NativeLibraryHelper.Handle.create(codeFile);
11375                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11376                        abiOverride);
11377            } catch (IOException e) {
11378                Slog.e(TAG, "Copying native libraries failed", e);
11379                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11380            } finally {
11381                IoUtils.closeQuietly(handle);
11382            }
11383
11384            return ret;
11385        }
11386
11387        int doPreInstall(int status) {
11388            if (status != PackageManager.INSTALL_SUCCEEDED) {
11389                cleanUp();
11390            }
11391            return status;
11392        }
11393
11394        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11395            if (status != PackageManager.INSTALL_SUCCEEDED) {
11396                cleanUp();
11397                return false;
11398            }
11399
11400            final File targetDir = codeFile.getParentFile();
11401            final File beforeCodeFile = codeFile;
11402            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11403
11404            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11405            try {
11406                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11407            } catch (ErrnoException e) {
11408                Slog.w(TAG, "Failed to rename", e);
11409                return false;
11410            }
11411
11412            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11413                Slog.w(TAG, "Failed to restorecon");
11414                return false;
11415            }
11416
11417            // Reflect the rename internally
11418            codeFile = afterCodeFile;
11419            resourceFile = afterCodeFile;
11420
11421            // Reflect the rename in scanned details
11422            pkg.codePath = afterCodeFile.getAbsolutePath();
11423            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11424                    pkg.baseCodePath);
11425            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11426                    pkg.splitCodePaths);
11427
11428            // Reflect the rename in app info
11429            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11430            pkg.applicationInfo.setCodePath(pkg.codePath);
11431            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11432            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11433            pkg.applicationInfo.setResourcePath(pkg.codePath);
11434            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11435            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11436
11437            return true;
11438        }
11439
11440        int doPostInstall(int status, int uid) {
11441            if (status != PackageManager.INSTALL_SUCCEEDED) {
11442                cleanUp();
11443            }
11444            return status;
11445        }
11446
11447        @Override
11448        String getCodePath() {
11449            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11450        }
11451
11452        @Override
11453        String getResourcePath() {
11454            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11455        }
11456
11457        private boolean cleanUp() {
11458            if (codeFile == null || !codeFile.exists()) {
11459                return false;
11460            }
11461
11462            if (codeFile.isDirectory()) {
11463                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11464            } else {
11465                codeFile.delete();
11466            }
11467
11468            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11469                resourceFile.delete();
11470            }
11471
11472            return true;
11473        }
11474
11475        void cleanUpResourcesLI() {
11476            // Try enumerating all code paths before deleting
11477            List<String> allCodePaths = Collections.EMPTY_LIST;
11478            if (codeFile != null && codeFile.exists()) {
11479                try {
11480                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11481                    allCodePaths = pkg.getAllCodePaths();
11482                } catch (PackageParserException e) {
11483                    // Ignored; we tried our best
11484                }
11485            }
11486
11487            cleanUp();
11488            removeDexFiles(allCodePaths, instructionSets);
11489        }
11490
11491        boolean doPostDeleteLI(boolean delete) {
11492            // XXX err, shouldn't we respect the delete flag?
11493            cleanUpResourcesLI();
11494            return true;
11495        }
11496    }
11497
11498    private boolean isAsecExternal(String cid) {
11499        final String asecPath = PackageHelper.getSdFilesystem(cid);
11500        return !asecPath.startsWith(mAsecInternalPath);
11501    }
11502
11503    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11504            PackageManagerException {
11505        if (copyRet < 0) {
11506            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11507                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11508                throw new PackageManagerException(copyRet, message);
11509            }
11510        }
11511    }
11512
11513    /**
11514     * Extract the MountService "container ID" from the full code path of an
11515     * .apk.
11516     */
11517    static String cidFromCodePath(String fullCodePath) {
11518        int eidx = fullCodePath.lastIndexOf("/");
11519        String subStr1 = fullCodePath.substring(0, eidx);
11520        int sidx = subStr1.lastIndexOf("/");
11521        return subStr1.substring(sidx+1, eidx);
11522    }
11523
11524    /**
11525     * Logic to handle installation of ASEC applications, including copying and
11526     * renaming logic.
11527     */
11528    class AsecInstallArgs extends InstallArgs {
11529        static final String RES_FILE_NAME = "pkg.apk";
11530        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11531
11532        String cid;
11533        String packagePath;
11534        String resourcePath;
11535
11536        /** New install */
11537        AsecInstallArgs(InstallParams params) {
11538            super(params.origin, params.move, params.observer, params.installFlags,
11539                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11540                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11541                    params.grantedRuntimePermissions,
11542                    params.traceMethod, params.traceCookie);
11543        }
11544
11545        /** Existing install */
11546        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11547                        boolean isExternal, boolean isForwardLocked) {
11548            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11549                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11550                    instructionSets, null, null, null, 0);
11551            // Hackily pretend we're still looking at a full code path
11552            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11553                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11554            }
11555
11556            // Extract cid from fullCodePath
11557            int eidx = fullCodePath.lastIndexOf("/");
11558            String subStr1 = fullCodePath.substring(0, eidx);
11559            int sidx = subStr1.lastIndexOf("/");
11560            cid = subStr1.substring(sidx+1, eidx);
11561            setMountPath(subStr1);
11562        }
11563
11564        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11565            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11566                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11567                    instructionSets, null, null, null, 0);
11568            this.cid = cid;
11569            setMountPath(PackageHelper.getSdDir(cid));
11570        }
11571
11572        void createCopyFile() {
11573            cid = mInstallerService.allocateExternalStageCidLegacy();
11574        }
11575
11576        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11577            if (origin.staged) {
11578                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11579                cid = origin.cid;
11580                setMountPath(PackageHelper.getSdDir(cid));
11581                return PackageManager.INSTALL_SUCCEEDED;
11582            }
11583
11584            if (temp) {
11585                createCopyFile();
11586            } else {
11587                /*
11588                 * Pre-emptively destroy the container since it's destroyed if
11589                 * copying fails due to it existing anyway.
11590                 */
11591                PackageHelper.destroySdDir(cid);
11592            }
11593
11594            final String newMountPath = imcs.copyPackageToContainer(
11595                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11596                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11597
11598            if (newMountPath != null) {
11599                setMountPath(newMountPath);
11600                return PackageManager.INSTALL_SUCCEEDED;
11601            } else {
11602                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11603            }
11604        }
11605
11606        @Override
11607        String getCodePath() {
11608            return packagePath;
11609        }
11610
11611        @Override
11612        String getResourcePath() {
11613            return resourcePath;
11614        }
11615
11616        int doPreInstall(int status) {
11617            if (status != PackageManager.INSTALL_SUCCEEDED) {
11618                // Destroy container
11619                PackageHelper.destroySdDir(cid);
11620            } else {
11621                boolean mounted = PackageHelper.isContainerMounted(cid);
11622                if (!mounted) {
11623                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11624                            Process.SYSTEM_UID);
11625                    if (newMountPath != null) {
11626                        setMountPath(newMountPath);
11627                    } else {
11628                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11629                    }
11630                }
11631            }
11632            return status;
11633        }
11634
11635        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11636            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11637            String newMountPath = null;
11638            if (PackageHelper.isContainerMounted(cid)) {
11639                // Unmount the container
11640                if (!PackageHelper.unMountSdDir(cid)) {
11641                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11642                    return false;
11643                }
11644            }
11645            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11646                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11647                        " which might be stale. Will try to clean up.");
11648                // Clean up the stale container and proceed to recreate.
11649                if (!PackageHelper.destroySdDir(newCacheId)) {
11650                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11651                    return false;
11652                }
11653                // Successfully cleaned up stale container. Try to rename again.
11654                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11655                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11656                            + " inspite of cleaning it up.");
11657                    return false;
11658                }
11659            }
11660            if (!PackageHelper.isContainerMounted(newCacheId)) {
11661                Slog.w(TAG, "Mounting container " + newCacheId);
11662                newMountPath = PackageHelper.mountSdDir(newCacheId,
11663                        getEncryptKey(), Process.SYSTEM_UID);
11664            } else {
11665                newMountPath = PackageHelper.getSdDir(newCacheId);
11666            }
11667            if (newMountPath == null) {
11668                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11669                return false;
11670            }
11671            Log.i(TAG, "Succesfully renamed " + cid +
11672                    " to " + newCacheId +
11673                    " at new path: " + newMountPath);
11674            cid = newCacheId;
11675
11676            final File beforeCodeFile = new File(packagePath);
11677            setMountPath(newMountPath);
11678            final File afterCodeFile = new File(packagePath);
11679
11680            // Reflect the rename in scanned details
11681            pkg.codePath = afterCodeFile.getAbsolutePath();
11682            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11683                    pkg.baseCodePath);
11684            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11685                    pkg.splitCodePaths);
11686
11687            // Reflect the rename in app info
11688            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11689            pkg.applicationInfo.setCodePath(pkg.codePath);
11690            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11691            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11692            pkg.applicationInfo.setResourcePath(pkg.codePath);
11693            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11694            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11695
11696            return true;
11697        }
11698
11699        private void setMountPath(String mountPath) {
11700            final File mountFile = new File(mountPath);
11701
11702            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11703            if (monolithicFile.exists()) {
11704                packagePath = monolithicFile.getAbsolutePath();
11705                if (isFwdLocked()) {
11706                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11707                } else {
11708                    resourcePath = packagePath;
11709                }
11710            } else {
11711                packagePath = mountFile.getAbsolutePath();
11712                resourcePath = packagePath;
11713            }
11714        }
11715
11716        int doPostInstall(int status, int uid) {
11717            if (status != PackageManager.INSTALL_SUCCEEDED) {
11718                cleanUp();
11719            } else {
11720                final int groupOwner;
11721                final String protectedFile;
11722                if (isFwdLocked()) {
11723                    groupOwner = UserHandle.getSharedAppGid(uid);
11724                    protectedFile = RES_FILE_NAME;
11725                } else {
11726                    groupOwner = -1;
11727                    protectedFile = null;
11728                }
11729
11730                if (uid < Process.FIRST_APPLICATION_UID
11731                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11732                    Slog.e(TAG, "Failed to finalize " + cid);
11733                    PackageHelper.destroySdDir(cid);
11734                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11735                }
11736
11737                boolean mounted = PackageHelper.isContainerMounted(cid);
11738                if (!mounted) {
11739                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11740                }
11741            }
11742            return status;
11743        }
11744
11745        private void cleanUp() {
11746            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11747
11748            // Destroy secure container
11749            PackageHelper.destroySdDir(cid);
11750        }
11751
11752        private List<String> getAllCodePaths() {
11753            final File codeFile = new File(getCodePath());
11754            if (codeFile != null && codeFile.exists()) {
11755                try {
11756                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11757                    return pkg.getAllCodePaths();
11758                } catch (PackageParserException e) {
11759                    // Ignored; we tried our best
11760                }
11761            }
11762            return Collections.EMPTY_LIST;
11763        }
11764
11765        void cleanUpResourcesLI() {
11766            // Enumerate all code paths before deleting
11767            cleanUpResourcesLI(getAllCodePaths());
11768        }
11769
11770        private void cleanUpResourcesLI(List<String> allCodePaths) {
11771            cleanUp();
11772            removeDexFiles(allCodePaths, instructionSets);
11773        }
11774
11775        String getPackageName() {
11776            return getAsecPackageName(cid);
11777        }
11778
11779        boolean doPostDeleteLI(boolean delete) {
11780            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11781            final List<String> allCodePaths = getAllCodePaths();
11782            boolean mounted = PackageHelper.isContainerMounted(cid);
11783            if (mounted) {
11784                // Unmount first
11785                if (PackageHelper.unMountSdDir(cid)) {
11786                    mounted = false;
11787                }
11788            }
11789            if (!mounted && delete) {
11790                cleanUpResourcesLI(allCodePaths);
11791            }
11792            return !mounted;
11793        }
11794
11795        @Override
11796        int doPreCopy() {
11797            if (isFwdLocked()) {
11798                if (!PackageHelper.fixSdPermissions(cid,
11799                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11800                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11801                }
11802            }
11803
11804            return PackageManager.INSTALL_SUCCEEDED;
11805        }
11806
11807        @Override
11808        int doPostCopy(int uid) {
11809            if (isFwdLocked()) {
11810                if (uid < Process.FIRST_APPLICATION_UID
11811                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11812                                RES_FILE_NAME)) {
11813                    Slog.e(TAG, "Failed to finalize " + cid);
11814                    PackageHelper.destroySdDir(cid);
11815                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11816                }
11817            }
11818
11819            return PackageManager.INSTALL_SUCCEEDED;
11820        }
11821    }
11822
11823    /**
11824     * Logic to handle movement of existing installed applications.
11825     */
11826    class MoveInstallArgs extends InstallArgs {
11827        private File codeFile;
11828        private File resourceFile;
11829
11830        /** New install */
11831        MoveInstallArgs(InstallParams params) {
11832            super(params.origin, params.move, params.observer, params.installFlags,
11833                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11834                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11835                    params.grantedRuntimePermissions,
11836                    params.traceMethod, params.traceCookie);
11837        }
11838
11839        int copyApk(IMediaContainerService imcs, boolean temp) {
11840            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11841                    + move.fromUuid + " to " + move.toUuid);
11842            synchronized (mInstaller) {
11843                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11844                        move.dataAppName, move.appId, move.seinfo) != 0) {
11845                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11846                }
11847            }
11848
11849            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11850            resourceFile = codeFile;
11851            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11852
11853            return PackageManager.INSTALL_SUCCEEDED;
11854        }
11855
11856        int doPreInstall(int status) {
11857            if (status != PackageManager.INSTALL_SUCCEEDED) {
11858                cleanUp(move.toUuid);
11859            }
11860            return status;
11861        }
11862
11863        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11864            if (status != PackageManager.INSTALL_SUCCEEDED) {
11865                cleanUp(move.toUuid);
11866                return false;
11867            }
11868
11869            // Reflect the move in app info
11870            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11871            pkg.applicationInfo.setCodePath(pkg.codePath);
11872            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11873            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11874            pkg.applicationInfo.setResourcePath(pkg.codePath);
11875            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11876            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11877
11878            return true;
11879        }
11880
11881        int doPostInstall(int status, int uid) {
11882            if (status == PackageManager.INSTALL_SUCCEEDED) {
11883                cleanUp(move.fromUuid);
11884            } else {
11885                cleanUp(move.toUuid);
11886            }
11887            return status;
11888        }
11889
11890        @Override
11891        String getCodePath() {
11892            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11893        }
11894
11895        @Override
11896        String getResourcePath() {
11897            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11898        }
11899
11900        private boolean cleanUp(String volumeUuid) {
11901            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11902                    move.dataAppName);
11903            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11904            synchronized (mInstallLock) {
11905                // Clean up both app data and code
11906                removeDataDirsLI(volumeUuid, move.packageName);
11907                if (codeFile.isDirectory()) {
11908                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11909                } else {
11910                    codeFile.delete();
11911                }
11912            }
11913            return true;
11914        }
11915
11916        void cleanUpResourcesLI() {
11917            throw new UnsupportedOperationException();
11918        }
11919
11920        boolean doPostDeleteLI(boolean delete) {
11921            throw new UnsupportedOperationException();
11922        }
11923    }
11924
11925    static String getAsecPackageName(String packageCid) {
11926        int idx = packageCid.lastIndexOf("-");
11927        if (idx == -1) {
11928            return packageCid;
11929        }
11930        return packageCid.substring(0, idx);
11931    }
11932
11933    // Utility method used to create code paths based on package name and available index.
11934    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11935        String idxStr = "";
11936        int idx = 1;
11937        // Fall back to default value of idx=1 if prefix is not
11938        // part of oldCodePath
11939        if (oldCodePath != null) {
11940            String subStr = oldCodePath;
11941            // Drop the suffix right away
11942            if (suffix != null && subStr.endsWith(suffix)) {
11943                subStr = subStr.substring(0, subStr.length() - suffix.length());
11944            }
11945            // If oldCodePath already contains prefix find out the
11946            // ending index to either increment or decrement.
11947            int sidx = subStr.lastIndexOf(prefix);
11948            if (sidx != -1) {
11949                subStr = subStr.substring(sidx + prefix.length());
11950                if (subStr != null) {
11951                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11952                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11953                    }
11954                    try {
11955                        idx = Integer.parseInt(subStr);
11956                        if (idx <= 1) {
11957                            idx++;
11958                        } else {
11959                            idx--;
11960                        }
11961                    } catch(NumberFormatException e) {
11962                    }
11963                }
11964            }
11965        }
11966        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11967        return prefix + idxStr;
11968    }
11969
11970    private File getNextCodePath(File targetDir, String packageName) {
11971        int suffix = 1;
11972        File result;
11973        do {
11974            result = new File(targetDir, packageName + "-" + suffix);
11975            suffix++;
11976        } while (result.exists());
11977        return result;
11978    }
11979
11980    // Utility method that returns the relative package path with respect
11981    // to the installation directory. Like say for /data/data/com.test-1.apk
11982    // string com.test-1 is returned.
11983    static String deriveCodePathName(String codePath) {
11984        if (codePath == null) {
11985            return null;
11986        }
11987        final File codeFile = new File(codePath);
11988        final String name = codeFile.getName();
11989        if (codeFile.isDirectory()) {
11990            return name;
11991        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11992            final int lastDot = name.lastIndexOf('.');
11993            return name.substring(0, lastDot);
11994        } else {
11995            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11996            return null;
11997        }
11998    }
11999
12000    class PackageInstalledInfo {
12001        String name;
12002        int uid;
12003        // The set of users that originally had this package installed.
12004        int[] origUsers;
12005        // The set of users that now have this package installed.
12006        int[] newUsers;
12007        PackageParser.Package pkg;
12008        int returnCode;
12009        String returnMsg;
12010        PackageRemovedInfo removedInfo;
12011
12012        public void setError(int code, String msg) {
12013            returnCode = code;
12014            returnMsg = msg;
12015            Slog.w(TAG, msg);
12016        }
12017
12018        public void setError(String msg, PackageParserException e) {
12019            returnCode = e.error;
12020            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12021            Slog.w(TAG, msg, e);
12022        }
12023
12024        public void setError(String msg, PackageManagerException e) {
12025            returnCode = e.error;
12026            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12027            Slog.w(TAG, msg, e);
12028        }
12029
12030        // In some error cases we want to convey more info back to the observer
12031        String origPackage;
12032        String origPermission;
12033    }
12034
12035    /*
12036     * Install a non-existing package.
12037     */
12038    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12039            UserHandle user, String installerPackageName, String volumeUuid,
12040            PackageInstalledInfo res) {
12041        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
12042
12043        // Remember this for later, in case we need to rollback this install
12044        String pkgName = pkg.packageName;
12045
12046        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
12047        // TODO: b/23350563
12048        final boolean dataDirExists = Environment
12049                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists();
12050
12051        synchronized(mPackages) {
12052            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
12053                // A package with the same name is already installed, though
12054                // it has been renamed to an older name.  The package we
12055                // are trying to install should be installed as an update to
12056                // the existing one, but that has not been requested, so bail.
12057                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12058                        + " without first uninstalling package running as "
12059                        + mSettings.mRenamedPackages.get(pkgName));
12060                return;
12061            }
12062            if (mPackages.containsKey(pkgName)) {
12063                // Don't allow installation over an existing package with the same name.
12064                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12065                        + " without first uninstalling.");
12066                return;
12067            }
12068        }
12069
12070        try {
12071            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
12072                    System.currentTimeMillis(), user);
12073
12074            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
12075            // delete the partially installed application. the data directory will have to be
12076            // restored if it was already existing
12077            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12078                // remove package from internal structures.  Note that we want deletePackageX to
12079                // delete the package data and cache directories that it created in
12080                // scanPackageLocked, unless those directories existed before we even tried to
12081                // install.
12082                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
12083                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
12084                                res.removedInfo, true);
12085            }
12086
12087        } catch (PackageManagerException e) {
12088            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12089        }
12090
12091        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12092    }
12093
12094    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
12095        // Can't rotate keys during boot or if sharedUser.
12096        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
12097                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
12098            return false;
12099        }
12100        // app is using upgradeKeySets; make sure all are valid
12101        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12102        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
12103        for (int i = 0; i < upgradeKeySets.length; i++) {
12104            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
12105                Slog.wtf(TAG, "Package "
12106                         + (oldPs.name != null ? oldPs.name : "<null>")
12107                         + " contains upgrade-key-set reference to unknown key-set: "
12108                         + upgradeKeySets[i]
12109                         + " reverting to signatures check.");
12110                return false;
12111            }
12112        }
12113        return true;
12114    }
12115
12116    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
12117        // Upgrade keysets are being used.  Determine if new package has a superset of the
12118        // required keys.
12119        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
12120        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12121        for (int i = 0; i < upgradeKeySets.length; i++) {
12122            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
12123            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
12124                return true;
12125            }
12126        }
12127        return false;
12128    }
12129
12130    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12131            UserHandle user, String installerPackageName, String volumeUuid,
12132            PackageInstalledInfo res) {
12133        final PackageParser.Package oldPackage;
12134        final String pkgName = pkg.packageName;
12135        final int[] allUsers;
12136        final boolean[] perUserInstalled;
12137
12138        // First find the old package info and check signatures
12139        synchronized(mPackages) {
12140            oldPackage = mPackages.get(pkgName);
12141            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
12142            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12143            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12144                if(!checkUpgradeKeySetLP(ps, pkg)) {
12145                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12146                            "New package not signed by keys specified by upgrade-keysets: "
12147                            + pkgName);
12148                    return;
12149                }
12150            } else {
12151                // default to original signature matching
12152                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
12153                    != PackageManager.SIGNATURE_MATCH) {
12154                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12155                            "New package has a different signature: " + pkgName);
12156                    return;
12157                }
12158            }
12159
12160            // In case of rollback, remember per-user/profile install state
12161            allUsers = sUserManager.getUserIds();
12162            perUserInstalled = new boolean[allUsers.length];
12163            for (int i = 0; i < allUsers.length; i++) {
12164                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12165            }
12166        }
12167
12168        boolean sysPkg = (isSystemApp(oldPackage));
12169        if (sysPkg) {
12170            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12171                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12172        } else {
12173            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12174                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12175        }
12176    }
12177
12178    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
12179            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12180            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12181            String volumeUuid, PackageInstalledInfo res) {
12182        String pkgName = deletedPackage.packageName;
12183        boolean deletedPkg = true;
12184        boolean updatedSettings = false;
12185
12186        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
12187                + deletedPackage);
12188        long origUpdateTime;
12189        if (pkg.mExtras != null) {
12190            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
12191        } else {
12192            origUpdateTime = 0;
12193        }
12194
12195        // First delete the existing package while retaining the data directory
12196        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
12197                res.removedInfo, true)) {
12198            // If the existing package wasn't successfully deleted
12199            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
12200            deletedPkg = false;
12201        } else {
12202            // Successfully deleted the old package; proceed with replace.
12203
12204            // If deleted package lived in a container, give users a chance to
12205            // relinquish resources before killing.
12206            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
12207                if (DEBUG_INSTALL) {
12208                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
12209                }
12210                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
12211                final ArrayList<String> pkgList = new ArrayList<String>(1);
12212                pkgList.add(deletedPackage.applicationInfo.packageName);
12213                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
12214            }
12215
12216            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
12217            try {
12218                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
12219                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
12220                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12221                        perUserInstalled, res, user);
12222                updatedSettings = true;
12223            } catch (PackageManagerException e) {
12224                res.setError("Package couldn't be installed in " + pkg.codePath, e);
12225            }
12226        }
12227
12228        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12229            // remove package from internal structures.  Note that we want deletePackageX to
12230            // delete the package data and cache directories that it created in
12231            // scanPackageLocked, unless those directories existed before we even tried to
12232            // install.
12233            if(updatedSettings) {
12234                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
12235                deletePackageLI(
12236                        pkgName, null, true, allUsers, perUserInstalled,
12237                        PackageManager.DELETE_KEEP_DATA,
12238                                res.removedInfo, true);
12239            }
12240            // Since we failed to install the new package we need to restore the old
12241            // package that we deleted.
12242            if (deletedPkg) {
12243                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
12244                File restoreFile = new File(deletedPackage.codePath);
12245                // Parse old package
12246                boolean oldExternal = isExternal(deletedPackage);
12247                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
12248                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
12249                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12250                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
12251                try {
12252                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
12253                            null);
12254                } catch (PackageManagerException e) {
12255                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
12256                            + e.getMessage());
12257                    return;
12258                }
12259                // Restore of old package succeeded. Update permissions.
12260                // writer
12261                synchronized (mPackages) {
12262                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
12263                            UPDATE_PERMISSIONS_ALL);
12264                    // can downgrade to reader
12265                    mSettings.writeLPr();
12266                }
12267                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
12268            }
12269        }
12270    }
12271
12272    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
12273            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12274            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12275            String volumeUuid, PackageInstalledInfo res) {
12276        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
12277                + ", old=" + deletedPackage);
12278        boolean disabledSystem = false;
12279        boolean updatedSettings = false;
12280        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
12281        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
12282                != 0) {
12283            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12284        }
12285        String packageName = deletedPackage.packageName;
12286        if (packageName == null) {
12287            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12288                    "Attempt to delete null packageName.");
12289            return;
12290        }
12291        PackageParser.Package oldPkg;
12292        PackageSetting oldPkgSetting;
12293        // reader
12294        synchronized (mPackages) {
12295            oldPkg = mPackages.get(packageName);
12296            oldPkgSetting = mSettings.mPackages.get(packageName);
12297            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
12298                    (oldPkgSetting == null)) {
12299                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12300                        "Couldn't find package:" + packageName + " information");
12301                return;
12302            }
12303        }
12304
12305        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12306
12307        res.removedInfo.uid = oldPkg.applicationInfo.uid;
12308        res.removedInfo.removedPackage = packageName;
12309        // Remove existing system package
12310        removePackageLI(oldPkgSetting, true);
12311        // writer
12312        synchronized (mPackages) {
12313            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12314            if (!disabledSystem && deletedPackage != null) {
12315                // We didn't need to disable the .apk as a current system package,
12316                // which means we are replacing another update that is already
12317                // installed.  We need to make sure to delete the older one's .apk.
12318                res.removedInfo.args = createInstallArgsForExisting(0,
12319                        deletedPackage.applicationInfo.getCodePath(),
12320                        deletedPackage.applicationInfo.getResourcePath(),
12321                        getAppDexInstructionSets(deletedPackage.applicationInfo));
12322            } else {
12323                res.removedInfo.args = null;
12324            }
12325        }
12326
12327        // Successfully disabled the old package. Now proceed with re-installation
12328        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12329
12330        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12331        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12332
12333        PackageParser.Package newPackage = null;
12334        try {
12335            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
12336            if (newPackage.mExtras != null) {
12337                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12338                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12339                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12340
12341                // is the update attempting to change shared user? that isn't going to work...
12342                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12343                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12344                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12345                            + " to " + newPkgSetting.sharedUser);
12346                    updatedSettings = true;
12347                }
12348            }
12349
12350            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12351                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12352                        perUserInstalled, res, user);
12353                updatedSettings = true;
12354            }
12355
12356        } catch (PackageManagerException e) {
12357            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12358        }
12359
12360        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12361            // Re installation failed. Restore old information
12362            // Remove new pkg information
12363            if (newPackage != null) {
12364                removeInstalledPackageLI(newPackage, true);
12365            }
12366            // Add back the old system package
12367            try {
12368                scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12369            } catch (PackageManagerException e) {
12370                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12371            }
12372            // Restore the old system information in Settings
12373            synchronized (mPackages) {
12374                if (disabledSystem) {
12375                    mSettings.enableSystemPackageLPw(packageName);
12376                }
12377                if (updatedSettings) {
12378                    mSettings.setInstallerPackageName(packageName,
12379                            oldPkgSetting.installerPackageName);
12380                }
12381                mSettings.writeLPr();
12382            }
12383        }
12384    }
12385
12386    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
12387        // Collect all used permissions in the UID
12388        ArraySet<String> usedPermissions = new ArraySet<>();
12389        final int packageCount = su.packages.size();
12390        for (int i = 0; i < packageCount; i++) {
12391            PackageSetting ps = su.packages.valueAt(i);
12392            if (ps.pkg == null) {
12393                continue;
12394            }
12395            final int requestedPermCount = ps.pkg.requestedPermissions.size();
12396            for (int j = 0; j < requestedPermCount; j++) {
12397                String permission = ps.pkg.requestedPermissions.get(j);
12398                BasePermission bp = mSettings.mPermissions.get(permission);
12399                if (bp != null) {
12400                    usedPermissions.add(permission);
12401                }
12402            }
12403        }
12404
12405        PermissionsState permissionsState = su.getPermissionsState();
12406        // Prune install permissions
12407        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
12408        final int installPermCount = installPermStates.size();
12409        for (int i = installPermCount - 1; i >= 0;  i--) {
12410            PermissionState permissionState = installPermStates.get(i);
12411            if (!usedPermissions.contains(permissionState.getName())) {
12412                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12413                if (bp != null) {
12414                    permissionsState.revokeInstallPermission(bp);
12415                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12416                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12417                }
12418            }
12419        }
12420
12421        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
12422
12423        // Prune runtime permissions
12424        for (int userId : allUserIds) {
12425            List<PermissionState> runtimePermStates = permissionsState
12426                    .getRuntimePermissionStates(userId);
12427            final int runtimePermCount = runtimePermStates.size();
12428            for (int i = runtimePermCount - 1; i >= 0; i--) {
12429                PermissionState permissionState = runtimePermStates.get(i);
12430                if (!usedPermissions.contains(permissionState.getName())) {
12431                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12432                    if (bp != null) {
12433                        permissionsState.revokeRuntimePermission(bp, userId);
12434                        permissionsState.updatePermissionFlags(bp, userId,
12435                                PackageManager.MASK_PERMISSION_FLAGS, 0);
12436                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
12437                                runtimePermissionChangedUserIds, userId);
12438                    }
12439                }
12440            }
12441        }
12442
12443        return runtimePermissionChangedUserIds;
12444    }
12445
12446    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12447            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12448            UserHandle user) {
12449        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
12450
12451        String pkgName = newPackage.packageName;
12452        synchronized (mPackages) {
12453            //write settings. the installStatus will be incomplete at this stage.
12454            //note that the new package setting would have already been
12455            //added to mPackages. It hasn't been persisted yet.
12456            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12457            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12458            mSettings.writeLPr();
12459            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12460        }
12461
12462        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12463        synchronized (mPackages) {
12464            updatePermissionsLPw(newPackage.packageName, newPackage,
12465                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12466                            ? UPDATE_PERMISSIONS_ALL : 0));
12467            // For system-bundled packages, we assume that installing an upgraded version
12468            // of the package implies that the user actually wants to run that new code,
12469            // so we enable the package.
12470            PackageSetting ps = mSettings.mPackages.get(pkgName);
12471            if (ps != null) {
12472                if (isSystemApp(newPackage)) {
12473                    // NB: implicit assumption that system package upgrades apply to all users
12474                    if (DEBUG_INSTALL) {
12475                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12476                    }
12477                    if (res.origUsers != null) {
12478                        for (int userHandle : res.origUsers) {
12479                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12480                                    userHandle, installerPackageName);
12481                        }
12482                    }
12483                    // Also convey the prior install/uninstall state
12484                    if (allUsers != null && perUserInstalled != null) {
12485                        for (int i = 0; i < allUsers.length; i++) {
12486                            if (DEBUG_INSTALL) {
12487                                Slog.d(TAG, "    user " + allUsers[i]
12488                                        + " => " + perUserInstalled[i]);
12489                            }
12490                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12491                        }
12492                        // these install state changes will be persisted in the
12493                        // upcoming call to mSettings.writeLPr().
12494                    }
12495                }
12496                // It's implied that when a user requests installation, they want the app to be
12497                // installed and enabled.
12498                int userId = user.getIdentifier();
12499                if (userId != UserHandle.USER_ALL) {
12500                    ps.setInstalled(true, userId);
12501                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12502                }
12503            }
12504            res.name = pkgName;
12505            res.uid = newPackage.applicationInfo.uid;
12506            res.pkg = newPackage;
12507            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12508            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12509            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12510            //to update install status
12511            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12512            mSettings.writeLPr();
12513            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12514        }
12515
12516        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12517    }
12518
12519    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
12520        try {
12521            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
12522            installPackageLI(args, res);
12523        } finally {
12524            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12525        }
12526    }
12527
12528    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12529        final int installFlags = args.installFlags;
12530        final String installerPackageName = args.installerPackageName;
12531        final String volumeUuid = args.volumeUuid;
12532        final File tmpPackageFile = new File(args.getCodePath());
12533        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12534        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12535                || (args.volumeUuid != null));
12536        final boolean quickInstall = ((installFlags & PackageManager.INSTALL_QUICK) != 0);
12537        boolean replace = false;
12538        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12539        if (args.move != null) {
12540            // moving a complete application; perfom an initial scan on the new install location
12541            scanFlags |= SCAN_INITIAL;
12542        }
12543        // Result object to be returned
12544        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12545
12546        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12547
12548        // Retrieve PackageSettings and parse package
12549        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12550                | PackageParser.PARSE_ENFORCE_CODE
12551                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12552                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
12553                | (quickInstall ? PackageParser.PARSE_SKIP_VERIFICATION : 0);
12554        PackageParser pp = new PackageParser();
12555        pp.setSeparateProcesses(mSeparateProcesses);
12556        pp.setDisplayMetrics(mMetrics);
12557
12558        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
12559        final PackageParser.Package pkg;
12560        try {
12561            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12562        } catch (PackageParserException e) {
12563            res.setError("Failed parse during installPackageLI", e);
12564            return;
12565        } finally {
12566            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12567        }
12568
12569        // Mark that we have an install time CPU ABI override.
12570        pkg.cpuAbiOverride = args.abiOverride;
12571
12572        String pkgName = res.name = pkg.packageName;
12573        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12574            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12575                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12576                return;
12577            }
12578        }
12579
12580        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
12581        try {
12582            pp.collectCertificates(pkg, parseFlags);
12583        } catch (PackageParserException e) {
12584            res.setError("Failed collect during installPackageLI", e);
12585            return;
12586        } finally {
12587            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12588        }
12589
12590        /* If the installer passed in a manifest digest, compare it now. */
12591        if (args.manifestDigest != null) {
12592            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectManifestDigest");
12593            try {
12594                pp.collectManifestDigest(pkg);
12595            } catch (PackageParserException e) {
12596                res.setError("Failed collect during installPackageLI", e);
12597                return;
12598            } finally {
12599                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12600            }
12601
12602            if (DEBUG_INSTALL) {
12603                final String parsedManifest = pkg.manifestDigest == null ? "null"
12604                        : pkg.manifestDigest.toString();
12605                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12606                        + parsedManifest);
12607            }
12608
12609            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12610                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12611                return;
12612            }
12613        } else if (DEBUG_INSTALL) {
12614            final String parsedManifest = pkg.manifestDigest == null
12615                    ? "null" : pkg.manifestDigest.toString();
12616            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12617        }
12618
12619        // Get rid of all references to package scan path via parser.
12620        pp = null;
12621        String oldCodePath = null;
12622        boolean systemApp = false;
12623        synchronized (mPackages) {
12624            // Check if installing already existing package
12625            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12626                String oldName = mSettings.mRenamedPackages.get(pkgName);
12627                if (pkg.mOriginalPackages != null
12628                        && pkg.mOriginalPackages.contains(oldName)
12629                        && mPackages.containsKey(oldName)) {
12630                    // This package is derived from an original package,
12631                    // and this device has been updating from that original
12632                    // name.  We must continue using the original name, so
12633                    // rename the new package here.
12634                    pkg.setPackageName(oldName);
12635                    pkgName = pkg.packageName;
12636                    replace = true;
12637                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12638                            + oldName + " pkgName=" + pkgName);
12639                } else if (mPackages.containsKey(pkgName)) {
12640                    // This package, under its official name, already exists
12641                    // on the device; we should replace it.
12642                    replace = true;
12643                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12644                }
12645
12646                // Prevent apps opting out from runtime permissions
12647                if (replace) {
12648                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12649                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12650                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12651                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12652                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12653                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12654                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12655                                        + " doesn't support runtime permissions but the old"
12656                                        + " target SDK " + oldTargetSdk + " does.");
12657                        return;
12658                    }
12659                }
12660            }
12661
12662            PackageSetting ps = mSettings.mPackages.get(pkgName);
12663            if (ps != null) {
12664                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12665
12666                // Quick sanity check that we're signed correctly if updating;
12667                // we'll check this again later when scanning, but we want to
12668                // bail early here before tripping over redefined permissions.
12669                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12670                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12671                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12672                                + pkg.packageName + " upgrade keys do not match the "
12673                                + "previously installed version");
12674                        return;
12675                    }
12676                } else {
12677                    try {
12678                        verifySignaturesLP(ps, pkg);
12679                    } catch (PackageManagerException e) {
12680                        res.setError(e.error, e.getMessage());
12681                        return;
12682                    }
12683                }
12684
12685                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12686                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12687                    systemApp = (ps.pkg.applicationInfo.flags &
12688                            ApplicationInfo.FLAG_SYSTEM) != 0;
12689                }
12690                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12691            }
12692
12693            // Check whether the newly-scanned package wants to define an already-defined perm
12694            int N = pkg.permissions.size();
12695            for (int i = N-1; i >= 0; i--) {
12696                PackageParser.Permission perm = pkg.permissions.get(i);
12697                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12698                if (bp != null) {
12699                    // If the defining package is signed with our cert, it's okay.  This
12700                    // also includes the "updating the same package" case, of course.
12701                    // "updating same package" could also involve key-rotation.
12702                    final boolean sigsOk;
12703                    if (bp.sourcePackage.equals(pkg.packageName)
12704                            && (bp.packageSetting instanceof PackageSetting)
12705                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12706                                    scanFlags))) {
12707                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12708                    } else {
12709                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12710                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12711                    }
12712                    if (!sigsOk) {
12713                        // If the owning package is the system itself, we log but allow
12714                        // install to proceed; we fail the install on all other permission
12715                        // redefinitions.
12716                        if (!bp.sourcePackage.equals("android")) {
12717                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12718                                    + pkg.packageName + " attempting to redeclare permission "
12719                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12720                            res.origPermission = perm.info.name;
12721                            res.origPackage = bp.sourcePackage;
12722                            return;
12723                        } else {
12724                            Slog.w(TAG, "Package " + pkg.packageName
12725                                    + " attempting to redeclare system permission "
12726                                    + perm.info.name + "; ignoring new declaration");
12727                            pkg.permissions.remove(i);
12728                        }
12729                    }
12730                }
12731            }
12732
12733        }
12734
12735        if (systemApp && onExternal) {
12736            // Disable updates to system apps on sdcard
12737            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12738                    "Cannot install updates to system apps on sdcard");
12739            return;
12740        }
12741
12742        if (args.move != null) {
12743            // We did an in-place move, so dex is ready to roll
12744            scanFlags |= SCAN_NO_DEX;
12745            scanFlags |= SCAN_MOVE;
12746
12747            synchronized (mPackages) {
12748                final PackageSetting ps = mSettings.mPackages.get(pkgName);
12749                if (ps == null) {
12750                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
12751                            "Missing settings for moved package " + pkgName);
12752                }
12753
12754                // We moved the entire application as-is, so bring over the
12755                // previously derived ABI information.
12756                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
12757                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
12758            }
12759
12760        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12761            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12762            scanFlags |= SCAN_NO_DEX;
12763
12764            try {
12765                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12766                        true /* extract libs */);
12767            } catch (PackageManagerException pme) {
12768                Slog.e(TAG, "Error deriving application ABI", pme);
12769                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12770                return;
12771            }
12772        }
12773
12774        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12775            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12776            return;
12777        }
12778
12779        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12780
12781        if (replace) {
12782            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
12783                    installerPackageName, volumeUuid, res);
12784        } else {
12785            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12786                    args.user, installerPackageName, volumeUuid, res);
12787        }
12788        synchronized (mPackages) {
12789            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12790            if (ps != null) {
12791                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12792            }
12793        }
12794    }
12795
12796    private void startIntentFilterVerifications(int userId, boolean replacing,
12797            PackageParser.Package pkg) {
12798        if (mIntentFilterVerifierComponent == null) {
12799            Slog.w(TAG, "No IntentFilter verification will not be done as "
12800                    + "there is no IntentFilterVerifier available!");
12801            return;
12802        }
12803
12804        final int verifierUid = getPackageUid(
12805                mIntentFilterVerifierComponent.getPackageName(),
12806                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
12807
12808        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12809        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12810        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12811        mHandler.sendMessage(msg);
12812    }
12813
12814    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12815            PackageParser.Package pkg) {
12816        int size = pkg.activities.size();
12817        if (size == 0) {
12818            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12819                    "No activity, so no need to verify any IntentFilter!");
12820            return;
12821        }
12822
12823        final boolean hasDomainURLs = hasDomainURLs(pkg);
12824        if (!hasDomainURLs) {
12825            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12826                    "No domain URLs, so no need to verify any IntentFilter!");
12827            return;
12828        }
12829
12830        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12831                + " if any IntentFilter from the " + size
12832                + " Activities needs verification ...");
12833
12834        int count = 0;
12835        final String packageName = pkg.packageName;
12836
12837        synchronized (mPackages) {
12838            // If this is a new install and we see that we've already run verification for this
12839            // package, we have nothing to do: it means the state was restored from backup.
12840            if (!replacing) {
12841                IntentFilterVerificationInfo ivi =
12842                        mSettings.getIntentFilterVerificationLPr(packageName);
12843                if (ivi != null) {
12844                    if (DEBUG_DOMAIN_VERIFICATION) {
12845                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12846                                + ivi.getStatusString());
12847                    }
12848                    return;
12849                }
12850            }
12851
12852            // If any filters need to be verified, then all need to be.
12853            boolean needToVerify = false;
12854            for (PackageParser.Activity a : pkg.activities) {
12855                for (ActivityIntentInfo filter : a.intents) {
12856                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12857                        if (DEBUG_DOMAIN_VERIFICATION) {
12858                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12859                        }
12860                        needToVerify = true;
12861                        break;
12862                    }
12863                }
12864            }
12865
12866            if (needToVerify) {
12867                final int verificationId = mIntentFilterVerificationToken++;
12868                for (PackageParser.Activity a : pkg.activities) {
12869                    for (ActivityIntentInfo filter : a.intents) {
12870                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12871                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12872                                    "Verification needed for IntentFilter:" + filter.toString());
12873                            mIntentFilterVerifier.addOneIntentFilterVerification(
12874                                    verifierUid, userId, verificationId, filter, packageName);
12875                            count++;
12876                        }
12877                    }
12878                }
12879            }
12880        }
12881
12882        if (count > 0) {
12883            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12884                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12885                    +  " for userId:" + userId);
12886            mIntentFilterVerifier.startVerifications(userId);
12887        } else {
12888            if (DEBUG_DOMAIN_VERIFICATION) {
12889                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12890            }
12891        }
12892    }
12893
12894    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12895        final ComponentName cn  = filter.activity.getComponentName();
12896        final String packageName = cn.getPackageName();
12897
12898        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12899                packageName);
12900        if (ivi == null) {
12901            return true;
12902        }
12903        int status = ivi.getStatus();
12904        switch (status) {
12905            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12906            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12907                return true;
12908
12909            default:
12910                // Nothing to do
12911                return false;
12912        }
12913    }
12914
12915    private static boolean isMultiArch(PackageSetting ps) {
12916        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12917    }
12918
12919    private static boolean isMultiArch(ApplicationInfo info) {
12920        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12921    }
12922
12923    private static boolean isExternal(PackageParser.Package pkg) {
12924        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12925    }
12926
12927    private static boolean isExternal(PackageSetting ps) {
12928        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12929    }
12930
12931    private static boolean isExternal(ApplicationInfo info) {
12932        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12933    }
12934
12935    private static boolean isSystemApp(PackageParser.Package pkg) {
12936        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12937    }
12938
12939    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12940        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12941    }
12942
12943    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12944        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12945    }
12946
12947    private static boolean isSystemApp(PackageSetting ps) {
12948        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12949    }
12950
12951    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12952        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12953    }
12954
12955    private int packageFlagsToInstallFlags(PackageSetting ps) {
12956        int installFlags = 0;
12957        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12958            // This existing package was an external ASEC install when we have
12959            // the external flag without a UUID
12960            installFlags |= PackageManager.INSTALL_EXTERNAL;
12961        }
12962        if (ps.isForwardLocked()) {
12963            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12964        }
12965        return installFlags;
12966    }
12967
12968    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
12969        if (isExternal(pkg)) {
12970            if (TextUtils.isEmpty(pkg.volumeUuid)) {
12971                return StorageManager.UUID_PRIMARY_PHYSICAL;
12972            } else {
12973                return pkg.volumeUuid;
12974            }
12975        } else {
12976            return StorageManager.UUID_PRIVATE_INTERNAL;
12977        }
12978    }
12979
12980    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
12981        if (isExternal(pkg)) {
12982            if (TextUtils.isEmpty(pkg.volumeUuid)) {
12983                return mSettings.getExternalVersion();
12984            } else {
12985                return mSettings.findOrCreateVersion(pkg.volumeUuid);
12986            }
12987        } else {
12988            return mSettings.getInternalVersion();
12989        }
12990    }
12991
12992    private void deleteTempPackageFiles() {
12993        final FilenameFilter filter = new FilenameFilter() {
12994            public boolean accept(File dir, String name) {
12995                return name.startsWith("vmdl") && name.endsWith(".tmp");
12996            }
12997        };
12998        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12999            file.delete();
13000        }
13001    }
13002
13003    @Override
13004    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
13005            int flags) {
13006        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
13007                flags);
13008    }
13009
13010    @Override
13011    public void deletePackage(final String packageName,
13012            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
13013        mContext.enforceCallingOrSelfPermission(
13014                android.Manifest.permission.DELETE_PACKAGES, null);
13015        Preconditions.checkNotNull(packageName);
13016        Preconditions.checkNotNull(observer);
13017        final int uid = Binder.getCallingUid();
13018        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
13019        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
13020        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
13021            mContext.enforceCallingPermission(
13022                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
13023                    "deletePackage for user " + userId);
13024        }
13025
13026        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
13027            try {
13028                observer.onPackageDeleted(packageName,
13029                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
13030            } catch (RemoteException re) {
13031            }
13032            return;
13033        }
13034
13035        for (int currentUserId : users) {
13036            if (getBlockUninstallForUser(packageName, currentUserId)) {
13037                try {
13038                    observer.onPackageDeleted(packageName,
13039                            PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
13040                } catch (RemoteException re) {
13041                }
13042                return;
13043            }
13044        }
13045
13046        if (DEBUG_REMOVE) {
13047            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
13048        }
13049        // Queue up an async operation since the package deletion may take a little while.
13050        mHandler.post(new Runnable() {
13051            public void run() {
13052                mHandler.removeCallbacks(this);
13053                final int returnCode = deletePackageX(packageName, userId, flags);
13054                try {
13055                    observer.onPackageDeleted(packageName, returnCode, null);
13056                } catch (RemoteException e) {
13057                    Log.i(TAG, "Observer no longer exists.");
13058                } //end catch
13059            } //end run
13060        });
13061    }
13062
13063    private boolean isPackageDeviceAdmin(String packageName, int userId) {
13064        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13065                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13066        try {
13067            if (dpm != null) {
13068                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwner();
13069                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
13070                        : deviceOwnerComponentName.getPackageName();
13071                // Does the package contains the device owner?
13072                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
13073                // this check is probably not needed, since DO should be registered as a device
13074                // admin on some user too. (Original bug for this: b/17657954)
13075                if (packageName.equals(deviceOwnerPackageName)) {
13076                    return true;
13077                }
13078                // Does it contain a device admin for any user?
13079                int[] users;
13080                if (userId == UserHandle.USER_ALL) {
13081                    users = sUserManager.getUserIds();
13082                } else {
13083                    users = new int[]{userId};
13084                }
13085                for (int i = 0; i < users.length; ++i) {
13086                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
13087                        return true;
13088                    }
13089                }
13090            }
13091        } catch (RemoteException e) {
13092        }
13093        return false;
13094    }
13095
13096    /**
13097     *  This method is an internal method that could be get invoked either
13098     *  to delete an installed package or to clean up a failed installation.
13099     *  After deleting an installed package, a broadcast is sent to notify any
13100     *  listeners that the package has been installed. For cleaning up a failed
13101     *  installation, the broadcast is not necessary since the package's
13102     *  installation wouldn't have sent the initial broadcast either
13103     *  The key steps in deleting a package are
13104     *  deleting the package information in internal structures like mPackages,
13105     *  deleting the packages base directories through installd
13106     *  updating mSettings to reflect current status
13107     *  persisting settings for later use
13108     *  sending a broadcast if necessary
13109     */
13110    private int deletePackageX(String packageName, int userId, int flags) {
13111        final PackageRemovedInfo info = new PackageRemovedInfo();
13112        final boolean res;
13113
13114        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
13115                ? UserHandle.ALL : new UserHandle(userId);
13116
13117        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
13118            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
13119            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
13120        }
13121
13122        boolean removedForAllUsers = false;
13123        boolean systemUpdate = false;
13124
13125        // for the uninstall-updates case and restricted profiles, remember the per-
13126        // userhandle installed state
13127        int[] allUsers;
13128        boolean[] perUserInstalled;
13129        synchronized (mPackages) {
13130            PackageSetting ps = mSettings.mPackages.get(packageName);
13131            allUsers = sUserManager.getUserIds();
13132            perUserInstalled = new boolean[allUsers.length];
13133            for (int i = 0; i < allUsers.length; i++) {
13134                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
13135            }
13136        }
13137
13138        synchronized (mInstallLock) {
13139            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
13140            res = deletePackageLI(packageName, removeForUser,
13141                    true, allUsers, perUserInstalled,
13142                    flags | REMOVE_CHATTY, info, true);
13143            systemUpdate = info.isRemovedPackageSystemUpdate;
13144            if (res && !systemUpdate && mPackages.get(packageName) == null) {
13145                removedForAllUsers = true;
13146            }
13147            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
13148                    + " removedForAllUsers=" + removedForAllUsers);
13149        }
13150
13151        if (res) {
13152            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
13153
13154            // If the removed package was a system update, the old system package
13155            // was re-enabled; we need to broadcast this information
13156            if (systemUpdate) {
13157                Bundle extras = new Bundle(1);
13158                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
13159                        ? info.removedAppId : info.uid);
13160                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13161
13162                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
13163                        extras, 0, null, null, null);
13164                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
13165                        extras, 0, null, null, null);
13166                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
13167                        null, 0, packageName, null, null);
13168            }
13169        }
13170        // Force a gc here.
13171        Runtime.getRuntime().gc();
13172        // Delete the resources here after sending the broadcast to let
13173        // other processes clean up before deleting resources.
13174        if (info.args != null) {
13175            synchronized (mInstallLock) {
13176                info.args.doPostDeleteLI(true);
13177            }
13178        }
13179
13180        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
13181    }
13182
13183    class PackageRemovedInfo {
13184        String removedPackage;
13185        int uid = -1;
13186        int removedAppId = -1;
13187        int[] removedUsers = null;
13188        boolean isRemovedPackageSystemUpdate = false;
13189        // Clean up resources deleted packages.
13190        InstallArgs args = null;
13191
13192        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
13193            Bundle extras = new Bundle(1);
13194            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
13195            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
13196            if (replacing) {
13197                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13198            }
13199            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
13200            if (removedPackage != null) {
13201                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
13202                        extras, 0, null, null, removedUsers);
13203                if (fullRemove && !replacing) {
13204                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
13205                            extras, 0, null, null, removedUsers);
13206                }
13207            }
13208            if (removedAppId >= 0) {
13209                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
13210                        removedUsers);
13211            }
13212        }
13213    }
13214
13215    /*
13216     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
13217     * flag is not set, the data directory is removed as well.
13218     * make sure this flag is set for partially installed apps. If not its meaningless to
13219     * delete a partially installed application.
13220     */
13221    private void removePackageDataLI(PackageSetting ps,
13222            int[] allUserHandles, boolean[] perUserInstalled,
13223            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
13224        String packageName = ps.name;
13225        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
13226        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
13227        // Retrieve object to delete permissions for shared user later on
13228        final PackageSetting deletedPs;
13229        // reader
13230        synchronized (mPackages) {
13231            deletedPs = mSettings.mPackages.get(packageName);
13232            if (outInfo != null) {
13233                outInfo.removedPackage = packageName;
13234                outInfo.removedUsers = deletedPs != null
13235                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
13236                        : null;
13237            }
13238        }
13239        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13240            removeDataDirsLI(ps.volumeUuid, packageName);
13241            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
13242        }
13243        // writer
13244        synchronized (mPackages) {
13245            if (deletedPs != null) {
13246                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13247                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
13248                    clearDefaultBrowserIfNeeded(packageName);
13249                    if (outInfo != null) {
13250                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
13251                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
13252                    }
13253                    updatePermissionsLPw(deletedPs.name, null, 0);
13254                    if (deletedPs.sharedUser != null) {
13255                        // Remove permissions associated with package. Since runtime
13256                        // permissions are per user we have to kill the removed package
13257                        // or packages running under the shared user of the removed
13258                        // package if revoking the permissions requested only by the removed
13259                        // package is successful and this causes a change in gids.
13260                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13261                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
13262                                    userId);
13263                            if (userIdToKill == UserHandle.USER_ALL
13264                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
13265                                // If gids changed for this user, kill all affected packages.
13266                                mHandler.post(new Runnable() {
13267                                    @Override
13268                                    public void run() {
13269                                        // This has to happen with no lock held.
13270                                        killApplication(deletedPs.name, deletedPs.appId,
13271                                                KILL_APP_REASON_GIDS_CHANGED);
13272                                    }
13273                                });
13274                                break;
13275                            }
13276                        }
13277                    }
13278                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
13279                }
13280                // make sure to preserve per-user disabled state if this removal was just
13281                // a downgrade of a system app to the factory package
13282                if (allUserHandles != null && perUserInstalled != null) {
13283                    if (DEBUG_REMOVE) {
13284                        Slog.d(TAG, "Propagating install state across downgrade");
13285                    }
13286                    for (int i = 0; i < allUserHandles.length; i++) {
13287                        if (DEBUG_REMOVE) {
13288                            Slog.d(TAG, "    user " + allUserHandles[i]
13289                                    + " => " + perUserInstalled[i]);
13290                        }
13291                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13292                    }
13293                }
13294            }
13295            // can downgrade to reader
13296            if (writeSettings) {
13297                // Save settings now
13298                mSettings.writeLPr();
13299            }
13300        }
13301        if (outInfo != null) {
13302            // A user ID was deleted here. Go through all users and remove it
13303            // from KeyStore.
13304            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
13305        }
13306    }
13307
13308    static boolean locationIsPrivileged(File path) {
13309        try {
13310            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
13311                    .getCanonicalPath();
13312            return path.getCanonicalPath().startsWith(privilegedAppDir);
13313        } catch (IOException e) {
13314            Slog.e(TAG, "Unable to access code path " + path);
13315        }
13316        return false;
13317    }
13318
13319    /*
13320     * Tries to delete system package.
13321     */
13322    private boolean deleteSystemPackageLI(PackageSetting newPs,
13323            int[] allUserHandles, boolean[] perUserInstalled,
13324            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
13325        final boolean applyUserRestrictions
13326                = (allUserHandles != null) && (perUserInstalled != null);
13327        PackageSetting disabledPs = null;
13328        // Confirm if the system package has been updated
13329        // An updated system app can be deleted. This will also have to restore
13330        // the system pkg from system partition
13331        // reader
13332        synchronized (mPackages) {
13333            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
13334        }
13335        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
13336                + " disabledPs=" + disabledPs);
13337        if (disabledPs == null) {
13338            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
13339            return false;
13340        } else if (DEBUG_REMOVE) {
13341            Slog.d(TAG, "Deleting system pkg from data partition");
13342        }
13343        if (DEBUG_REMOVE) {
13344            if (applyUserRestrictions) {
13345                Slog.d(TAG, "Remembering install states:");
13346                for (int i = 0; i < allUserHandles.length; i++) {
13347                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
13348                }
13349            }
13350        }
13351        // Delete the updated package
13352        outInfo.isRemovedPackageSystemUpdate = true;
13353        if (disabledPs.versionCode < newPs.versionCode) {
13354            // Delete data for downgrades
13355            flags &= ~PackageManager.DELETE_KEEP_DATA;
13356        } else {
13357            // Preserve data by setting flag
13358            flags |= PackageManager.DELETE_KEEP_DATA;
13359        }
13360        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
13361                allUserHandles, perUserInstalled, outInfo, writeSettings);
13362        if (!ret) {
13363            return false;
13364        }
13365        // writer
13366        synchronized (mPackages) {
13367            // Reinstate the old system package
13368            mSettings.enableSystemPackageLPw(newPs.name);
13369            // Remove any native libraries from the upgraded package.
13370            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
13371        }
13372        // Install the system package
13373        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
13374        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
13375        if (locationIsPrivileged(disabledPs.codePath)) {
13376            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13377        }
13378
13379        final PackageParser.Package newPkg;
13380        try {
13381            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
13382        } catch (PackageManagerException e) {
13383            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
13384            return false;
13385        }
13386
13387        // writer
13388        synchronized (mPackages) {
13389            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
13390
13391            // Propagate the permissions state as we do not want to drop on the floor
13392            // runtime permissions. The update permissions method below will take
13393            // care of removing obsolete permissions and grant install permissions.
13394            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
13395            updatePermissionsLPw(newPkg.packageName, newPkg,
13396                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
13397
13398            if (applyUserRestrictions) {
13399                if (DEBUG_REMOVE) {
13400                    Slog.d(TAG, "Propagating install state across reinstall");
13401                }
13402                for (int i = 0; i < allUserHandles.length; i++) {
13403                    if (DEBUG_REMOVE) {
13404                        Slog.d(TAG, "    user " + allUserHandles[i]
13405                                + " => " + perUserInstalled[i]);
13406                    }
13407                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13408
13409                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13410                }
13411                // Regardless of writeSettings we need to ensure that this restriction
13412                // state propagation is persisted
13413                mSettings.writeAllUsersPackageRestrictionsLPr();
13414            }
13415            // can downgrade to reader here
13416            if (writeSettings) {
13417                mSettings.writeLPr();
13418            }
13419        }
13420        return true;
13421    }
13422
13423    private boolean deleteInstalledPackageLI(PackageSetting ps,
13424            boolean deleteCodeAndResources, int flags,
13425            int[] allUserHandles, boolean[] perUserInstalled,
13426            PackageRemovedInfo outInfo, boolean writeSettings) {
13427        if (outInfo != null) {
13428            outInfo.uid = ps.appId;
13429        }
13430
13431        // Delete package data from internal structures and also remove data if flag is set
13432        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13433
13434        // Delete application code and resources
13435        if (deleteCodeAndResources && (outInfo != null)) {
13436            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13437                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13438            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13439        }
13440        return true;
13441    }
13442
13443    @Override
13444    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13445            int userId) {
13446        mContext.enforceCallingOrSelfPermission(
13447                android.Manifest.permission.DELETE_PACKAGES, null);
13448        synchronized (mPackages) {
13449            PackageSetting ps = mSettings.mPackages.get(packageName);
13450            if (ps == null) {
13451                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13452                return false;
13453            }
13454            if (!ps.getInstalled(userId)) {
13455                // Can't block uninstall for an app that is not installed or enabled.
13456                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13457                return false;
13458            }
13459            ps.setBlockUninstall(blockUninstall, userId);
13460            mSettings.writePackageRestrictionsLPr(userId);
13461        }
13462        return true;
13463    }
13464
13465    @Override
13466    public boolean getBlockUninstallForUser(String packageName, int userId) {
13467        synchronized (mPackages) {
13468            PackageSetting ps = mSettings.mPackages.get(packageName);
13469            if (ps == null) {
13470                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13471                return false;
13472            }
13473            return ps.getBlockUninstall(userId);
13474        }
13475    }
13476
13477    /*
13478     * This method handles package deletion in general
13479     */
13480    private boolean deletePackageLI(String packageName, UserHandle user,
13481            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13482            int flags, PackageRemovedInfo outInfo,
13483            boolean writeSettings) {
13484        if (packageName == null) {
13485            Slog.w(TAG, "Attempt to delete null packageName.");
13486            return false;
13487        }
13488        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13489        PackageSetting ps;
13490        boolean dataOnly = false;
13491        int removeUser = -1;
13492        int appId = -1;
13493        synchronized (mPackages) {
13494            ps = mSettings.mPackages.get(packageName);
13495            if (ps == null) {
13496                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13497                return false;
13498            }
13499            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13500                    && user.getIdentifier() != UserHandle.USER_ALL) {
13501                // The caller is asking that the package only be deleted for a single
13502                // user.  To do this, we just mark its uninstalled state and delete
13503                // its data.  If this is a system app, we only allow this to happen if
13504                // they have set the special DELETE_SYSTEM_APP which requests different
13505                // semantics than normal for uninstalling system apps.
13506                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13507                final int userId = user.getIdentifier();
13508                ps.setUserState(userId,
13509                        COMPONENT_ENABLED_STATE_DEFAULT,
13510                        false, //installed
13511                        true,  //stopped
13512                        true,  //notLaunched
13513                        false, //hidden
13514                        null, null, null,
13515                        false, // blockUninstall
13516                        ps.readUserState(userId).domainVerificationStatus, 0);
13517                if (!isSystemApp(ps)) {
13518                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
13519                        // Other user still have this package installed, so all
13520                        // we need to do is clear this user's data and save that
13521                        // it is uninstalled.
13522                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13523                        removeUser = user.getIdentifier();
13524                        appId = ps.appId;
13525                        scheduleWritePackageRestrictionsLocked(removeUser);
13526                    } else {
13527                        // We need to set it back to 'installed' so the uninstall
13528                        // broadcasts will be sent correctly.
13529                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13530                        ps.setInstalled(true, user.getIdentifier());
13531                    }
13532                } else {
13533                    // This is a system app, so we assume that the
13534                    // other users still have this package installed, so all
13535                    // we need to do is clear this user's data and save that
13536                    // it is uninstalled.
13537                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13538                    removeUser = user.getIdentifier();
13539                    appId = ps.appId;
13540                    scheduleWritePackageRestrictionsLocked(removeUser);
13541                }
13542            }
13543        }
13544
13545        if (removeUser >= 0) {
13546            // From above, we determined that we are deleting this only
13547            // for a single user.  Continue the work here.
13548            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13549            if (outInfo != null) {
13550                outInfo.removedPackage = packageName;
13551                outInfo.removedAppId = appId;
13552                outInfo.removedUsers = new int[] {removeUser};
13553            }
13554            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13555            removeKeystoreDataIfNeeded(removeUser, appId);
13556            schedulePackageCleaning(packageName, removeUser, false);
13557            synchronized (mPackages) {
13558                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13559                    scheduleWritePackageRestrictionsLocked(removeUser);
13560                }
13561                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13562            }
13563            return true;
13564        }
13565
13566        if (dataOnly) {
13567            // Delete application data first
13568            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13569            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13570            return true;
13571        }
13572
13573        boolean ret = false;
13574        if (isSystemApp(ps)) {
13575            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13576            // When an updated system application is deleted we delete the existing resources as well and
13577            // fall back to existing code in system partition
13578            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13579                    flags, outInfo, writeSettings);
13580        } else {
13581            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13582            // Kill application pre-emptively especially for apps on sd.
13583            killApplication(packageName, ps.appId, "uninstall pkg");
13584            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13585                    allUserHandles, perUserInstalled,
13586                    outInfo, writeSettings);
13587        }
13588
13589        return ret;
13590    }
13591
13592    private final class ClearStorageConnection implements ServiceConnection {
13593        IMediaContainerService mContainerService;
13594
13595        @Override
13596        public void onServiceConnected(ComponentName name, IBinder service) {
13597            synchronized (this) {
13598                mContainerService = IMediaContainerService.Stub.asInterface(service);
13599                notifyAll();
13600            }
13601        }
13602
13603        @Override
13604        public void onServiceDisconnected(ComponentName name) {
13605        }
13606    }
13607
13608    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13609        final boolean mounted;
13610        if (Environment.isExternalStorageEmulated()) {
13611            mounted = true;
13612        } else {
13613            final String status = Environment.getExternalStorageState();
13614
13615            mounted = status.equals(Environment.MEDIA_MOUNTED)
13616                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13617        }
13618
13619        if (!mounted) {
13620            return;
13621        }
13622
13623        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13624        int[] users;
13625        if (userId == UserHandle.USER_ALL) {
13626            users = sUserManager.getUserIds();
13627        } else {
13628            users = new int[] { userId };
13629        }
13630        final ClearStorageConnection conn = new ClearStorageConnection();
13631        if (mContext.bindServiceAsUser(
13632                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
13633            try {
13634                for (int curUser : users) {
13635                    long timeout = SystemClock.uptimeMillis() + 5000;
13636                    synchronized (conn) {
13637                        long now = SystemClock.uptimeMillis();
13638                        while (conn.mContainerService == null && now < timeout) {
13639                            try {
13640                                conn.wait(timeout - now);
13641                            } catch (InterruptedException e) {
13642                            }
13643                        }
13644                    }
13645                    if (conn.mContainerService == null) {
13646                        return;
13647                    }
13648
13649                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13650                    clearDirectory(conn.mContainerService,
13651                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13652                    if (allData) {
13653                        clearDirectory(conn.mContainerService,
13654                                userEnv.buildExternalStorageAppDataDirs(packageName));
13655                        clearDirectory(conn.mContainerService,
13656                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13657                    }
13658                }
13659            } finally {
13660                mContext.unbindService(conn);
13661            }
13662        }
13663    }
13664
13665    @Override
13666    public void clearApplicationUserData(final String packageName,
13667            final IPackageDataObserver observer, final int userId) {
13668        mContext.enforceCallingOrSelfPermission(
13669                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13670        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13671        // Queue up an async operation since the package deletion may take a little while.
13672        mHandler.post(new Runnable() {
13673            public void run() {
13674                mHandler.removeCallbacks(this);
13675                final boolean succeeded;
13676                synchronized (mInstallLock) {
13677                    succeeded = clearApplicationUserDataLI(packageName, userId);
13678                }
13679                clearExternalStorageDataSync(packageName, userId, true);
13680                if (succeeded) {
13681                    // invoke DeviceStorageMonitor's update method to clear any notifications
13682                    DeviceStorageMonitorInternal
13683                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13684                    if (dsm != null) {
13685                        dsm.checkMemory();
13686                    }
13687                }
13688                if(observer != null) {
13689                    try {
13690                        observer.onRemoveCompleted(packageName, succeeded);
13691                    } catch (RemoteException e) {
13692                        Log.i(TAG, "Observer no longer exists.");
13693                    }
13694                } //end if observer
13695            } //end run
13696        });
13697    }
13698
13699    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13700        if (packageName == null) {
13701            Slog.w(TAG, "Attempt to delete null packageName.");
13702            return false;
13703        }
13704
13705        // Try finding details about the requested package
13706        PackageParser.Package pkg;
13707        synchronized (mPackages) {
13708            pkg = mPackages.get(packageName);
13709            if (pkg == null) {
13710                final PackageSetting ps = mSettings.mPackages.get(packageName);
13711                if (ps != null) {
13712                    pkg = ps.pkg;
13713                }
13714            }
13715
13716            if (pkg == null) {
13717                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13718                return false;
13719            }
13720
13721            PackageSetting ps = (PackageSetting) pkg.mExtras;
13722            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13723        }
13724
13725        // Always delete data directories for package, even if we found no other
13726        // record of app. This helps users recover from UID mismatches without
13727        // resorting to a full data wipe.
13728        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13729        if (retCode < 0) {
13730            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13731            return false;
13732        }
13733
13734        final int appId = pkg.applicationInfo.uid;
13735        removeKeystoreDataIfNeeded(userId, appId);
13736
13737        // Create a native library symlink only if we have native libraries
13738        // and if the native libraries are 32 bit libraries. We do not provide
13739        // this symlink for 64 bit libraries.
13740        if (pkg.applicationInfo.primaryCpuAbi != null &&
13741                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13742            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13743            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13744                    nativeLibPath, userId) < 0) {
13745                Slog.w(TAG, "Failed linking native library dir");
13746                return false;
13747            }
13748        }
13749
13750        return true;
13751    }
13752
13753    /**
13754     * Reverts user permission state changes (permissions and flags) in
13755     * all packages for a given user.
13756     *
13757     * @param userId The device user for which to do a reset.
13758     */
13759    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
13760        final int packageCount = mPackages.size();
13761        for (int i = 0; i < packageCount; i++) {
13762            PackageParser.Package pkg = mPackages.valueAt(i);
13763            PackageSetting ps = (PackageSetting) pkg.mExtras;
13764            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13765        }
13766    }
13767
13768    /**
13769     * Reverts user permission state changes (permissions and flags).
13770     *
13771     * @param ps The package for which to reset.
13772     * @param userId The device user for which to do a reset.
13773     */
13774    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
13775            final PackageSetting ps, final int userId) {
13776        if (ps.pkg == null) {
13777            return;
13778        }
13779
13780        final int userSettableFlags = FLAG_PERMISSION_USER_SET
13781                | FLAG_PERMISSION_USER_FIXED
13782                | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13783
13784        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13785                | FLAG_PERMISSION_POLICY_FIXED;
13786
13787        boolean writeInstallPermissions = false;
13788        boolean writeRuntimePermissions = false;
13789
13790        final int permissionCount = ps.pkg.requestedPermissions.size();
13791        for (int i = 0; i < permissionCount; i++) {
13792            String permission = ps.pkg.requestedPermissions.get(i);
13793
13794            BasePermission bp = mSettings.mPermissions.get(permission);
13795            if (bp == null) {
13796                continue;
13797            }
13798
13799            // If shared user we just reset the state to which only this app contributed.
13800            if (ps.sharedUser != null) {
13801                boolean used = false;
13802                final int packageCount = ps.sharedUser.packages.size();
13803                for (int j = 0; j < packageCount; j++) {
13804                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13805                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13806                            && pkg.pkg.requestedPermissions.contains(permission)) {
13807                        used = true;
13808                        break;
13809                    }
13810                }
13811                if (used) {
13812                    continue;
13813                }
13814            }
13815
13816            PermissionsState permissionsState = ps.getPermissionsState();
13817
13818            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13819
13820            // Always clear the user settable flags.
13821            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13822                    bp.name) != null;
13823            if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13824                if (hasInstallState) {
13825                    writeInstallPermissions = true;
13826                } else {
13827                    writeRuntimePermissions = true;
13828                }
13829            }
13830
13831            // Below is only runtime permission handling.
13832            if (!bp.isRuntime()) {
13833                continue;
13834            }
13835
13836            // Never clobber system or policy.
13837            if ((oldFlags & policyOrSystemFlags) != 0) {
13838                continue;
13839            }
13840
13841            // If this permission was granted by default, make sure it is.
13842            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13843                if (permissionsState.grantRuntimePermission(bp, userId)
13844                        != PERMISSION_OPERATION_FAILURE) {
13845                    writeRuntimePermissions = true;
13846                }
13847            } else {
13848                // Otherwise, reset the permission.
13849                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13850                switch (revokeResult) {
13851                    case PERMISSION_OPERATION_SUCCESS: {
13852                        writeRuntimePermissions = true;
13853                    } break;
13854
13855                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13856                        writeRuntimePermissions = true;
13857                        final int appId = ps.appId;
13858                        mHandler.post(new Runnable() {
13859                            @Override
13860                            public void run() {
13861                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
13862                            }
13863                        });
13864                    } break;
13865                }
13866            }
13867        }
13868
13869        // Synchronously write as we are taking permissions away.
13870        if (writeRuntimePermissions) {
13871            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13872        }
13873
13874        // Synchronously write as we are taking permissions away.
13875        if (writeInstallPermissions) {
13876            mSettings.writeLPr();
13877        }
13878    }
13879
13880    /**
13881     * Remove entries from the keystore daemon. Will only remove it if the
13882     * {@code appId} is valid.
13883     */
13884    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13885        if (appId < 0) {
13886            return;
13887        }
13888
13889        final KeyStore keyStore = KeyStore.getInstance();
13890        if (keyStore != null) {
13891            if (userId == UserHandle.USER_ALL) {
13892                for (final int individual : sUserManager.getUserIds()) {
13893                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13894                }
13895            } else {
13896                keyStore.clearUid(UserHandle.getUid(userId, appId));
13897            }
13898        } else {
13899            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13900        }
13901    }
13902
13903    @Override
13904    public void deleteApplicationCacheFiles(final String packageName,
13905            final IPackageDataObserver observer) {
13906        mContext.enforceCallingOrSelfPermission(
13907                android.Manifest.permission.DELETE_CACHE_FILES, null);
13908        // Queue up an async operation since the package deletion may take a little while.
13909        final int userId = UserHandle.getCallingUserId();
13910        mHandler.post(new Runnable() {
13911            public void run() {
13912                mHandler.removeCallbacks(this);
13913                final boolean succeded;
13914                synchronized (mInstallLock) {
13915                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13916                }
13917                clearExternalStorageDataSync(packageName, userId, false);
13918                if (observer != null) {
13919                    try {
13920                        observer.onRemoveCompleted(packageName, succeded);
13921                    } catch (RemoteException e) {
13922                        Log.i(TAG, "Observer no longer exists.");
13923                    }
13924                } //end if observer
13925            } //end run
13926        });
13927    }
13928
13929    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13930        if (packageName == null) {
13931            Slog.w(TAG, "Attempt to delete null packageName.");
13932            return false;
13933        }
13934        PackageParser.Package p;
13935        synchronized (mPackages) {
13936            p = mPackages.get(packageName);
13937        }
13938        if (p == null) {
13939            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13940            return false;
13941        }
13942        final ApplicationInfo applicationInfo = p.applicationInfo;
13943        if (applicationInfo == null) {
13944            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13945            return false;
13946        }
13947        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13948        if (retCode < 0) {
13949            Slog.w(TAG, "Couldn't remove cache files for package: "
13950                       + packageName + " u" + userId);
13951            return false;
13952        }
13953        return true;
13954    }
13955
13956    @Override
13957    public void getPackageSizeInfo(final String packageName, int userHandle,
13958            final IPackageStatsObserver observer) {
13959        mContext.enforceCallingOrSelfPermission(
13960                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13961        if (packageName == null) {
13962            throw new IllegalArgumentException("Attempt to get size of null packageName");
13963        }
13964
13965        PackageStats stats = new PackageStats(packageName, userHandle);
13966
13967        /*
13968         * Queue up an async operation since the package measurement may take a
13969         * little while.
13970         */
13971        Message msg = mHandler.obtainMessage(INIT_COPY);
13972        msg.obj = new MeasureParams(stats, observer);
13973        mHandler.sendMessage(msg);
13974    }
13975
13976    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13977            PackageStats pStats) {
13978        if (packageName == null) {
13979            Slog.w(TAG, "Attempt to get size of null packageName.");
13980            return false;
13981        }
13982        PackageParser.Package p;
13983        boolean dataOnly = false;
13984        String libDirRoot = null;
13985        String asecPath = null;
13986        PackageSetting ps = null;
13987        synchronized (mPackages) {
13988            p = mPackages.get(packageName);
13989            ps = mSettings.mPackages.get(packageName);
13990            if(p == null) {
13991                dataOnly = true;
13992                if((ps == null) || (ps.pkg == null)) {
13993                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13994                    return false;
13995                }
13996                p = ps.pkg;
13997            }
13998            if (ps != null) {
13999                libDirRoot = ps.legacyNativeLibraryPathString;
14000            }
14001            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
14002                final long token = Binder.clearCallingIdentity();
14003                try {
14004                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
14005                    if (secureContainerId != null) {
14006                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
14007                    }
14008                } finally {
14009                    Binder.restoreCallingIdentity(token);
14010                }
14011            }
14012        }
14013        String publicSrcDir = null;
14014        if(!dataOnly) {
14015            final ApplicationInfo applicationInfo = p.applicationInfo;
14016            if (applicationInfo == null) {
14017                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14018                return false;
14019            }
14020            if (p.isForwardLocked()) {
14021                publicSrcDir = applicationInfo.getBaseResourcePath();
14022            }
14023        }
14024        // TODO: extend to measure size of split APKs
14025        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
14026        // not just the first level.
14027        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
14028        // just the primary.
14029        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
14030
14031        String apkPath;
14032        File packageDir = new File(p.codePath);
14033
14034        if (packageDir.isDirectory() && p.canHaveOatDir()) {
14035            apkPath = packageDir.getAbsolutePath();
14036            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
14037            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
14038                libDirRoot = null;
14039            }
14040        } else {
14041            apkPath = p.baseCodePath;
14042        }
14043
14044        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath,
14045                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
14046        if (res < 0) {
14047            return false;
14048        }
14049
14050        // Fix-up for forward-locked applications in ASEC containers.
14051        if (!isExternal(p)) {
14052            pStats.codeSize += pStats.externalCodeSize;
14053            pStats.externalCodeSize = 0L;
14054        }
14055
14056        return true;
14057    }
14058
14059
14060    @Override
14061    public void addPackageToPreferred(String packageName) {
14062        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
14063    }
14064
14065    @Override
14066    public void removePackageFromPreferred(String packageName) {
14067        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
14068    }
14069
14070    @Override
14071    public List<PackageInfo> getPreferredPackages(int flags) {
14072        return new ArrayList<PackageInfo>();
14073    }
14074
14075    private int getUidTargetSdkVersionLockedLPr(int uid) {
14076        Object obj = mSettings.getUserIdLPr(uid);
14077        if (obj instanceof SharedUserSetting) {
14078            final SharedUserSetting sus = (SharedUserSetting) obj;
14079            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
14080            final Iterator<PackageSetting> it = sus.packages.iterator();
14081            while (it.hasNext()) {
14082                final PackageSetting ps = it.next();
14083                if (ps.pkg != null) {
14084                    int v = ps.pkg.applicationInfo.targetSdkVersion;
14085                    if (v < vers) vers = v;
14086                }
14087            }
14088            return vers;
14089        } else if (obj instanceof PackageSetting) {
14090            final PackageSetting ps = (PackageSetting) obj;
14091            if (ps.pkg != null) {
14092                return ps.pkg.applicationInfo.targetSdkVersion;
14093            }
14094        }
14095        return Build.VERSION_CODES.CUR_DEVELOPMENT;
14096    }
14097
14098    @Override
14099    public void addPreferredActivity(IntentFilter filter, int match,
14100            ComponentName[] set, ComponentName activity, int userId) {
14101        addPreferredActivityInternal(filter, match, set, activity, true, userId,
14102                "Adding preferred");
14103    }
14104
14105    private void addPreferredActivityInternal(IntentFilter filter, int match,
14106            ComponentName[] set, ComponentName activity, boolean always, int userId,
14107            String opname) {
14108        // writer
14109        int callingUid = Binder.getCallingUid();
14110        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
14111        if (filter.countActions() == 0) {
14112            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14113            return;
14114        }
14115        synchronized (mPackages) {
14116            if (mContext.checkCallingOrSelfPermission(
14117                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14118                    != PackageManager.PERMISSION_GRANTED) {
14119                if (getUidTargetSdkVersionLockedLPr(callingUid)
14120                        < Build.VERSION_CODES.FROYO) {
14121                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
14122                            + callingUid);
14123                    return;
14124                }
14125                mContext.enforceCallingOrSelfPermission(
14126                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14127            }
14128
14129            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
14130            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
14131                    + userId + ":");
14132            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14133            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
14134            scheduleWritePackageRestrictionsLocked(userId);
14135        }
14136    }
14137
14138    @Override
14139    public void replacePreferredActivity(IntentFilter filter, int match,
14140            ComponentName[] set, ComponentName activity, int userId) {
14141        if (filter.countActions() != 1) {
14142            throw new IllegalArgumentException(
14143                    "replacePreferredActivity expects filter to have only 1 action.");
14144        }
14145        if (filter.countDataAuthorities() != 0
14146                || filter.countDataPaths() != 0
14147                || filter.countDataSchemes() > 1
14148                || filter.countDataTypes() != 0) {
14149            throw new IllegalArgumentException(
14150                    "replacePreferredActivity expects filter to have no data authorities, " +
14151                    "paths, or types; and at most one scheme.");
14152        }
14153
14154        final int callingUid = Binder.getCallingUid();
14155        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
14156        synchronized (mPackages) {
14157            if (mContext.checkCallingOrSelfPermission(
14158                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14159                    != PackageManager.PERMISSION_GRANTED) {
14160                if (getUidTargetSdkVersionLockedLPr(callingUid)
14161                        < Build.VERSION_CODES.FROYO) {
14162                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
14163                            + Binder.getCallingUid());
14164                    return;
14165                }
14166                mContext.enforceCallingOrSelfPermission(
14167                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14168            }
14169
14170            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14171            if (pir != null) {
14172                // Get all of the existing entries that exactly match this filter.
14173                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
14174                if (existing != null && existing.size() == 1) {
14175                    PreferredActivity cur = existing.get(0);
14176                    if (DEBUG_PREFERRED) {
14177                        Slog.i(TAG, "Checking replace of preferred:");
14178                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14179                        if (!cur.mPref.mAlways) {
14180                            Slog.i(TAG, "  -- CUR; not mAlways!");
14181                        } else {
14182                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
14183                            Slog.i(TAG, "  -- CUR: mSet="
14184                                    + Arrays.toString(cur.mPref.mSetComponents));
14185                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
14186                            Slog.i(TAG, "  -- NEW: mMatch="
14187                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
14188                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
14189                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
14190                        }
14191                    }
14192                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
14193                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
14194                            && cur.mPref.sameSet(set)) {
14195                        // Setting the preferred activity to what it happens to be already
14196                        if (DEBUG_PREFERRED) {
14197                            Slog.i(TAG, "Replacing with same preferred activity "
14198                                    + cur.mPref.mShortComponent + " for user "
14199                                    + userId + ":");
14200                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14201                        }
14202                        return;
14203                    }
14204                }
14205
14206                if (existing != null) {
14207                    if (DEBUG_PREFERRED) {
14208                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
14209                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14210                    }
14211                    for (int i = 0; i < existing.size(); i++) {
14212                        PreferredActivity pa = existing.get(i);
14213                        if (DEBUG_PREFERRED) {
14214                            Slog.i(TAG, "Removing existing preferred activity "
14215                                    + pa.mPref.mComponent + ":");
14216                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
14217                        }
14218                        pir.removeFilter(pa);
14219                    }
14220                }
14221            }
14222            addPreferredActivityInternal(filter, match, set, activity, true, userId,
14223                    "Replacing preferred");
14224        }
14225    }
14226
14227    @Override
14228    public void clearPackagePreferredActivities(String packageName) {
14229        final int uid = Binder.getCallingUid();
14230        // writer
14231        synchronized (mPackages) {
14232            PackageParser.Package pkg = mPackages.get(packageName);
14233            if (pkg == null || pkg.applicationInfo.uid != uid) {
14234                if (mContext.checkCallingOrSelfPermission(
14235                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14236                        != PackageManager.PERMISSION_GRANTED) {
14237                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
14238                            < Build.VERSION_CODES.FROYO) {
14239                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
14240                                + Binder.getCallingUid());
14241                        return;
14242                    }
14243                    mContext.enforceCallingOrSelfPermission(
14244                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14245                }
14246            }
14247
14248            int user = UserHandle.getCallingUserId();
14249            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
14250                scheduleWritePackageRestrictionsLocked(user);
14251            }
14252        }
14253    }
14254
14255    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14256    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
14257        ArrayList<PreferredActivity> removed = null;
14258        boolean changed = false;
14259        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14260            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
14261            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14262            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
14263                continue;
14264            }
14265            Iterator<PreferredActivity> it = pir.filterIterator();
14266            while (it.hasNext()) {
14267                PreferredActivity pa = it.next();
14268                // Mark entry for removal only if it matches the package name
14269                // and the entry is of type "always".
14270                if (packageName == null ||
14271                        (pa.mPref.mComponent.getPackageName().equals(packageName)
14272                                && pa.mPref.mAlways)) {
14273                    if (removed == null) {
14274                        removed = new ArrayList<PreferredActivity>();
14275                    }
14276                    removed.add(pa);
14277                }
14278            }
14279            if (removed != null) {
14280                for (int j=0; j<removed.size(); j++) {
14281                    PreferredActivity pa = removed.get(j);
14282                    pir.removeFilter(pa);
14283                }
14284                changed = true;
14285            }
14286        }
14287        return changed;
14288    }
14289
14290    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14291    private void clearIntentFilterVerificationsLPw(int userId) {
14292        final int packageCount = mPackages.size();
14293        for (int i = 0; i < packageCount; i++) {
14294            PackageParser.Package pkg = mPackages.valueAt(i);
14295            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
14296        }
14297    }
14298
14299    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14300    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
14301        if (userId == UserHandle.USER_ALL) {
14302            if (mSettings.removeIntentFilterVerificationLPw(packageName,
14303                    sUserManager.getUserIds())) {
14304                for (int oneUserId : sUserManager.getUserIds()) {
14305                    scheduleWritePackageRestrictionsLocked(oneUserId);
14306                }
14307            }
14308        } else {
14309            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
14310                scheduleWritePackageRestrictionsLocked(userId);
14311            }
14312        }
14313    }
14314
14315    void clearDefaultBrowserIfNeeded(String packageName) {
14316        for (int oneUserId : sUserManager.getUserIds()) {
14317            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
14318            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
14319            if (packageName.equals(defaultBrowserPackageName)) {
14320                setDefaultBrowserPackageName(null, oneUserId);
14321            }
14322        }
14323    }
14324
14325    @Override
14326    public void resetApplicationPreferences(int userId) {
14327        mContext.enforceCallingOrSelfPermission(
14328                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14329        // writer
14330        synchronized (mPackages) {
14331            final long identity = Binder.clearCallingIdentity();
14332            try {
14333                clearPackagePreferredActivitiesLPw(null, userId);
14334                mSettings.applyDefaultPreferredAppsLPw(this, userId);
14335                // TODO: We have to reset the default SMS and Phone. This requires
14336                // significant refactoring to keep all default apps in the package
14337                // manager (cleaner but more work) or have the services provide
14338                // callbacks to the package manager to request a default app reset.
14339                applyFactoryDefaultBrowserLPw(userId);
14340                clearIntentFilterVerificationsLPw(userId);
14341                primeDomainVerificationsLPw(userId);
14342                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
14343                scheduleWritePackageRestrictionsLocked(userId);
14344            } finally {
14345                Binder.restoreCallingIdentity(identity);
14346            }
14347        }
14348    }
14349
14350    @Override
14351    public int getPreferredActivities(List<IntentFilter> outFilters,
14352            List<ComponentName> outActivities, String packageName) {
14353
14354        int num = 0;
14355        final int userId = UserHandle.getCallingUserId();
14356        // reader
14357        synchronized (mPackages) {
14358            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14359            if (pir != null) {
14360                final Iterator<PreferredActivity> it = pir.filterIterator();
14361                while (it.hasNext()) {
14362                    final PreferredActivity pa = it.next();
14363                    if (packageName == null
14364                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
14365                                    && pa.mPref.mAlways)) {
14366                        if (outFilters != null) {
14367                            outFilters.add(new IntentFilter(pa));
14368                        }
14369                        if (outActivities != null) {
14370                            outActivities.add(pa.mPref.mComponent);
14371                        }
14372                    }
14373                }
14374            }
14375        }
14376
14377        return num;
14378    }
14379
14380    @Override
14381    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
14382            int userId) {
14383        int callingUid = Binder.getCallingUid();
14384        if (callingUid != Process.SYSTEM_UID) {
14385            throw new SecurityException(
14386                    "addPersistentPreferredActivity can only be run by the system");
14387        }
14388        if (filter.countActions() == 0) {
14389            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14390            return;
14391        }
14392        synchronized (mPackages) {
14393            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
14394                    " :");
14395            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14396            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
14397                    new PersistentPreferredActivity(filter, activity));
14398            scheduleWritePackageRestrictionsLocked(userId);
14399        }
14400    }
14401
14402    @Override
14403    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
14404        int callingUid = Binder.getCallingUid();
14405        if (callingUid != Process.SYSTEM_UID) {
14406            throw new SecurityException(
14407                    "clearPackagePersistentPreferredActivities can only be run by the system");
14408        }
14409        ArrayList<PersistentPreferredActivity> removed = null;
14410        boolean changed = false;
14411        synchronized (mPackages) {
14412            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
14413                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
14414                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
14415                        .valueAt(i);
14416                if (userId != thisUserId) {
14417                    continue;
14418                }
14419                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
14420                while (it.hasNext()) {
14421                    PersistentPreferredActivity ppa = it.next();
14422                    // Mark entry for removal only if it matches the package name.
14423                    if (ppa.mComponent.getPackageName().equals(packageName)) {
14424                        if (removed == null) {
14425                            removed = new ArrayList<PersistentPreferredActivity>();
14426                        }
14427                        removed.add(ppa);
14428                    }
14429                }
14430                if (removed != null) {
14431                    for (int j=0; j<removed.size(); j++) {
14432                        PersistentPreferredActivity ppa = removed.get(j);
14433                        ppir.removeFilter(ppa);
14434                    }
14435                    changed = true;
14436                }
14437            }
14438
14439            if (changed) {
14440                scheduleWritePackageRestrictionsLocked(userId);
14441            }
14442        }
14443    }
14444
14445    /**
14446     * Common machinery for picking apart a restored XML blob and passing
14447     * it to a caller-supplied functor to be applied to the running system.
14448     */
14449    private void restoreFromXml(XmlPullParser parser, int userId,
14450            String expectedStartTag, BlobXmlRestorer functor)
14451            throws IOException, XmlPullParserException {
14452        int type;
14453        while ((type = parser.next()) != XmlPullParser.START_TAG
14454                && type != XmlPullParser.END_DOCUMENT) {
14455        }
14456        if (type != XmlPullParser.START_TAG) {
14457            // oops didn't find a start tag?!
14458            if (DEBUG_BACKUP) {
14459                Slog.e(TAG, "Didn't find start tag during restore");
14460            }
14461            return;
14462        }
14463
14464        // this is supposed to be TAG_PREFERRED_BACKUP
14465        if (!expectedStartTag.equals(parser.getName())) {
14466            if (DEBUG_BACKUP) {
14467                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14468            }
14469            return;
14470        }
14471
14472        // skip interfering stuff, then we're aligned with the backing implementation
14473        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14474        functor.apply(parser, userId);
14475    }
14476
14477    private interface BlobXmlRestorer {
14478        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14479    }
14480
14481    /**
14482     * Non-Binder method, support for the backup/restore mechanism: write the
14483     * full set of preferred activities in its canonical XML format.  Returns the
14484     * XML output as a byte array, or null if there is none.
14485     */
14486    @Override
14487    public byte[] getPreferredActivityBackup(int userId) {
14488        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14489            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14490        }
14491
14492        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14493        try {
14494            final XmlSerializer serializer = new FastXmlSerializer();
14495            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14496            serializer.startDocument(null, true);
14497            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14498
14499            synchronized (mPackages) {
14500                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14501            }
14502
14503            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14504            serializer.endDocument();
14505            serializer.flush();
14506        } catch (Exception e) {
14507            if (DEBUG_BACKUP) {
14508                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14509            }
14510            return null;
14511        }
14512
14513        return dataStream.toByteArray();
14514    }
14515
14516    @Override
14517    public void restorePreferredActivities(byte[] backup, int userId) {
14518        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14519            throw new SecurityException("Only the system may call restorePreferredActivities()");
14520        }
14521
14522        try {
14523            final XmlPullParser parser = Xml.newPullParser();
14524            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14525            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14526                    new BlobXmlRestorer() {
14527                        @Override
14528                        public void apply(XmlPullParser parser, int userId)
14529                                throws XmlPullParserException, IOException {
14530                            synchronized (mPackages) {
14531                                mSettings.readPreferredActivitiesLPw(parser, userId);
14532                            }
14533                        }
14534                    } );
14535        } catch (Exception e) {
14536            if (DEBUG_BACKUP) {
14537                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14538            }
14539        }
14540    }
14541
14542    /**
14543     * Non-Binder method, support for the backup/restore mechanism: write the
14544     * default browser (etc) settings in its canonical XML format.  Returns the default
14545     * browser XML representation as a byte array, or null if there is none.
14546     */
14547    @Override
14548    public byte[] getDefaultAppsBackup(int userId) {
14549        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14550            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14551        }
14552
14553        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14554        try {
14555            final XmlSerializer serializer = new FastXmlSerializer();
14556            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14557            serializer.startDocument(null, true);
14558            serializer.startTag(null, TAG_DEFAULT_APPS);
14559
14560            synchronized (mPackages) {
14561                mSettings.writeDefaultAppsLPr(serializer, userId);
14562            }
14563
14564            serializer.endTag(null, TAG_DEFAULT_APPS);
14565            serializer.endDocument();
14566            serializer.flush();
14567        } catch (Exception e) {
14568            if (DEBUG_BACKUP) {
14569                Slog.e(TAG, "Unable to write default apps for backup", e);
14570            }
14571            return null;
14572        }
14573
14574        return dataStream.toByteArray();
14575    }
14576
14577    @Override
14578    public void restoreDefaultApps(byte[] backup, int userId) {
14579        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14580            throw new SecurityException("Only the system may call restoreDefaultApps()");
14581        }
14582
14583        try {
14584            final XmlPullParser parser = Xml.newPullParser();
14585            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14586            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14587                    new BlobXmlRestorer() {
14588                        @Override
14589                        public void apply(XmlPullParser parser, int userId)
14590                                throws XmlPullParserException, IOException {
14591                            synchronized (mPackages) {
14592                                mSettings.readDefaultAppsLPw(parser, userId);
14593                            }
14594                        }
14595                    } );
14596        } catch (Exception e) {
14597            if (DEBUG_BACKUP) {
14598                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14599            }
14600        }
14601    }
14602
14603    @Override
14604    public byte[] getIntentFilterVerificationBackup(int userId) {
14605        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14606            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14607        }
14608
14609        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14610        try {
14611            final XmlSerializer serializer = new FastXmlSerializer();
14612            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14613            serializer.startDocument(null, true);
14614            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14615
14616            synchronized (mPackages) {
14617                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14618            }
14619
14620            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14621            serializer.endDocument();
14622            serializer.flush();
14623        } catch (Exception e) {
14624            if (DEBUG_BACKUP) {
14625                Slog.e(TAG, "Unable to write default apps for backup", e);
14626            }
14627            return null;
14628        }
14629
14630        return dataStream.toByteArray();
14631    }
14632
14633    @Override
14634    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14635        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14636            throw new SecurityException("Only the system may call restorePreferredActivities()");
14637        }
14638
14639        try {
14640            final XmlPullParser parser = Xml.newPullParser();
14641            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14642            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14643                    new BlobXmlRestorer() {
14644                        @Override
14645                        public void apply(XmlPullParser parser, int userId)
14646                                throws XmlPullParserException, IOException {
14647                            synchronized (mPackages) {
14648                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14649                                mSettings.writeLPr();
14650                            }
14651                        }
14652                    } );
14653        } catch (Exception e) {
14654            if (DEBUG_BACKUP) {
14655                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14656            }
14657        }
14658    }
14659
14660    @Override
14661    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14662            int sourceUserId, int targetUserId, int flags) {
14663        mContext.enforceCallingOrSelfPermission(
14664                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14665        int callingUid = Binder.getCallingUid();
14666        enforceOwnerRights(ownerPackage, callingUid);
14667        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14668        if (intentFilter.countActions() == 0) {
14669            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14670            return;
14671        }
14672        synchronized (mPackages) {
14673            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14674                    ownerPackage, targetUserId, flags);
14675            CrossProfileIntentResolver resolver =
14676                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14677            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14678            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14679            if (existing != null) {
14680                int size = existing.size();
14681                for (int i = 0; i < size; i++) {
14682                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14683                        return;
14684                    }
14685                }
14686            }
14687            resolver.addFilter(newFilter);
14688            scheduleWritePackageRestrictionsLocked(sourceUserId);
14689        }
14690    }
14691
14692    @Override
14693    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14694        mContext.enforceCallingOrSelfPermission(
14695                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14696        int callingUid = Binder.getCallingUid();
14697        enforceOwnerRights(ownerPackage, callingUid);
14698        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14699        synchronized (mPackages) {
14700            CrossProfileIntentResolver resolver =
14701                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14702            ArraySet<CrossProfileIntentFilter> set =
14703                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14704            for (CrossProfileIntentFilter filter : set) {
14705                if (filter.getOwnerPackage().equals(ownerPackage)) {
14706                    resolver.removeFilter(filter);
14707                }
14708            }
14709            scheduleWritePackageRestrictionsLocked(sourceUserId);
14710        }
14711    }
14712
14713    // Enforcing that callingUid is owning pkg on userId
14714    private void enforceOwnerRights(String pkg, int callingUid) {
14715        // The system owns everything.
14716        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14717            return;
14718        }
14719        int callingUserId = UserHandle.getUserId(callingUid);
14720        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14721        if (pi == null) {
14722            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14723                    + callingUserId);
14724        }
14725        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14726            throw new SecurityException("Calling uid " + callingUid
14727                    + " does not own package " + pkg);
14728        }
14729    }
14730
14731    @Override
14732    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14733        Intent intent = new Intent(Intent.ACTION_MAIN);
14734        intent.addCategory(Intent.CATEGORY_HOME);
14735
14736        final int callingUserId = UserHandle.getCallingUserId();
14737        List<ResolveInfo> list = queryIntentActivities(intent, null,
14738                PackageManager.GET_META_DATA, callingUserId);
14739        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14740                true, false, false, callingUserId);
14741
14742        allHomeCandidates.clear();
14743        if (list != null) {
14744            for (ResolveInfo ri : list) {
14745                allHomeCandidates.add(ri);
14746            }
14747        }
14748        return (preferred == null || preferred.activityInfo == null)
14749                ? null
14750                : new ComponentName(preferred.activityInfo.packageName,
14751                        preferred.activityInfo.name);
14752    }
14753
14754    @Override
14755    public void setApplicationEnabledSetting(String appPackageName,
14756            int newState, int flags, int userId, String callingPackage) {
14757        if (!sUserManager.exists(userId)) return;
14758        if (callingPackage == null) {
14759            callingPackage = Integer.toString(Binder.getCallingUid());
14760        }
14761        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14762    }
14763
14764    @Override
14765    public void setComponentEnabledSetting(ComponentName componentName,
14766            int newState, int flags, int userId) {
14767        if (!sUserManager.exists(userId)) return;
14768        setEnabledSetting(componentName.getPackageName(),
14769                componentName.getClassName(), newState, flags, userId, null);
14770    }
14771
14772    private void setEnabledSetting(final String packageName, String className, int newState,
14773            final int flags, int userId, String callingPackage) {
14774        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14775              || newState == COMPONENT_ENABLED_STATE_ENABLED
14776              || newState == COMPONENT_ENABLED_STATE_DISABLED
14777              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14778              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14779            throw new IllegalArgumentException("Invalid new component state: "
14780                    + newState);
14781        }
14782        PackageSetting pkgSetting;
14783        final int uid = Binder.getCallingUid();
14784        final int permission = mContext.checkCallingOrSelfPermission(
14785                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14786        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14787        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14788        boolean sendNow = false;
14789        boolean isApp = (className == null);
14790        String componentName = isApp ? packageName : className;
14791        int packageUid = -1;
14792        ArrayList<String> components;
14793
14794        // writer
14795        synchronized (mPackages) {
14796            pkgSetting = mSettings.mPackages.get(packageName);
14797            if (pkgSetting == null) {
14798                if (className == null) {
14799                    throw new IllegalArgumentException(
14800                            "Unknown package: " + packageName);
14801                }
14802                throw new IllegalArgumentException(
14803                        "Unknown component: " + packageName
14804                        + "/" + className);
14805            }
14806            // Allow root and verify that userId is not being specified by a different user
14807            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14808                throw new SecurityException(
14809                        "Permission Denial: attempt to change component state from pid="
14810                        + Binder.getCallingPid()
14811                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14812            }
14813            if (className == null) {
14814                // We're dealing with an application/package level state change
14815                if (pkgSetting.getEnabled(userId) == newState) {
14816                    // Nothing to do
14817                    return;
14818                }
14819                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14820                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14821                    // Don't care about who enables an app.
14822                    callingPackage = null;
14823                }
14824                pkgSetting.setEnabled(newState, userId, callingPackage);
14825                // pkgSetting.pkg.mSetEnabled = newState;
14826            } else {
14827                // We're dealing with a component level state change
14828                // First, verify that this is a valid class name.
14829                PackageParser.Package pkg = pkgSetting.pkg;
14830                if (pkg == null || !pkg.hasComponentClassName(className)) {
14831                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14832                        throw new IllegalArgumentException("Component class " + className
14833                                + " does not exist in " + packageName);
14834                    } else {
14835                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14836                                + className + " does not exist in " + packageName);
14837                    }
14838                }
14839                switch (newState) {
14840                case COMPONENT_ENABLED_STATE_ENABLED:
14841                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14842                        return;
14843                    }
14844                    break;
14845                case COMPONENT_ENABLED_STATE_DISABLED:
14846                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14847                        return;
14848                    }
14849                    break;
14850                case COMPONENT_ENABLED_STATE_DEFAULT:
14851                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14852                        return;
14853                    }
14854                    break;
14855                default:
14856                    Slog.e(TAG, "Invalid new component state: " + newState);
14857                    return;
14858                }
14859            }
14860            scheduleWritePackageRestrictionsLocked(userId);
14861            components = mPendingBroadcasts.get(userId, packageName);
14862            final boolean newPackage = components == null;
14863            if (newPackage) {
14864                components = new ArrayList<String>();
14865            }
14866            if (!components.contains(componentName)) {
14867                components.add(componentName);
14868            }
14869            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14870                sendNow = true;
14871                // Purge entry from pending broadcast list if another one exists already
14872                // since we are sending one right away.
14873                mPendingBroadcasts.remove(userId, packageName);
14874            } else {
14875                if (newPackage) {
14876                    mPendingBroadcasts.put(userId, packageName, components);
14877                }
14878                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14879                    // Schedule a message
14880                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14881                }
14882            }
14883        }
14884
14885        long callingId = Binder.clearCallingIdentity();
14886        try {
14887            if (sendNow) {
14888                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14889                sendPackageChangedBroadcast(packageName,
14890                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14891            }
14892        } finally {
14893            Binder.restoreCallingIdentity(callingId);
14894        }
14895    }
14896
14897    private void sendPackageChangedBroadcast(String packageName,
14898            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14899        if (DEBUG_INSTALL)
14900            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14901                    + componentNames);
14902        Bundle extras = new Bundle(4);
14903        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14904        String nameList[] = new String[componentNames.size()];
14905        componentNames.toArray(nameList);
14906        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14907        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14908        extras.putInt(Intent.EXTRA_UID, packageUid);
14909        // If this is not reporting a change of the overall package, then only send it
14910        // to registered receivers.  We don't want to launch a swath of apps for every
14911        // little component state change.
14912        final int flags = !componentNames.contains(packageName)
14913                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
14914        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
14915                new int[] {UserHandle.getUserId(packageUid)});
14916    }
14917
14918    @Override
14919    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14920        if (!sUserManager.exists(userId)) return;
14921        final int uid = Binder.getCallingUid();
14922        final int permission = mContext.checkCallingOrSelfPermission(
14923                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14924        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14925        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14926        // writer
14927        synchronized (mPackages) {
14928            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14929                    allowedByPermission, uid, userId)) {
14930                scheduleWritePackageRestrictionsLocked(userId);
14931            }
14932        }
14933    }
14934
14935    @Override
14936    public String getInstallerPackageName(String packageName) {
14937        // reader
14938        synchronized (mPackages) {
14939            return mSettings.getInstallerPackageNameLPr(packageName);
14940        }
14941    }
14942
14943    @Override
14944    public int getApplicationEnabledSetting(String packageName, int userId) {
14945        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14946        int uid = Binder.getCallingUid();
14947        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14948        // reader
14949        synchronized (mPackages) {
14950            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14951        }
14952    }
14953
14954    @Override
14955    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14956        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14957        int uid = Binder.getCallingUid();
14958        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14959        // reader
14960        synchronized (mPackages) {
14961            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14962        }
14963    }
14964
14965    @Override
14966    public void enterSafeMode() {
14967        enforceSystemOrRoot("Only the system can request entering safe mode");
14968
14969        if (!mSystemReady) {
14970            mSafeMode = true;
14971        }
14972    }
14973
14974    @Override
14975    public void systemReady() {
14976        mSystemReady = true;
14977
14978        // Read the compatibilty setting when the system is ready.
14979        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14980                mContext.getContentResolver(),
14981                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14982        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14983        if (DEBUG_SETTINGS) {
14984            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14985        }
14986
14987        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14988
14989        synchronized (mPackages) {
14990            // Verify that all of the preferred activity components actually
14991            // exist.  It is possible for applications to be updated and at
14992            // that point remove a previously declared activity component that
14993            // had been set as a preferred activity.  We try to clean this up
14994            // the next time we encounter that preferred activity, but it is
14995            // possible for the user flow to never be able to return to that
14996            // situation so here we do a sanity check to make sure we haven't
14997            // left any junk around.
14998            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14999            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15000                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15001                removed.clear();
15002                for (PreferredActivity pa : pir.filterSet()) {
15003                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
15004                        removed.add(pa);
15005                    }
15006                }
15007                if (removed.size() > 0) {
15008                    for (int r=0; r<removed.size(); r++) {
15009                        PreferredActivity pa = removed.get(r);
15010                        Slog.w(TAG, "Removing dangling preferred activity: "
15011                                + pa.mPref.mComponent);
15012                        pir.removeFilter(pa);
15013                    }
15014                    mSettings.writePackageRestrictionsLPr(
15015                            mSettings.mPreferredActivities.keyAt(i));
15016                }
15017            }
15018
15019            for (int userId : UserManagerService.getInstance().getUserIds()) {
15020                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
15021                    grantPermissionsUserIds = ArrayUtils.appendInt(
15022                            grantPermissionsUserIds, userId);
15023                }
15024            }
15025        }
15026        sUserManager.systemReady();
15027
15028        // If we upgraded grant all default permissions before kicking off.
15029        for (int userId : grantPermissionsUserIds) {
15030            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
15031        }
15032
15033        // Kick off any messages waiting for system ready
15034        if (mPostSystemReadyMessages != null) {
15035            for (Message msg : mPostSystemReadyMessages) {
15036                msg.sendToTarget();
15037            }
15038            mPostSystemReadyMessages = null;
15039        }
15040
15041        // Watch for external volumes that come and go over time
15042        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15043        storage.registerListener(mStorageListener);
15044
15045        mInstallerService.systemReady();
15046        mPackageDexOptimizer.systemReady();
15047
15048        MountServiceInternal mountServiceInternal = LocalServices.getService(
15049                MountServiceInternal.class);
15050        mountServiceInternal.addExternalStoragePolicy(
15051                new MountServiceInternal.ExternalStorageMountPolicy() {
15052            @Override
15053            public int getMountMode(int uid, String packageName) {
15054                if (Process.isIsolated(uid)) {
15055                    return Zygote.MOUNT_EXTERNAL_NONE;
15056                }
15057                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
15058                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15059                }
15060                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15061                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15062                }
15063                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15064                    return Zygote.MOUNT_EXTERNAL_READ;
15065                }
15066                return Zygote.MOUNT_EXTERNAL_WRITE;
15067            }
15068
15069            @Override
15070            public boolean hasExternalStorage(int uid, String packageName) {
15071                return true;
15072            }
15073        });
15074    }
15075
15076    @Override
15077    public boolean isSafeMode() {
15078        return mSafeMode;
15079    }
15080
15081    @Override
15082    public boolean hasSystemUidErrors() {
15083        return mHasSystemUidErrors;
15084    }
15085
15086    static String arrayToString(int[] array) {
15087        StringBuffer buf = new StringBuffer(128);
15088        buf.append('[');
15089        if (array != null) {
15090            for (int i=0; i<array.length; i++) {
15091                if (i > 0) buf.append(", ");
15092                buf.append(array[i]);
15093            }
15094        }
15095        buf.append(']');
15096        return buf.toString();
15097    }
15098
15099    static class DumpState {
15100        public static final int DUMP_LIBS = 1 << 0;
15101        public static final int DUMP_FEATURES = 1 << 1;
15102        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
15103        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
15104        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
15105        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
15106        public static final int DUMP_PERMISSIONS = 1 << 6;
15107        public static final int DUMP_PACKAGES = 1 << 7;
15108        public static final int DUMP_SHARED_USERS = 1 << 8;
15109        public static final int DUMP_MESSAGES = 1 << 9;
15110        public static final int DUMP_PROVIDERS = 1 << 10;
15111        public static final int DUMP_VERIFIERS = 1 << 11;
15112        public static final int DUMP_PREFERRED = 1 << 12;
15113        public static final int DUMP_PREFERRED_XML = 1 << 13;
15114        public static final int DUMP_KEYSETS = 1 << 14;
15115        public static final int DUMP_VERSION = 1 << 15;
15116        public static final int DUMP_INSTALLS = 1 << 16;
15117        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
15118        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
15119
15120        public static final int OPTION_SHOW_FILTERS = 1 << 0;
15121
15122        private int mTypes;
15123
15124        private int mOptions;
15125
15126        private boolean mTitlePrinted;
15127
15128        private SharedUserSetting mSharedUser;
15129
15130        public boolean isDumping(int type) {
15131            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
15132                return true;
15133            }
15134
15135            return (mTypes & type) != 0;
15136        }
15137
15138        public void setDump(int type) {
15139            mTypes |= type;
15140        }
15141
15142        public boolean isOptionEnabled(int option) {
15143            return (mOptions & option) != 0;
15144        }
15145
15146        public void setOptionEnabled(int option) {
15147            mOptions |= option;
15148        }
15149
15150        public boolean onTitlePrinted() {
15151            final boolean printed = mTitlePrinted;
15152            mTitlePrinted = true;
15153            return printed;
15154        }
15155
15156        public boolean getTitlePrinted() {
15157            return mTitlePrinted;
15158        }
15159
15160        public void setTitlePrinted(boolean enabled) {
15161            mTitlePrinted = enabled;
15162        }
15163
15164        public SharedUserSetting getSharedUser() {
15165            return mSharedUser;
15166        }
15167
15168        public void setSharedUser(SharedUserSetting user) {
15169            mSharedUser = user;
15170        }
15171    }
15172
15173    @Override
15174    public void onShellCommand(FileDescriptor in, FileDescriptor out,
15175            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
15176        (new PackageManagerShellCommand(this)).exec(
15177                this, in, out, err, args, resultReceiver);
15178    }
15179
15180    @Override
15181    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
15182        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
15183                != PackageManager.PERMISSION_GRANTED) {
15184            pw.println("Permission Denial: can't dump ActivityManager from from pid="
15185                    + Binder.getCallingPid()
15186                    + ", uid=" + Binder.getCallingUid()
15187                    + " without permission "
15188                    + android.Manifest.permission.DUMP);
15189            return;
15190        }
15191
15192        DumpState dumpState = new DumpState();
15193        boolean fullPreferred = false;
15194        boolean checkin = false;
15195
15196        String packageName = null;
15197        ArraySet<String> permissionNames = null;
15198
15199        int opti = 0;
15200        while (opti < args.length) {
15201            String opt = args[opti];
15202            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
15203                break;
15204            }
15205            opti++;
15206
15207            if ("-a".equals(opt)) {
15208                // Right now we only know how to print all.
15209            } else if ("-h".equals(opt)) {
15210                pw.println("Package manager dump options:");
15211                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
15212                pw.println("    --checkin: dump for a checkin");
15213                pw.println("    -f: print details of intent filters");
15214                pw.println("    -h: print this help");
15215                pw.println("  cmd may be one of:");
15216                pw.println("    l[ibraries]: list known shared libraries");
15217                pw.println("    f[eatures]: list device features");
15218                pw.println("    k[eysets]: print known keysets");
15219                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
15220                pw.println("    perm[issions]: dump permissions");
15221                pw.println("    permission [name ...]: dump declaration and use of given permission");
15222                pw.println("    pref[erred]: print preferred package settings");
15223                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
15224                pw.println("    prov[iders]: dump content providers");
15225                pw.println("    p[ackages]: dump installed packages");
15226                pw.println("    s[hared-users]: dump shared user IDs");
15227                pw.println("    m[essages]: print collected runtime messages");
15228                pw.println("    v[erifiers]: print package verifier info");
15229                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
15230                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
15231                pw.println("    version: print database version info");
15232                pw.println("    write: write current settings now");
15233                pw.println("    installs: details about install sessions");
15234                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
15235                pw.println("    <package.name>: info about given package");
15236                return;
15237            } else if ("--checkin".equals(opt)) {
15238                checkin = true;
15239            } else if ("-f".equals(opt)) {
15240                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15241            } else {
15242                pw.println("Unknown argument: " + opt + "; use -h for help");
15243            }
15244        }
15245
15246        // Is the caller requesting to dump a particular piece of data?
15247        if (opti < args.length) {
15248            String cmd = args[opti];
15249            opti++;
15250            // Is this a package name?
15251            if ("android".equals(cmd) || cmd.contains(".")) {
15252                packageName = cmd;
15253                // When dumping a single package, we always dump all of its
15254                // filter information since the amount of data will be reasonable.
15255                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15256            } else if ("check-permission".equals(cmd)) {
15257                if (opti >= args.length) {
15258                    pw.println("Error: check-permission missing permission argument");
15259                    return;
15260                }
15261                String perm = args[opti];
15262                opti++;
15263                if (opti >= args.length) {
15264                    pw.println("Error: check-permission missing package argument");
15265                    return;
15266                }
15267                String pkg = args[opti];
15268                opti++;
15269                int user = UserHandle.getUserId(Binder.getCallingUid());
15270                if (opti < args.length) {
15271                    try {
15272                        user = Integer.parseInt(args[opti]);
15273                    } catch (NumberFormatException e) {
15274                        pw.println("Error: check-permission user argument is not a number: "
15275                                + args[opti]);
15276                        return;
15277                    }
15278                }
15279                pw.println(checkPermission(perm, pkg, user));
15280                return;
15281            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
15282                dumpState.setDump(DumpState.DUMP_LIBS);
15283            } else if ("f".equals(cmd) || "features".equals(cmd)) {
15284                dumpState.setDump(DumpState.DUMP_FEATURES);
15285            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
15286                if (opti >= args.length) {
15287                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
15288                            | DumpState.DUMP_SERVICE_RESOLVERS
15289                            | DumpState.DUMP_RECEIVER_RESOLVERS
15290                            | DumpState.DUMP_CONTENT_RESOLVERS);
15291                } else {
15292                    while (opti < args.length) {
15293                        String name = args[opti];
15294                        if ("a".equals(name) || "activity".equals(name)) {
15295                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
15296                        } else if ("s".equals(name) || "service".equals(name)) {
15297                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
15298                        } else if ("r".equals(name) || "receiver".equals(name)) {
15299                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
15300                        } else if ("c".equals(name) || "content".equals(name)) {
15301                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
15302                        } else {
15303                            pw.println("Error: unknown resolver table type: " + name);
15304                            return;
15305                        }
15306                        opti++;
15307                    }
15308                }
15309            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
15310                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
15311            } else if ("permission".equals(cmd)) {
15312                if (opti >= args.length) {
15313                    pw.println("Error: permission requires permission name");
15314                    return;
15315                }
15316                permissionNames = new ArraySet<>();
15317                while (opti < args.length) {
15318                    permissionNames.add(args[opti]);
15319                    opti++;
15320                }
15321                dumpState.setDump(DumpState.DUMP_PERMISSIONS
15322                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
15323            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
15324                dumpState.setDump(DumpState.DUMP_PREFERRED);
15325            } else if ("preferred-xml".equals(cmd)) {
15326                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
15327                if (opti < args.length && "--full".equals(args[opti])) {
15328                    fullPreferred = true;
15329                    opti++;
15330                }
15331            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
15332                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
15333            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
15334                dumpState.setDump(DumpState.DUMP_PACKAGES);
15335            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
15336                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
15337            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
15338                dumpState.setDump(DumpState.DUMP_PROVIDERS);
15339            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
15340                dumpState.setDump(DumpState.DUMP_MESSAGES);
15341            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
15342                dumpState.setDump(DumpState.DUMP_VERIFIERS);
15343            } else if ("i".equals(cmd) || "ifv".equals(cmd)
15344                    || "intent-filter-verifiers".equals(cmd)) {
15345                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
15346            } else if ("version".equals(cmd)) {
15347                dumpState.setDump(DumpState.DUMP_VERSION);
15348            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
15349                dumpState.setDump(DumpState.DUMP_KEYSETS);
15350            } else if ("installs".equals(cmd)) {
15351                dumpState.setDump(DumpState.DUMP_INSTALLS);
15352            } else if ("write".equals(cmd)) {
15353                synchronized (mPackages) {
15354                    mSettings.writeLPr();
15355                    pw.println("Settings written.");
15356                    return;
15357                }
15358            }
15359        }
15360
15361        if (checkin) {
15362            pw.println("vers,1");
15363        }
15364
15365        // reader
15366        synchronized (mPackages) {
15367            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
15368                if (!checkin) {
15369                    if (dumpState.onTitlePrinted())
15370                        pw.println();
15371                    pw.println("Database versions:");
15372                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
15373                }
15374            }
15375
15376            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
15377                if (!checkin) {
15378                    if (dumpState.onTitlePrinted())
15379                        pw.println();
15380                    pw.println("Verifiers:");
15381                    pw.print("  Required: ");
15382                    pw.print(mRequiredVerifierPackage);
15383                    pw.print(" (uid=");
15384                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
15385                    pw.println(")");
15386                } else if (mRequiredVerifierPackage != null) {
15387                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
15388                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
15389                }
15390            }
15391
15392            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
15393                    packageName == null) {
15394                if (mIntentFilterVerifierComponent != null) {
15395                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
15396                    if (!checkin) {
15397                        if (dumpState.onTitlePrinted())
15398                            pw.println();
15399                        pw.println("Intent Filter Verifier:");
15400                        pw.print("  Using: ");
15401                        pw.print(verifierPackageName);
15402                        pw.print(" (uid=");
15403                        pw.print(getPackageUid(verifierPackageName, 0));
15404                        pw.println(")");
15405                    } else if (verifierPackageName != null) {
15406                        pw.print("ifv,"); pw.print(verifierPackageName);
15407                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
15408                    }
15409                } else {
15410                    pw.println();
15411                    pw.println("No Intent Filter Verifier available!");
15412                }
15413            }
15414
15415            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
15416                boolean printedHeader = false;
15417                final Iterator<String> it = mSharedLibraries.keySet().iterator();
15418                while (it.hasNext()) {
15419                    String name = it.next();
15420                    SharedLibraryEntry ent = mSharedLibraries.get(name);
15421                    if (!checkin) {
15422                        if (!printedHeader) {
15423                            if (dumpState.onTitlePrinted())
15424                                pw.println();
15425                            pw.println("Libraries:");
15426                            printedHeader = true;
15427                        }
15428                        pw.print("  ");
15429                    } else {
15430                        pw.print("lib,");
15431                    }
15432                    pw.print(name);
15433                    if (!checkin) {
15434                        pw.print(" -> ");
15435                    }
15436                    if (ent.path != null) {
15437                        if (!checkin) {
15438                            pw.print("(jar) ");
15439                            pw.print(ent.path);
15440                        } else {
15441                            pw.print(",jar,");
15442                            pw.print(ent.path);
15443                        }
15444                    } else {
15445                        if (!checkin) {
15446                            pw.print("(apk) ");
15447                            pw.print(ent.apk);
15448                        } else {
15449                            pw.print(",apk,");
15450                            pw.print(ent.apk);
15451                        }
15452                    }
15453                    pw.println();
15454                }
15455            }
15456
15457            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
15458                if (dumpState.onTitlePrinted())
15459                    pw.println();
15460                if (!checkin) {
15461                    pw.println("Features:");
15462                }
15463                Iterator<String> it = mAvailableFeatures.keySet().iterator();
15464                while (it.hasNext()) {
15465                    String name = it.next();
15466                    if (!checkin) {
15467                        pw.print("  ");
15468                    } else {
15469                        pw.print("feat,");
15470                    }
15471                    pw.println(name);
15472                }
15473            }
15474
15475            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
15476                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
15477                        : "Activity Resolver Table:", "  ", packageName,
15478                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15479                    dumpState.setTitlePrinted(true);
15480                }
15481            }
15482            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
15483                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
15484                        : "Receiver Resolver Table:", "  ", packageName,
15485                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15486                    dumpState.setTitlePrinted(true);
15487                }
15488            }
15489            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
15490                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
15491                        : "Service Resolver Table:", "  ", packageName,
15492                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15493                    dumpState.setTitlePrinted(true);
15494                }
15495            }
15496            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
15497                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
15498                        : "Provider Resolver Table:", "  ", packageName,
15499                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15500                    dumpState.setTitlePrinted(true);
15501                }
15502            }
15503
15504            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
15505                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15506                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15507                    int user = mSettings.mPreferredActivities.keyAt(i);
15508                    if (pir.dump(pw,
15509                            dumpState.getTitlePrinted()
15510                                ? "\nPreferred Activities User " + user + ":"
15511                                : "Preferred Activities User " + user + ":", "  ",
15512                            packageName, true, false)) {
15513                        dumpState.setTitlePrinted(true);
15514                    }
15515                }
15516            }
15517
15518            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
15519                pw.flush();
15520                FileOutputStream fout = new FileOutputStream(fd);
15521                BufferedOutputStream str = new BufferedOutputStream(fout);
15522                XmlSerializer serializer = new FastXmlSerializer();
15523                try {
15524                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
15525                    serializer.startDocument(null, true);
15526                    serializer.setFeature(
15527                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
15528                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
15529                    serializer.endDocument();
15530                    serializer.flush();
15531                } catch (IllegalArgumentException e) {
15532                    pw.println("Failed writing: " + e);
15533                } catch (IllegalStateException e) {
15534                    pw.println("Failed writing: " + e);
15535                } catch (IOException e) {
15536                    pw.println("Failed writing: " + e);
15537                }
15538            }
15539
15540            if (!checkin
15541                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15542                    && packageName == null) {
15543                pw.println();
15544                int count = mSettings.mPackages.size();
15545                if (count == 0) {
15546                    pw.println("No applications!");
15547                    pw.println();
15548                } else {
15549                    final String prefix = "  ";
15550                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15551                    if (allPackageSettings.size() == 0) {
15552                        pw.println("No domain preferred apps!");
15553                        pw.println();
15554                    } else {
15555                        pw.println("App verification status:");
15556                        pw.println();
15557                        count = 0;
15558                        for (PackageSetting ps : allPackageSettings) {
15559                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15560                            if (ivi == null || ivi.getPackageName() == null) continue;
15561                            pw.println(prefix + "Package: " + ivi.getPackageName());
15562                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15563                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15564                            pw.println();
15565                            count++;
15566                        }
15567                        if (count == 0) {
15568                            pw.println(prefix + "No app verification established.");
15569                            pw.println();
15570                        }
15571                        for (int userId : sUserManager.getUserIds()) {
15572                            pw.println("App linkages for user " + userId + ":");
15573                            pw.println();
15574                            count = 0;
15575                            for (PackageSetting ps : allPackageSettings) {
15576                                final long status = ps.getDomainVerificationStatusForUser(userId);
15577                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15578                                    continue;
15579                                }
15580                                pw.println(prefix + "Package: " + ps.name);
15581                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15582                                String statusStr = IntentFilterVerificationInfo.
15583                                        getStatusStringFromValue(status);
15584                                pw.println(prefix + "Status:  " + statusStr);
15585                                pw.println();
15586                                count++;
15587                            }
15588                            if (count == 0) {
15589                                pw.println(prefix + "No configured app linkages.");
15590                                pw.println();
15591                            }
15592                        }
15593                    }
15594                }
15595            }
15596
15597            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15598                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15599                if (packageName == null && permissionNames == null) {
15600                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15601                        if (iperm == 0) {
15602                            if (dumpState.onTitlePrinted())
15603                                pw.println();
15604                            pw.println("AppOp Permissions:");
15605                        }
15606                        pw.print("  AppOp Permission ");
15607                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15608                        pw.println(":");
15609                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15610                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15611                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15612                        }
15613                    }
15614                }
15615            }
15616
15617            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15618                boolean printedSomething = false;
15619                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15620                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15621                        continue;
15622                    }
15623                    if (!printedSomething) {
15624                        if (dumpState.onTitlePrinted())
15625                            pw.println();
15626                        pw.println("Registered ContentProviders:");
15627                        printedSomething = true;
15628                    }
15629                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15630                    pw.print("    "); pw.println(p.toString());
15631                }
15632                printedSomething = false;
15633                for (Map.Entry<String, PackageParser.Provider> entry :
15634                        mProvidersByAuthority.entrySet()) {
15635                    PackageParser.Provider p = entry.getValue();
15636                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15637                        continue;
15638                    }
15639                    if (!printedSomething) {
15640                        if (dumpState.onTitlePrinted())
15641                            pw.println();
15642                        pw.println("ContentProvider Authorities:");
15643                        printedSomething = true;
15644                    }
15645                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15646                    pw.print("    "); pw.println(p.toString());
15647                    if (p.info != null && p.info.applicationInfo != null) {
15648                        final String appInfo = p.info.applicationInfo.toString();
15649                        pw.print("      applicationInfo="); pw.println(appInfo);
15650                    }
15651                }
15652            }
15653
15654            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15655                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15656            }
15657
15658            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15659                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15660            }
15661
15662            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15663                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15664            }
15665
15666            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15667                // XXX should handle packageName != null by dumping only install data that
15668                // the given package is involved with.
15669                if (dumpState.onTitlePrinted()) pw.println();
15670                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15671            }
15672
15673            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15674                if (dumpState.onTitlePrinted()) pw.println();
15675                mSettings.dumpReadMessagesLPr(pw, dumpState);
15676
15677                pw.println();
15678                pw.println("Package warning messages:");
15679                BufferedReader in = null;
15680                String line = null;
15681                try {
15682                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15683                    while ((line = in.readLine()) != null) {
15684                        if (line.contains("ignored: updated version")) continue;
15685                        pw.println(line);
15686                    }
15687                } catch (IOException ignored) {
15688                } finally {
15689                    IoUtils.closeQuietly(in);
15690                }
15691            }
15692
15693            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15694                BufferedReader in = null;
15695                String line = null;
15696                try {
15697                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15698                    while ((line = in.readLine()) != null) {
15699                        if (line.contains("ignored: updated version")) continue;
15700                        pw.print("msg,");
15701                        pw.println(line);
15702                    }
15703                } catch (IOException ignored) {
15704                } finally {
15705                    IoUtils.closeQuietly(in);
15706                }
15707            }
15708        }
15709    }
15710
15711    private String dumpDomainString(String packageName) {
15712        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15713        List<IntentFilter> filters = getAllIntentFilters(packageName);
15714
15715        ArraySet<String> result = new ArraySet<>();
15716        if (iviList.size() > 0) {
15717            for (IntentFilterVerificationInfo ivi : iviList) {
15718                for (String host : ivi.getDomains()) {
15719                    result.add(host);
15720                }
15721            }
15722        }
15723        if (filters != null && filters.size() > 0) {
15724            for (IntentFilter filter : filters) {
15725                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
15726                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15727                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
15728                    result.addAll(filter.getHostsList());
15729                }
15730            }
15731        }
15732
15733        StringBuilder sb = new StringBuilder(result.size() * 16);
15734        for (String domain : result) {
15735            if (sb.length() > 0) sb.append(" ");
15736            sb.append(domain);
15737        }
15738        return sb.toString();
15739    }
15740
15741    // ------- apps on sdcard specific code -------
15742    static final boolean DEBUG_SD_INSTALL = false;
15743
15744    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15745
15746    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15747
15748    private boolean mMediaMounted = false;
15749
15750    static String getEncryptKey() {
15751        try {
15752            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15753                    SD_ENCRYPTION_KEYSTORE_NAME);
15754            if (sdEncKey == null) {
15755                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15756                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15757                if (sdEncKey == null) {
15758                    Slog.e(TAG, "Failed to create encryption keys");
15759                    return null;
15760                }
15761            }
15762            return sdEncKey;
15763        } catch (NoSuchAlgorithmException nsae) {
15764            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15765            return null;
15766        } catch (IOException ioe) {
15767            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15768            return null;
15769        }
15770    }
15771
15772    /*
15773     * Update media status on PackageManager.
15774     */
15775    @Override
15776    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15777        int callingUid = Binder.getCallingUid();
15778        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15779            throw new SecurityException("Media status can only be updated by the system");
15780        }
15781        // reader; this apparently protects mMediaMounted, but should probably
15782        // be a different lock in that case.
15783        synchronized (mPackages) {
15784            Log.i(TAG, "Updating external media status from "
15785                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15786                    + (mediaStatus ? "mounted" : "unmounted"));
15787            if (DEBUG_SD_INSTALL)
15788                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15789                        + ", mMediaMounted=" + mMediaMounted);
15790            if (mediaStatus == mMediaMounted) {
15791                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15792                        : 0, -1);
15793                mHandler.sendMessage(msg);
15794                return;
15795            }
15796            mMediaMounted = mediaStatus;
15797        }
15798        // Queue up an async operation since the package installation may take a
15799        // little while.
15800        mHandler.post(new Runnable() {
15801            public void run() {
15802                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15803            }
15804        });
15805    }
15806
15807    /**
15808     * Called by MountService when the initial ASECs to scan are available.
15809     * Should block until all the ASEC containers are finished being scanned.
15810     */
15811    public void scanAvailableAsecs() {
15812        updateExternalMediaStatusInner(true, false, false);
15813        if (mShouldRestoreconData) {
15814            SELinuxMMAC.setRestoreconDone();
15815            mShouldRestoreconData = false;
15816        }
15817    }
15818
15819    /*
15820     * Collect information of applications on external media, map them against
15821     * existing containers and update information based on current mount status.
15822     * Please note that we always have to report status if reportStatus has been
15823     * set to true especially when unloading packages.
15824     */
15825    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15826            boolean externalStorage) {
15827        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15828        int[] uidArr = EmptyArray.INT;
15829
15830        final String[] list = PackageHelper.getSecureContainerList();
15831        if (ArrayUtils.isEmpty(list)) {
15832            Log.i(TAG, "No secure containers found");
15833        } else {
15834            // Process list of secure containers and categorize them
15835            // as active or stale based on their package internal state.
15836
15837            // reader
15838            synchronized (mPackages) {
15839                for (String cid : list) {
15840                    // Leave stages untouched for now; installer service owns them
15841                    if (PackageInstallerService.isStageName(cid)) continue;
15842
15843                    if (DEBUG_SD_INSTALL)
15844                        Log.i(TAG, "Processing container " + cid);
15845                    String pkgName = getAsecPackageName(cid);
15846                    if (pkgName == null) {
15847                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15848                        continue;
15849                    }
15850                    if (DEBUG_SD_INSTALL)
15851                        Log.i(TAG, "Looking for pkg : " + pkgName);
15852
15853                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15854                    if (ps == null) {
15855                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15856                        continue;
15857                    }
15858
15859                    /*
15860                     * Skip packages that are not external if we're unmounting
15861                     * external storage.
15862                     */
15863                    if (externalStorage && !isMounted && !isExternal(ps)) {
15864                        continue;
15865                    }
15866
15867                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15868                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15869                    // The package status is changed only if the code path
15870                    // matches between settings and the container id.
15871                    if (ps.codePathString != null
15872                            && ps.codePathString.startsWith(args.getCodePath())) {
15873                        if (DEBUG_SD_INSTALL) {
15874                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15875                                    + " at code path: " + ps.codePathString);
15876                        }
15877
15878                        // We do have a valid package installed on sdcard
15879                        processCids.put(args, ps.codePathString);
15880                        final int uid = ps.appId;
15881                        if (uid != -1) {
15882                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15883                        }
15884                    } else {
15885                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15886                                + ps.codePathString);
15887                    }
15888                }
15889            }
15890
15891            Arrays.sort(uidArr);
15892        }
15893
15894        // Process packages with valid entries.
15895        if (isMounted) {
15896            if (DEBUG_SD_INSTALL)
15897                Log.i(TAG, "Loading packages");
15898            loadMediaPackages(processCids, uidArr, externalStorage);
15899            startCleaningPackages();
15900            mInstallerService.onSecureContainersAvailable();
15901        } else {
15902            if (DEBUG_SD_INSTALL)
15903                Log.i(TAG, "Unloading packages");
15904            unloadMediaPackages(processCids, uidArr, reportStatus);
15905        }
15906    }
15907
15908    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15909            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15910        final int size = infos.size();
15911        final String[] packageNames = new String[size];
15912        final int[] packageUids = new int[size];
15913        for (int i = 0; i < size; i++) {
15914            final ApplicationInfo info = infos.get(i);
15915            packageNames[i] = info.packageName;
15916            packageUids[i] = info.uid;
15917        }
15918        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15919                finishedReceiver);
15920    }
15921
15922    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15923            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15924        sendResourcesChangedBroadcast(mediaStatus, replacing,
15925                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15926    }
15927
15928    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15929            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15930        int size = pkgList.length;
15931        if (size > 0) {
15932            // Send broadcasts here
15933            Bundle extras = new Bundle();
15934            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15935            if (uidArr != null) {
15936                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15937            }
15938            if (replacing) {
15939                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15940            }
15941            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15942                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15943            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
15944        }
15945    }
15946
15947   /*
15948     * Look at potentially valid container ids from processCids If package
15949     * information doesn't match the one on record or package scanning fails,
15950     * the cid is added to list of removeCids. We currently don't delete stale
15951     * containers.
15952     */
15953    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
15954            boolean externalStorage) {
15955        ArrayList<String> pkgList = new ArrayList<String>();
15956        Set<AsecInstallArgs> keys = processCids.keySet();
15957
15958        for (AsecInstallArgs args : keys) {
15959            String codePath = processCids.get(args);
15960            if (DEBUG_SD_INSTALL)
15961                Log.i(TAG, "Loading container : " + args.cid);
15962            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15963            try {
15964                // Make sure there are no container errors first.
15965                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15966                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15967                            + " when installing from sdcard");
15968                    continue;
15969                }
15970                // Check code path here.
15971                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15972                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15973                            + " does not match one in settings " + codePath);
15974                    continue;
15975                }
15976                // Parse package
15977                int parseFlags = mDefParseFlags;
15978                if (args.isExternalAsec()) {
15979                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15980                }
15981                if (args.isFwdLocked()) {
15982                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15983                }
15984
15985                synchronized (mInstallLock) {
15986                    PackageParser.Package pkg = null;
15987                    try {
15988                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
15989                    } catch (PackageManagerException e) {
15990                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15991                    }
15992                    // Scan the package
15993                    if (pkg != null) {
15994                        /*
15995                         * TODO why is the lock being held? doPostInstall is
15996                         * called in other places without the lock. This needs
15997                         * to be straightened out.
15998                         */
15999                        // writer
16000                        synchronized (mPackages) {
16001                            retCode = PackageManager.INSTALL_SUCCEEDED;
16002                            pkgList.add(pkg.packageName);
16003                            // Post process args
16004                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
16005                                    pkg.applicationInfo.uid);
16006                        }
16007                    } else {
16008                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
16009                    }
16010                }
16011
16012            } finally {
16013                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
16014                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
16015                }
16016            }
16017        }
16018        // writer
16019        synchronized (mPackages) {
16020            // If the platform SDK has changed since the last time we booted,
16021            // we need to re-grant app permission to catch any new ones that
16022            // appear. This is really a hack, and means that apps can in some
16023            // cases get permissions that the user didn't initially explicitly
16024            // allow... it would be nice to have some better way to handle
16025            // this situation.
16026            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
16027                    : mSettings.getInternalVersion();
16028            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
16029                    : StorageManager.UUID_PRIVATE_INTERNAL;
16030
16031            int updateFlags = UPDATE_PERMISSIONS_ALL;
16032            if (ver.sdkVersion != mSdkVersion) {
16033                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16034                        + mSdkVersion + "; regranting permissions for external");
16035                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16036            }
16037            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
16038
16039            // Yay, everything is now upgraded
16040            ver.forceCurrent();
16041
16042            // can downgrade to reader
16043            // Persist settings
16044            mSettings.writeLPr();
16045        }
16046        // Send a broadcast to let everyone know we are done processing
16047        if (pkgList.size() > 0) {
16048            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
16049        }
16050    }
16051
16052   /*
16053     * Utility method to unload a list of specified containers
16054     */
16055    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
16056        // Just unmount all valid containers.
16057        for (AsecInstallArgs arg : cidArgs) {
16058            synchronized (mInstallLock) {
16059                arg.doPostDeleteLI(false);
16060           }
16061       }
16062   }
16063
16064    /*
16065     * Unload packages mounted on external media. This involves deleting package
16066     * data from internal structures, sending broadcasts about diabled packages,
16067     * gc'ing to free up references, unmounting all secure containers
16068     * corresponding to packages on external media, and posting a
16069     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
16070     * that we always have to post this message if status has been requested no
16071     * matter what.
16072     */
16073    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
16074            final boolean reportStatus) {
16075        if (DEBUG_SD_INSTALL)
16076            Log.i(TAG, "unloading media packages");
16077        ArrayList<String> pkgList = new ArrayList<String>();
16078        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
16079        final Set<AsecInstallArgs> keys = processCids.keySet();
16080        for (AsecInstallArgs args : keys) {
16081            String pkgName = args.getPackageName();
16082            if (DEBUG_SD_INSTALL)
16083                Log.i(TAG, "Trying to unload pkg : " + pkgName);
16084            // Delete package internally
16085            PackageRemovedInfo outInfo = new PackageRemovedInfo();
16086            synchronized (mInstallLock) {
16087                boolean res = deletePackageLI(pkgName, null, false, null, null,
16088                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
16089                if (res) {
16090                    pkgList.add(pkgName);
16091                } else {
16092                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
16093                    failedList.add(args);
16094                }
16095            }
16096        }
16097
16098        // reader
16099        synchronized (mPackages) {
16100            // We didn't update the settings after removing each package;
16101            // write them now for all packages.
16102            mSettings.writeLPr();
16103        }
16104
16105        // We have to absolutely send UPDATED_MEDIA_STATUS only
16106        // after confirming that all the receivers processed the ordered
16107        // broadcast when packages get disabled, force a gc to clean things up.
16108        // and unload all the containers.
16109        if (pkgList.size() > 0) {
16110            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
16111                    new IIntentReceiver.Stub() {
16112                public void performReceive(Intent intent, int resultCode, String data,
16113                        Bundle extras, boolean ordered, boolean sticky,
16114                        int sendingUser) throws RemoteException {
16115                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
16116                            reportStatus ? 1 : 0, 1, keys);
16117                    mHandler.sendMessage(msg);
16118                }
16119            });
16120        } else {
16121            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
16122                    keys);
16123            mHandler.sendMessage(msg);
16124        }
16125    }
16126
16127    private void loadPrivatePackages(final VolumeInfo vol) {
16128        mHandler.post(new Runnable() {
16129            @Override
16130            public void run() {
16131                loadPrivatePackagesInner(vol);
16132            }
16133        });
16134    }
16135
16136    private void loadPrivatePackagesInner(VolumeInfo vol) {
16137        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
16138        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
16139
16140        final VersionInfo ver;
16141        final List<PackageSetting> packages;
16142        synchronized (mPackages) {
16143            ver = mSettings.findOrCreateVersion(vol.fsUuid);
16144            packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16145        }
16146
16147        for (PackageSetting ps : packages) {
16148            synchronized (mInstallLock) {
16149                final PackageParser.Package pkg;
16150                try {
16151                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
16152                    loaded.add(pkg.applicationInfo);
16153                } catch (PackageManagerException e) {
16154                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
16155                }
16156
16157                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
16158                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
16159                }
16160            }
16161        }
16162
16163        synchronized (mPackages) {
16164            int updateFlags = UPDATE_PERMISSIONS_ALL;
16165            if (ver.sdkVersion != mSdkVersion) {
16166                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16167                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
16168                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16169            }
16170            updatePermissionsLPw(null, null, vol.fsUuid, updateFlags);
16171
16172            // Yay, everything is now upgraded
16173            ver.forceCurrent();
16174
16175            mSettings.writeLPr();
16176        }
16177
16178        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
16179        sendResourcesChangedBroadcast(true, false, loaded, null);
16180    }
16181
16182    private void unloadPrivatePackages(final VolumeInfo vol) {
16183        mHandler.post(new Runnable() {
16184            @Override
16185            public void run() {
16186                unloadPrivatePackagesInner(vol);
16187            }
16188        });
16189    }
16190
16191    private void unloadPrivatePackagesInner(VolumeInfo vol) {
16192        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
16193        synchronized (mInstallLock) {
16194        synchronized (mPackages) {
16195            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16196            for (PackageSetting ps : packages) {
16197                if (ps.pkg == null) continue;
16198
16199                final ApplicationInfo info = ps.pkg.applicationInfo;
16200                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
16201                if (deletePackageLI(ps.name, null, false, null, null,
16202                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
16203                    unloaded.add(info);
16204                } else {
16205                    Slog.w(TAG, "Failed to unload " + ps.codePath);
16206                }
16207            }
16208
16209            mSettings.writeLPr();
16210        }
16211        }
16212
16213        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
16214        sendResourcesChangedBroadcast(false, false, unloaded, null);
16215    }
16216
16217    /**
16218     * Examine all users present on given mounted volume, and destroy data
16219     * belonging to users that are no longer valid, or whose user ID has been
16220     * recycled.
16221     */
16222    private void reconcileUsers(String volumeUuid) {
16223        final File[] files = FileUtils
16224                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
16225        for (File file : files) {
16226            if (!file.isDirectory()) continue;
16227
16228            final int userId;
16229            final UserInfo info;
16230            try {
16231                userId = Integer.parseInt(file.getName());
16232                info = sUserManager.getUserInfo(userId);
16233            } catch (NumberFormatException e) {
16234                Slog.w(TAG, "Invalid user directory " + file);
16235                continue;
16236            }
16237
16238            boolean destroyUser = false;
16239            if (info == null) {
16240                logCriticalInfo(Log.WARN, "Destroying user directory " + file
16241                        + " because no matching user was found");
16242                destroyUser = true;
16243            } else {
16244                try {
16245                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
16246                } catch (IOException e) {
16247                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
16248                            + " because we failed to enforce serial number: " + e);
16249                    destroyUser = true;
16250                }
16251            }
16252
16253            if (destroyUser) {
16254                synchronized (mInstallLock) {
16255                    mInstaller.removeUserDataDirs(volumeUuid, userId);
16256                }
16257            }
16258        }
16259
16260        final StorageManager sm = mContext.getSystemService(StorageManager.class);
16261        final UserManager um = mContext.getSystemService(UserManager.class);
16262        for (UserInfo user : um.getUsers()) {
16263            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
16264            if (userDir.exists()) continue;
16265
16266            try {
16267                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber);
16268                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
16269            } catch (IOException e) {
16270                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
16271            }
16272        }
16273    }
16274
16275    /**
16276     * Examine all apps present on given mounted volume, and destroy apps that
16277     * aren't expected, either due to uninstallation or reinstallation on
16278     * another volume.
16279     */
16280    private void reconcileApps(String volumeUuid) {
16281        final File[] files = FileUtils
16282                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
16283        for (File file : files) {
16284            final boolean isPackage = (isApkFile(file) || file.isDirectory())
16285                    && !PackageInstallerService.isStageName(file.getName());
16286            if (!isPackage) {
16287                // Ignore entries which are not packages
16288                continue;
16289            }
16290
16291            boolean destroyApp = false;
16292            String packageName = null;
16293            try {
16294                final PackageLite pkg = PackageParser.parsePackageLite(file,
16295                        PackageParser.PARSE_MUST_BE_APK);
16296                packageName = pkg.packageName;
16297
16298                synchronized (mPackages) {
16299                    final PackageSetting ps = mSettings.mPackages.get(packageName);
16300                    if (ps == null) {
16301                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
16302                                + volumeUuid + " because we found no install record");
16303                        destroyApp = true;
16304                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
16305                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
16306                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
16307                        destroyApp = true;
16308                    }
16309                }
16310
16311            } catch (PackageParserException e) {
16312                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
16313                destroyApp = true;
16314            }
16315
16316            if (destroyApp) {
16317                synchronized (mInstallLock) {
16318                    if (packageName != null) {
16319                        removeDataDirsLI(volumeUuid, packageName);
16320                    }
16321                    if (file.isDirectory()) {
16322                        mInstaller.rmPackageDir(file.getAbsolutePath());
16323                    } else {
16324                        file.delete();
16325                    }
16326                }
16327            }
16328        }
16329    }
16330
16331    private void unfreezePackage(String packageName) {
16332        synchronized (mPackages) {
16333            final PackageSetting ps = mSettings.mPackages.get(packageName);
16334            if (ps != null) {
16335                ps.frozen = false;
16336            }
16337        }
16338    }
16339
16340    @Override
16341    public int movePackage(final String packageName, final String volumeUuid) {
16342        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16343
16344        final int moveId = mNextMoveId.getAndIncrement();
16345        mHandler.post(new Runnable() {
16346            @Override
16347            public void run() {
16348                try {
16349                    movePackageInternal(packageName, volumeUuid, moveId);
16350                } catch (PackageManagerException e) {
16351                    Slog.w(TAG, "Failed to move " + packageName, e);
16352                    mMoveCallbacks.notifyStatusChanged(moveId,
16353                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16354                }
16355            }
16356        });
16357        return moveId;
16358    }
16359
16360    private void movePackageInternal(final String packageName, final String volumeUuid,
16361            final int moveId) throws PackageManagerException {
16362        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
16363        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16364        final PackageManager pm = mContext.getPackageManager();
16365
16366        final boolean currentAsec;
16367        final String currentVolumeUuid;
16368        final File codeFile;
16369        final String installerPackageName;
16370        final String packageAbiOverride;
16371        final int appId;
16372        final String seinfo;
16373        final String label;
16374
16375        // reader
16376        synchronized (mPackages) {
16377            final PackageParser.Package pkg = mPackages.get(packageName);
16378            final PackageSetting ps = mSettings.mPackages.get(packageName);
16379            if (pkg == null || ps == null) {
16380                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
16381            }
16382
16383            if (pkg.applicationInfo.isSystemApp()) {
16384                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
16385                        "Cannot move system application");
16386            }
16387
16388            if (pkg.applicationInfo.isExternalAsec()) {
16389                currentAsec = true;
16390                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
16391            } else if (pkg.applicationInfo.isForwardLocked()) {
16392                currentAsec = true;
16393                currentVolumeUuid = "forward_locked";
16394            } else {
16395                currentAsec = false;
16396                currentVolumeUuid = ps.volumeUuid;
16397
16398                final File probe = new File(pkg.codePath);
16399                final File probeOat = new File(probe, "oat");
16400                if (!probe.isDirectory() || !probeOat.isDirectory()) {
16401                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16402                            "Move only supported for modern cluster style installs");
16403                }
16404            }
16405
16406            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
16407                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16408                        "Package already moved to " + volumeUuid);
16409            }
16410
16411            if (ps.frozen) {
16412                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
16413                        "Failed to move already frozen package");
16414            }
16415            ps.frozen = true;
16416
16417            codeFile = new File(pkg.codePath);
16418            installerPackageName = ps.installerPackageName;
16419            packageAbiOverride = ps.cpuAbiOverrideString;
16420            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16421            seinfo = pkg.applicationInfo.seinfo;
16422            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
16423        }
16424
16425        // Now that we're guarded by frozen state, kill app during move
16426        final long token = Binder.clearCallingIdentity();
16427        try {
16428            killApplication(packageName, appId, "move pkg");
16429        } finally {
16430            Binder.restoreCallingIdentity(token);
16431        }
16432
16433        final Bundle extras = new Bundle();
16434        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
16435        extras.putString(Intent.EXTRA_TITLE, label);
16436        mMoveCallbacks.notifyCreated(moveId, extras);
16437
16438        int installFlags;
16439        final boolean moveCompleteApp;
16440        final File measurePath;
16441
16442        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
16443            installFlags = INSTALL_INTERNAL;
16444            moveCompleteApp = !currentAsec;
16445            measurePath = Environment.getDataAppDirectory(volumeUuid);
16446        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
16447            installFlags = INSTALL_EXTERNAL;
16448            moveCompleteApp = false;
16449            measurePath = storage.getPrimaryPhysicalVolume().getPath();
16450        } else {
16451            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
16452            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
16453                    || !volume.isMountedWritable()) {
16454                unfreezePackage(packageName);
16455                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16456                        "Move location not mounted private volume");
16457            }
16458
16459            Preconditions.checkState(!currentAsec);
16460
16461            installFlags = INSTALL_INTERNAL;
16462            moveCompleteApp = true;
16463            measurePath = Environment.getDataAppDirectory(volumeUuid);
16464        }
16465
16466        final PackageStats stats = new PackageStats(null, -1);
16467        synchronized (mInstaller) {
16468            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
16469                unfreezePackage(packageName);
16470                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16471                        "Failed to measure package size");
16472            }
16473        }
16474
16475        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
16476                + stats.dataSize);
16477
16478        final long startFreeBytes = measurePath.getFreeSpace();
16479        final long sizeBytes;
16480        if (moveCompleteApp) {
16481            sizeBytes = stats.codeSize + stats.dataSize;
16482        } else {
16483            sizeBytes = stats.codeSize;
16484        }
16485
16486        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
16487            unfreezePackage(packageName);
16488            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16489                    "Not enough free space to move");
16490        }
16491
16492        mMoveCallbacks.notifyStatusChanged(moveId, 10);
16493
16494        final CountDownLatch installedLatch = new CountDownLatch(1);
16495        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
16496            @Override
16497            public void onUserActionRequired(Intent intent) throws RemoteException {
16498                throw new IllegalStateException();
16499            }
16500
16501            @Override
16502            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
16503                    Bundle extras) throws RemoteException {
16504                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
16505                        + PackageManager.installStatusToString(returnCode, msg));
16506
16507                installedLatch.countDown();
16508
16509                // Regardless of success or failure of the move operation,
16510                // always unfreeze the package
16511                unfreezePackage(packageName);
16512
16513                final int status = PackageManager.installStatusToPublicStatus(returnCode);
16514                switch (status) {
16515                    case PackageInstaller.STATUS_SUCCESS:
16516                        mMoveCallbacks.notifyStatusChanged(moveId,
16517                                PackageManager.MOVE_SUCCEEDED);
16518                        break;
16519                    case PackageInstaller.STATUS_FAILURE_STORAGE:
16520                        mMoveCallbacks.notifyStatusChanged(moveId,
16521                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
16522                        break;
16523                    default:
16524                        mMoveCallbacks.notifyStatusChanged(moveId,
16525                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16526                        break;
16527                }
16528            }
16529        };
16530
16531        final MoveInfo move;
16532        if (moveCompleteApp) {
16533            // Kick off a thread to report progress estimates
16534            new Thread() {
16535                @Override
16536                public void run() {
16537                    while (true) {
16538                        try {
16539                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
16540                                break;
16541                            }
16542                        } catch (InterruptedException ignored) {
16543                        }
16544
16545                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
16546                        final int progress = 10 + (int) MathUtils.constrain(
16547                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
16548                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
16549                    }
16550                }
16551            }.start();
16552
16553            final String dataAppName = codeFile.getName();
16554            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
16555                    dataAppName, appId, seinfo);
16556        } else {
16557            move = null;
16558        }
16559
16560        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
16561
16562        final Message msg = mHandler.obtainMessage(INIT_COPY);
16563        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
16564        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
16565                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
16566        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
16567        msg.obj = params;
16568
16569        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
16570                System.identityHashCode(msg.obj));
16571        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
16572                System.identityHashCode(msg.obj));
16573
16574        mHandler.sendMessage(msg);
16575    }
16576
16577    @Override
16578    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
16579        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16580
16581        final int realMoveId = mNextMoveId.getAndIncrement();
16582        final Bundle extras = new Bundle();
16583        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
16584        mMoveCallbacks.notifyCreated(realMoveId, extras);
16585
16586        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
16587            @Override
16588            public void onCreated(int moveId, Bundle extras) {
16589                // Ignored
16590            }
16591
16592            @Override
16593            public void onStatusChanged(int moveId, int status, long estMillis) {
16594                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16595            }
16596        };
16597
16598        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16599        storage.setPrimaryStorageUuid(volumeUuid, callback);
16600        return realMoveId;
16601    }
16602
16603    @Override
16604    public int getMoveStatus(int moveId) {
16605        mContext.enforceCallingOrSelfPermission(
16606                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16607        return mMoveCallbacks.mLastStatus.get(moveId);
16608    }
16609
16610    @Override
16611    public void registerMoveCallback(IPackageMoveObserver callback) {
16612        mContext.enforceCallingOrSelfPermission(
16613                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16614        mMoveCallbacks.register(callback);
16615    }
16616
16617    @Override
16618    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16619        mContext.enforceCallingOrSelfPermission(
16620                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16621        mMoveCallbacks.unregister(callback);
16622    }
16623
16624    @Override
16625    public boolean setInstallLocation(int loc) {
16626        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16627                null);
16628        if (getInstallLocation() == loc) {
16629            return true;
16630        }
16631        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16632                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16633            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16634                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16635            return true;
16636        }
16637        return false;
16638   }
16639
16640    @Override
16641    public int getInstallLocation() {
16642        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16643                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16644                PackageHelper.APP_INSTALL_AUTO);
16645    }
16646
16647    /** Called by UserManagerService */
16648    void cleanUpUser(UserManagerService userManager, int userHandle) {
16649        synchronized (mPackages) {
16650            mDirtyUsers.remove(userHandle);
16651            mUserNeedsBadging.delete(userHandle);
16652            mSettings.removeUserLPw(userHandle);
16653            mPendingBroadcasts.remove(userHandle);
16654        }
16655        synchronized (mInstallLock) {
16656            if (mInstaller != null) {
16657                final StorageManager storage = mContext.getSystemService(StorageManager.class);
16658                for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16659                    final String volumeUuid = vol.getFsUuid();
16660                    if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16661                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16662                }
16663            }
16664            synchronized (mPackages) {
16665                removeUnusedPackagesLILPw(userManager, userHandle);
16666            }
16667        }
16668    }
16669
16670    /**
16671     * We're removing userHandle and would like to remove any downloaded packages
16672     * that are no longer in use by any other user.
16673     * @param userHandle the user being removed
16674     */
16675    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16676        final boolean DEBUG_CLEAN_APKS = false;
16677        int [] users = userManager.getUserIds();
16678        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16679        while (psit.hasNext()) {
16680            PackageSetting ps = psit.next();
16681            if (ps.pkg == null) {
16682                continue;
16683            }
16684            final String packageName = ps.pkg.packageName;
16685            // Skip over if system app
16686            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16687                continue;
16688            }
16689            if (DEBUG_CLEAN_APKS) {
16690                Slog.i(TAG, "Checking package " + packageName);
16691            }
16692            boolean keep = false;
16693            for (int i = 0; i < users.length; i++) {
16694                if (users[i] != userHandle && ps.getInstalled(users[i])) {
16695                    keep = true;
16696                    if (DEBUG_CLEAN_APKS) {
16697                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
16698                                + users[i]);
16699                    }
16700                    break;
16701                }
16702            }
16703            if (!keep) {
16704                if (DEBUG_CLEAN_APKS) {
16705                    Slog.i(TAG, "  Removing package " + packageName);
16706                }
16707                mHandler.post(new Runnable() {
16708                    public void run() {
16709                        deletePackageX(packageName, userHandle, 0);
16710                    } //end run
16711                });
16712            }
16713        }
16714    }
16715
16716    /** Called by UserManagerService */
16717    void createNewUser(int userHandle) {
16718        if (mInstaller != null) {
16719            synchronized (mInstallLock) {
16720                synchronized (mPackages) {
16721                    mInstaller.createUserConfig(userHandle);
16722                    mSettings.createNewUserLILPw(this, mInstaller, userHandle);
16723                }
16724            }
16725            synchronized (mPackages) {
16726                applyFactoryDefaultBrowserLPw(userHandle);
16727                primeDomainVerificationsLPw(userHandle);
16728            }
16729        }
16730    }
16731
16732    void newUserCreated(final int userHandle) {
16733        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
16734    }
16735
16736    @Override
16737    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
16738        mContext.enforceCallingOrSelfPermission(
16739                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16740                "Only package verification agents can read the verifier device identity");
16741
16742        synchronized (mPackages) {
16743            return mSettings.getVerifierDeviceIdentityLPw();
16744        }
16745    }
16746
16747    @Override
16748    public void setPermissionEnforced(String permission, boolean enforced) {
16749        // TODO: Now that we no longer change GID for storage, this should to away.
16750        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
16751                "setPermissionEnforced");
16752        if (READ_EXTERNAL_STORAGE.equals(permission)) {
16753            synchronized (mPackages) {
16754                if (mSettings.mReadExternalStorageEnforced == null
16755                        || mSettings.mReadExternalStorageEnforced != enforced) {
16756                    mSettings.mReadExternalStorageEnforced = enforced;
16757                    mSettings.writeLPr();
16758                }
16759            }
16760            // kill any non-foreground processes so we restart them and
16761            // grant/revoke the GID.
16762            final IActivityManager am = ActivityManagerNative.getDefault();
16763            if (am != null) {
16764                final long token = Binder.clearCallingIdentity();
16765                try {
16766                    am.killProcessesBelowForeground("setPermissionEnforcement");
16767                } catch (RemoteException e) {
16768                } finally {
16769                    Binder.restoreCallingIdentity(token);
16770                }
16771            }
16772        } else {
16773            throw new IllegalArgumentException("No selective enforcement for " + permission);
16774        }
16775    }
16776
16777    @Override
16778    @Deprecated
16779    public boolean isPermissionEnforced(String permission) {
16780        return true;
16781    }
16782
16783    @Override
16784    public boolean isStorageLow() {
16785        final long token = Binder.clearCallingIdentity();
16786        try {
16787            final DeviceStorageMonitorInternal
16788                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16789            if (dsm != null) {
16790                return dsm.isMemoryLow();
16791            } else {
16792                return false;
16793            }
16794        } finally {
16795            Binder.restoreCallingIdentity(token);
16796        }
16797    }
16798
16799    @Override
16800    public IPackageInstaller getPackageInstaller() {
16801        return mInstallerService;
16802    }
16803
16804    private boolean userNeedsBadging(int userId) {
16805        int index = mUserNeedsBadging.indexOfKey(userId);
16806        if (index < 0) {
16807            final UserInfo userInfo;
16808            final long token = Binder.clearCallingIdentity();
16809            try {
16810                userInfo = sUserManager.getUserInfo(userId);
16811            } finally {
16812                Binder.restoreCallingIdentity(token);
16813            }
16814            final boolean b;
16815            if (userInfo != null && userInfo.isManagedProfile()) {
16816                b = true;
16817            } else {
16818                b = false;
16819            }
16820            mUserNeedsBadging.put(userId, b);
16821            return b;
16822        }
16823        return mUserNeedsBadging.valueAt(index);
16824    }
16825
16826    @Override
16827    public KeySet getKeySetByAlias(String packageName, String alias) {
16828        if (packageName == null || alias == null) {
16829            return null;
16830        }
16831        synchronized(mPackages) {
16832            final PackageParser.Package pkg = mPackages.get(packageName);
16833            if (pkg == null) {
16834                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16835                throw new IllegalArgumentException("Unknown package: " + packageName);
16836            }
16837            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16838            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16839        }
16840    }
16841
16842    @Override
16843    public KeySet getSigningKeySet(String packageName) {
16844        if (packageName == null) {
16845            return null;
16846        }
16847        synchronized(mPackages) {
16848            final PackageParser.Package pkg = mPackages.get(packageName);
16849            if (pkg == null) {
16850                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16851                throw new IllegalArgumentException("Unknown package: " + packageName);
16852            }
16853            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16854                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16855                throw new SecurityException("May not access signing KeySet of other apps.");
16856            }
16857            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16858            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16859        }
16860    }
16861
16862    @Override
16863    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16864        if (packageName == null || ks == null) {
16865            return false;
16866        }
16867        synchronized(mPackages) {
16868            final PackageParser.Package pkg = mPackages.get(packageName);
16869            if (pkg == null) {
16870                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16871                throw new IllegalArgumentException("Unknown package: " + packageName);
16872            }
16873            IBinder ksh = ks.getToken();
16874            if (ksh instanceof KeySetHandle) {
16875                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16876                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16877            }
16878            return false;
16879        }
16880    }
16881
16882    @Override
16883    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16884        if (packageName == null || ks == null) {
16885            return false;
16886        }
16887        synchronized(mPackages) {
16888            final PackageParser.Package pkg = mPackages.get(packageName);
16889            if (pkg == null) {
16890                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16891                throw new IllegalArgumentException("Unknown package: " + packageName);
16892            }
16893            IBinder ksh = ks.getToken();
16894            if (ksh instanceof KeySetHandle) {
16895                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16896                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16897            }
16898            return false;
16899        }
16900    }
16901
16902    /**
16903     * Check and throw if the given before/after packages would be considered a
16904     * downgrade.
16905     */
16906    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16907            throws PackageManagerException {
16908        if (after.versionCode < before.mVersionCode) {
16909            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16910                    "Update version code " + after.versionCode + " is older than current "
16911                    + before.mVersionCode);
16912        } else if (after.versionCode == before.mVersionCode) {
16913            if (after.baseRevisionCode < before.baseRevisionCode) {
16914                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16915                        "Update base revision code " + after.baseRevisionCode
16916                        + " is older than current " + before.baseRevisionCode);
16917            }
16918
16919            if (!ArrayUtils.isEmpty(after.splitNames)) {
16920                for (int i = 0; i < after.splitNames.length; i++) {
16921                    final String splitName = after.splitNames[i];
16922                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16923                    if (j != -1) {
16924                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16925                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16926                                    "Update split " + splitName + " revision code "
16927                                    + after.splitRevisionCodes[i] + " is older than current "
16928                                    + before.splitRevisionCodes[j]);
16929                        }
16930                    }
16931                }
16932            }
16933        }
16934    }
16935
16936    private static class MoveCallbacks extends Handler {
16937        private static final int MSG_CREATED = 1;
16938        private static final int MSG_STATUS_CHANGED = 2;
16939
16940        private final RemoteCallbackList<IPackageMoveObserver>
16941                mCallbacks = new RemoteCallbackList<>();
16942
16943        private final SparseIntArray mLastStatus = new SparseIntArray();
16944
16945        public MoveCallbacks(Looper looper) {
16946            super(looper);
16947        }
16948
16949        public void register(IPackageMoveObserver callback) {
16950            mCallbacks.register(callback);
16951        }
16952
16953        public void unregister(IPackageMoveObserver callback) {
16954            mCallbacks.unregister(callback);
16955        }
16956
16957        @Override
16958        public void handleMessage(Message msg) {
16959            final SomeArgs args = (SomeArgs) msg.obj;
16960            final int n = mCallbacks.beginBroadcast();
16961            for (int i = 0; i < n; i++) {
16962                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16963                try {
16964                    invokeCallback(callback, msg.what, args);
16965                } catch (RemoteException ignored) {
16966                }
16967            }
16968            mCallbacks.finishBroadcast();
16969            args.recycle();
16970        }
16971
16972        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16973                throws RemoteException {
16974            switch (what) {
16975                case MSG_CREATED: {
16976                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16977                    break;
16978                }
16979                case MSG_STATUS_CHANGED: {
16980                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16981                    break;
16982                }
16983            }
16984        }
16985
16986        private void notifyCreated(int moveId, Bundle extras) {
16987            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16988
16989            final SomeArgs args = SomeArgs.obtain();
16990            args.argi1 = moveId;
16991            args.arg2 = extras;
16992            obtainMessage(MSG_CREATED, args).sendToTarget();
16993        }
16994
16995        private void notifyStatusChanged(int moveId, int status) {
16996            notifyStatusChanged(moveId, status, -1);
16997        }
16998
16999        private void notifyStatusChanged(int moveId, int status, long estMillis) {
17000            Slog.v(TAG, "Move " + moveId + " status " + status);
17001
17002            final SomeArgs args = SomeArgs.obtain();
17003            args.argi1 = moveId;
17004            args.argi2 = status;
17005            args.arg3 = estMillis;
17006            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
17007
17008            synchronized (mLastStatus) {
17009                mLastStatus.put(moveId, status);
17010            }
17011        }
17012    }
17013
17014    private final class OnPermissionChangeListeners extends Handler {
17015        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
17016
17017        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
17018                new RemoteCallbackList<>();
17019
17020        public OnPermissionChangeListeners(Looper looper) {
17021            super(looper);
17022        }
17023
17024        @Override
17025        public void handleMessage(Message msg) {
17026            switch (msg.what) {
17027                case MSG_ON_PERMISSIONS_CHANGED: {
17028                    final int uid = msg.arg1;
17029                    handleOnPermissionsChanged(uid);
17030                } break;
17031            }
17032        }
17033
17034        public void addListenerLocked(IOnPermissionsChangeListener listener) {
17035            mPermissionListeners.register(listener);
17036
17037        }
17038
17039        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
17040            mPermissionListeners.unregister(listener);
17041        }
17042
17043        public void onPermissionsChanged(int uid) {
17044            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
17045                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
17046            }
17047        }
17048
17049        private void handleOnPermissionsChanged(int uid) {
17050            final int count = mPermissionListeners.beginBroadcast();
17051            try {
17052                for (int i = 0; i < count; i++) {
17053                    IOnPermissionsChangeListener callback = mPermissionListeners
17054                            .getBroadcastItem(i);
17055                    try {
17056                        callback.onPermissionsChanged(uid);
17057                    } catch (RemoteException e) {
17058                        Log.e(TAG, "Permission listener is dead", e);
17059                    }
17060                }
17061            } finally {
17062                mPermissionListeners.finishBroadcast();
17063            }
17064        }
17065    }
17066
17067    private class PackageManagerInternalImpl extends PackageManagerInternal {
17068        @Override
17069        public void setLocationPackagesProvider(PackagesProvider provider) {
17070            synchronized (mPackages) {
17071                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
17072            }
17073        }
17074
17075        @Override
17076        public void setImePackagesProvider(PackagesProvider provider) {
17077            synchronized (mPackages) {
17078                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
17079            }
17080        }
17081
17082        @Override
17083        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
17084            synchronized (mPackages) {
17085                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
17086            }
17087        }
17088
17089        @Override
17090        public void setSmsAppPackagesProvider(PackagesProvider provider) {
17091            synchronized (mPackages) {
17092                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
17093            }
17094        }
17095
17096        @Override
17097        public void setDialerAppPackagesProvider(PackagesProvider provider) {
17098            synchronized (mPackages) {
17099                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
17100            }
17101        }
17102
17103        @Override
17104        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
17105            synchronized (mPackages) {
17106                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
17107            }
17108        }
17109
17110        @Override
17111        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
17112            synchronized (mPackages) {
17113                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
17114            }
17115        }
17116
17117        @Override
17118        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
17119            synchronized (mPackages) {
17120                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
17121                        packageName, userId);
17122            }
17123        }
17124
17125        @Override
17126        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
17127            synchronized (mPackages) {
17128                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
17129                        packageName, userId);
17130            }
17131        }
17132        @Override
17133        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
17134            synchronized (mPackages) {
17135                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
17136                        packageName, userId);
17137            }
17138        }
17139    }
17140
17141    @Override
17142    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
17143        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
17144        synchronized (mPackages) {
17145            final long identity = Binder.clearCallingIdentity();
17146            try {
17147                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
17148                        packageNames, userId);
17149            } finally {
17150                Binder.restoreCallingIdentity(identity);
17151            }
17152        }
17153    }
17154
17155    private static void enforceSystemOrPhoneCaller(String tag) {
17156        int callingUid = Binder.getCallingUid();
17157        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
17158            throw new SecurityException(
17159                    "Cannot call " + tag + " from UID " + callingUid);
17160        }
17161    }
17162}
17163