PackageManagerService.java revision 11c5b0aff7a742e21bd701ad04572dcf7e0f9332
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.IMediaContainerService;
213import com.android.internal.app.ResolverActivity;
214import com.android.internal.content.NativeLibraryHelper;
215import com.android.internal.content.PackageHelper;
216import com.android.internal.os.IParcelFileDescriptorFactory;
217import com.android.internal.os.SomeArgs;
218import com.android.internal.os.Zygote;
219import com.android.internal.util.ArrayUtils;
220import com.android.internal.util.FastPrintWriter;
221import com.android.internal.util.FastXmlSerializer;
222import com.android.internal.util.IndentingPrintWriter;
223import com.android.internal.util.Preconditions;
224import com.android.server.EventLogTags;
225import com.android.server.FgThread;
226import com.android.server.IntentResolver;
227import com.android.server.LocalServices;
228import com.android.server.ServiceThread;
229import com.android.server.SystemConfig;
230import com.android.server.Watchdog;
231import com.android.server.pm.PermissionsState.PermissionState;
232import com.android.server.pm.Settings.DatabaseVersion;
233import com.android.server.pm.Settings.VersionInfo;
234import com.android.server.storage.DeviceStorageMonitorInternal;
235
236import org.xmlpull.v1.XmlPullParser;
237import org.xmlpull.v1.XmlPullParserException;
238import org.xmlpull.v1.XmlSerializer;
239
240import java.io.BufferedInputStream;
241import java.io.BufferedOutputStream;
242import java.io.BufferedReader;
243import java.io.ByteArrayInputStream;
244import java.io.ByteArrayOutputStream;
245import java.io.File;
246import java.io.FileDescriptor;
247import java.io.FileNotFoundException;
248import java.io.FileOutputStream;
249import java.io.FileReader;
250import java.io.FilenameFilter;
251import java.io.IOException;
252import java.io.InputStream;
253import java.io.PrintWriter;
254import java.nio.charset.StandardCharsets;
255import java.security.NoSuchAlgorithmException;
256import java.security.PublicKey;
257import java.security.cert.CertificateEncodingException;
258import java.security.cert.CertificateException;
259import java.text.SimpleDateFormat;
260import java.util.ArrayList;
261import java.util.Arrays;
262import java.util.Collection;
263import java.util.Collections;
264import java.util.Comparator;
265import java.util.Date;
266import java.util.Iterator;
267import java.util.List;
268import java.util.Map;
269import java.util.Objects;
270import java.util.Set;
271import java.util.concurrent.CountDownLatch;
272import java.util.concurrent.TimeUnit;
273import java.util.concurrent.atomic.AtomicBoolean;
274import java.util.concurrent.atomic.AtomicInteger;
275import java.util.concurrent.atomic.AtomicLong;
276
277/**
278 * Keep track of all those .apks everywhere.
279 *
280 * This is very central to the platform's security; please run the unit
281 * tests whenever making modifications here:
282 *
283runtest -c android.content.pm.PackageManagerTests frameworks-core
284 *
285 * {@hide}
286 */
287public class PackageManagerService extends IPackageManager.Stub {
288    static final String TAG = "PackageManager";
289    static final boolean DEBUG_SETTINGS = false;
290    static final boolean DEBUG_PREFERRED = false;
291    static final boolean DEBUG_UPGRADE = false;
292    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
293    private static final boolean DEBUG_BACKUP = false;
294    private static final boolean DEBUG_INSTALL = false;
295    private static final boolean DEBUG_REMOVE = false;
296    private static final boolean DEBUG_BROADCASTS = false;
297    private static final boolean DEBUG_SHOW_INFO = false;
298    private static final boolean DEBUG_PACKAGE_INFO = false;
299    private static final boolean DEBUG_INTENT_MATCHING = false;
300    private static final boolean DEBUG_PACKAGE_SCANNING = false;
301    private static final boolean DEBUG_VERIFY = false;
302    private static final boolean DEBUG_DEXOPT = false;
303    private static final boolean DEBUG_ABI_SELECTION = false;
304
305    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
306
307    private static final int RADIO_UID = Process.PHONE_UID;
308    private static final int LOG_UID = Process.LOG_UID;
309    private static final int NFC_UID = Process.NFC_UID;
310    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
311    private static final int SHELL_UID = Process.SHELL_UID;
312
313    // Cap the size of permission trees that 3rd party apps can define
314    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
315
316    // Suffix used during package installation when copying/moving
317    // package apks to install directory.
318    private static final String INSTALL_PACKAGE_SUFFIX = "-";
319
320    static final int SCAN_NO_DEX = 1<<1;
321    static final int SCAN_FORCE_DEX = 1<<2;
322    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
323    static final int SCAN_NEW_INSTALL = 1<<4;
324    static final int SCAN_NO_PATHS = 1<<5;
325    static final int SCAN_UPDATE_TIME = 1<<6;
326    static final int SCAN_DEFER_DEX = 1<<7;
327    static final int SCAN_BOOTING = 1<<8;
328    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
329    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
330    static final int SCAN_REPLACING = 1<<11;
331    static final int SCAN_REQUIRE_KNOWN = 1<<12;
332    static final int SCAN_MOVE = 1<<13;
333    static final int SCAN_INITIAL = 1<<14;
334
335    static final int REMOVE_CHATTY = 1<<16;
336
337    private static final int[] EMPTY_INT_ARRAY = new int[0];
338
339    /**
340     * Timeout (in milliseconds) after which the watchdog should declare that
341     * our handler thread is wedged.  The usual default for such things is one
342     * minute but we sometimes do very lengthy I/O operations on this thread,
343     * such as installing multi-gigabyte applications, so ours needs to be longer.
344     */
345    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
346
347    /**
348     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
349     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
350     * settings entry if available, otherwise we use the hardcoded default.  If it's been
351     * more than this long since the last fstrim, we force one during the boot sequence.
352     *
353     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
354     * one gets run at the next available charging+idle time.  This final mandatory
355     * no-fstrim check kicks in only of the other scheduling criteria is never met.
356     */
357    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
358
359    /**
360     * Whether verification is enabled by default.
361     */
362    private static final boolean DEFAULT_VERIFY_ENABLE = true;
363
364    /**
365     * The default maximum time to wait for the verification agent to return in
366     * milliseconds.
367     */
368    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
369
370    /**
371     * The default response for package verification timeout.
372     *
373     * This can be either PackageManager.VERIFICATION_ALLOW or
374     * PackageManager.VERIFICATION_REJECT.
375     */
376    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
377
378    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
379
380    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
381            DEFAULT_CONTAINER_PACKAGE,
382            "com.android.defcontainer.DefaultContainerService");
383
384    private static final String KILL_APP_REASON_GIDS_CHANGED =
385            "permission grant or revoke changed gids";
386
387    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
388            "permissions revoked";
389
390    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
391
392    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
393
394    /** Permission grant: not grant the permission. */
395    private static final int GRANT_DENIED = 1;
396
397    /** Permission grant: grant the permission as an install permission. */
398    private static final int GRANT_INSTALL = 2;
399
400    /** Permission grant: grant the permission as an install permission for a legacy app. */
401    private static final int GRANT_INSTALL_LEGACY = 3;
402
403    /** Permission grant: grant the permission as a runtime one. */
404    private static final int GRANT_RUNTIME = 4;
405
406    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
407    private static final int GRANT_UPGRADE = 5;
408
409    /** Canonical intent used to identify what counts as a "web browser" app */
410    private static final Intent sBrowserIntent;
411    static {
412        sBrowserIntent = new Intent();
413        sBrowserIntent.setAction(Intent.ACTION_VIEW);
414        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
415        sBrowserIntent.setData(Uri.parse("http:"));
416    }
417
418    final ServiceThread mHandlerThread;
419
420    final PackageHandler mHandler;
421
422    /**
423     * Messages for {@link #mHandler} that need to wait for system ready before
424     * being dispatched.
425     */
426    private ArrayList<Message> mPostSystemReadyMessages;
427
428    final int mSdkVersion = Build.VERSION.SDK_INT;
429
430    final Context mContext;
431    final boolean mFactoryTest;
432    final boolean mOnlyCore;
433    final DisplayMetrics mMetrics;
434    final int mDefParseFlags;
435    final String[] mSeparateProcesses;
436    final boolean mIsUpgrade;
437
438    // This is where all application persistent data goes.
439    final File mAppDataDir;
440
441    // This is where all application persistent data goes for secondary users.
442    final File mUserAppDataDir;
443
444    /** The location for ASEC container files on internal storage. */
445    final String mAsecInternalPath;
446
447    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
448    // LOCK HELD.  Can be called with mInstallLock held.
449    @GuardedBy("mInstallLock")
450    final Installer mInstaller;
451
452    /** Directory where installed third-party apps stored */
453    final File mAppInstallDir;
454
455    /**
456     * Directory to which applications installed internally have their
457     * 32 bit native libraries copied.
458     */
459    private File mAppLib32InstallDir;
460
461    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
462    // apps.
463    final File mDrmAppPrivateInstallDir;
464
465    // ----------------------------------------------------------------
466
467    // Lock for state used when installing and doing other long running
468    // operations.  Methods that must be called with this lock held have
469    // the suffix "LI".
470    final Object mInstallLock = new Object();
471
472    // ----------------------------------------------------------------
473
474    // Keys are String (package name), values are Package.  This also serves
475    // as the lock for the global state.  Methods that must be called with
476    // this lock held have the prefix "LP".
477    @GuardedBy("mPackages")
478    final ArrayMap<String, PackageParser.Package> mPackages =
479            new ArrayMap<String, PackageParser.Package>();
480
481    // Tracks available target package names -> overlay package paths.
482    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
483        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
484
485    /**
486     * Tracks new system packages [received in an OTA] that we expect to
487     * find updated user-installed versions. Keys are package name, values
488     * are package location.
489     */
490    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
491
492    /**
493     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
494     */
495    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
496    /**
497     * Whether or not system app permissions should be promoted from install to runtime.
498     */
499    boolean mPromoteSystemApps;
500
501    final Settings mSettings;
502    boolean mRestoredSettings;
503
504    // System configuration read by SystemConfig.
505    final int[] mGlobalGids;
506    final SparseArray<ArraySet<String>> mSystemPermissions;
507    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
508
509    // If mac_permissions.xml was found for seinfo labeling.
510    boolean mFoundPolicyFile;
511
512    // If a recursive restorecon of /data/data/<pkg> is needed.
513    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
514
515    public static final class SharedLibraryEntry {
516        public final String path;
517        public final String apk;
518
519        SharedLibraryEntry(String _path, String _apk) {
520            path = _path;
521            apk = _apk;
522        }
523    }
524
525    // Currently known shared libraries.
526    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
527            new ArrayMap<String, SharedLibraryEntry>();
528
529    // All available activities, for your resolving pleasure.
530    final ActivityIntentResolver mActivities =
531            new ActivityIntentResolver();
532
533    // All available receivers, for your resolving pleasure.
534    final ActivityIntentResolver mReceivers =
535            new ActivityIntentResolver();
536
537    // All available services, for your resolving pleasure.
538    final ServiceIntentResolver mServices = new ServiceIntentResolver();
539
540    // All available providers, for your resolving pleasure.
541    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
542
543    // Mapping from provider base names (first directory in content URI codePath)
544    // to the provider information.
545    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
546            new ArrayMap<String, PackageParser.Provider>();
547
548    // Mapping from instrumentation class names to info about them.
549    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
550            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
551
552    // Mapping from permission names to info about them.
553    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
554            new ArrayMap<String, PackageParser.PermissionGroup>();
555
556    // Packages whose data we have transfered into another package, thus
557    // should no longer exist.
558    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
559
560    // Broadcast actions that are only available to the system.
561    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
562
563    /** List of packages waiting for verification. */
564    final SparseArray<PackageVerificationState> mPendingVerification
565            = new SparseArray<PackageVerificationState>();
566
567    /** Set of packages associated with each app op permission. */
568    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
569
570    final PackageInstallerService mInstallerService;
571
572    private final PackageDexOptimizer mPackageDexOptimizer;
573
574    private AtomicInteger mNextMoveId = new AtomicInteger();
575    private final MoveCallbacks mMoveCallbacks;
576
577    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
578
579    // Cache of users who need badging.
580    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
581
582    /** Token for keys in mPendingVerification. */
583    private int mPendingVerificationToken = 0;
584
585    volatile boolean mSystemReady;
586    volatile boolean mSafeMode;
587    volatile boolean mHasSystemUidErrors;
588
589    ApplicationInfo mAndroidApplication;
590    final ActivityInfo mResolveActivity = new ActivityInfo();
591    final ResolveInfo mResolveInfo = new ResolveInfo();
592    ComponentName mResolveComponentName;
593    PackageParser.Package mPlatformPackage;
594    ComponentName mCustomResolverComponentName;
595
596    boolean mResolverReplaced = false;
597
598    private final ComponentName mIntentFilterVerifierComponent;
599    private int mIntentFilterVerificationToken = 0;
600
601    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
602            = new SparseArray<IntentFilterVerificationState>();
603
604    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
605            new DefaultPermissionGrantPolicy(this);
606
607    private static class IFVerificationParams {
608        PackageParser.Package pkg;
609        boolean replacing;
610        int userId;
611        int verifierUid;
612
613        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
614                int _userId, int _verifierUid) {
615            pkg = _pkg;
616            replacing = _replacing;
617            userId = _userId;
618            replacing = _replacing;
619            verifierUid = _verifierUid;
620        }
621    }
622
623    private interface IntentFilterVerifier<T extends IntentFilter> {
624        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
625                                               T filter, String packageName);
626        void startVerifications(int userId);
627        void receiveVerificationResponse(int verificationId);
628    }
629
630    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
631        private Context mContext;
632        private ComponentName mIntentFilterVerifierComponent;
633        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
634
635        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
636            mContext = context;
637            mIntentFilterVerifierComponent = verifierComponent;
638        }
639
640        private String getDefaultScheme() {
641            return IntentFilter.SCHEME_HTTPS;
642        }
643
644        @Override
645        public void startVerifications(int userId) {
646            // Launch verifications requests
647            int count = mCurrentIntentFilterVerifications.size();
648            for (int n=0; n<count; n++) {
649                int verificationId = mCurrentIntentFilterVerifications.get(n);
650                final IntentFilterVerificationState ivs =
651                        mIntentFilterVerificationStates.get(verificationId);
652
653                String packageName = ivs.getPackageName();
654
655                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
656                final int filterCount = filters.size();
657                ArraySet<String> domainsSet = new ArraySet<>();
658                for (int m=0; m<filterCount; m++) {
659                    PackageParser.ActivityIntentInfo filter = filters.get(m);
660                    domainsSet.addAll(filter.getHostsList());
661                }
662                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
663                synchronized (mPackages) {
664                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
665                            packageName, domainsList) != null) {
666                        scheduleWriteSettingsLocked();
667                    }
668                }
669                sendVerificationRequest(userId, verificationId, ivs);
670            }
671            mCurrentIntentFilterVerifications.clear();
672        }
673
674        private void sendVerificationRequest(int userId, int verificationId,
675                IntentFilterVerificationState ivs) {
676
677            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
678            verificationIntent.putExtra(
679                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
680                    verificationId);
681            verificationIntent.putExtra(
682                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
683                    getDefaultScheme());
684            verificationIntent.putExtra(
685                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
686                    ivs.getHostsString());
687            verificationIntent.putExtra(
688                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
689                    ivs.getPackageName());
690            verificationIntent.setComponent(mIntentFilterVerifierComponent);
691            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
692
693            UserHandle user = new UserHandle(userId);
694            mContext.sendBroadcastAsUser(verificationIntent, user);
695            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
696                    "Sending IntentFilter verification broadcast");
697        }
698
699        public void receiveVerificationResponse(int verificationId) {
700            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
701
702            final boolean verified = ivs.isVerified();
703
704            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
705            final int count = filters.size();
706            if (DEBUG_DOMAIN_VERIFICATION) {
707                Slog.i(TAG, "Received verification response " + verificationId
708                        + " for " + count + " filters, verified=" + verified);
709            }
710            for (int n=0; n<count; n++) {
711                PackageParser.ActivityIntentInfo filter = filters.get(n);
712                filter.setVerified(verified);
713
714                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
715                        + " verified with result:" + verified + " and hosts:"
716                        + ivs.getHostsString());
717            }
718
719            mIntentFilterVerificationStates.remove(verificationId);
720
721            final String packageName = ivs.getPackageName();
722            IntentFilterVerificationInfo ivi = null;
723
724            synchronized (mPackages) {
725                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
726            }
727            if (ivi == null) {
728                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
729                        + verificationId + " packageName:" + packageName);
730                return;
731            }
732            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
733                    "Updating IntentFilterVerificationInfo for package " + packageName
734                            +" verificationId:" + verificationId);
735
736            synchronized (mPackages) {
737                if (verified) {
738                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
739                } else {
740                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
741                }
742                scheduleWriteSettingsLocked();
743
744                final int userId = ivs.getUserId();
745                if (userId != UserHandle.USER_ALL) {
746                    final int userStatus =
747                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
748
749                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
750                    boolean needUpdate = false;
751
752                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
753                    // already been set by the User thru the Disambiguation dialog
754                    switch (userStatus) {
755                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
756                            if (verified) {
757                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
758                            } else {
759                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
760                            }
761                            needUpdate = true;
762                            break;
763
764                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
765                            if (verified) {
766                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
767                                needUpdate = true;
768                            }
769                            break;
770
771                        default:
772                            // Nothing to do
773                    }
774
775                    if (needUpdate) {
776                        mSettings.updateIntentFilterVerificationStatusLPw(
777                                packageName, updatedStatus, userId);
778                        scheduleWritePackageRestrictionsLocked(userId);
779                    }
780                }
781            }
782        }
783
784        @Override
785        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
786                    ActivityIntentInfo filter, String packageName) {
787            if (!hasValidDomains(filter)) {
788                return false;
789            }
790            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
791            if (ivs == null) {
792                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
793                        packageName);
794            }
795            if (DEBUG_DOMAIN_VERIFICATION) {
796                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
797            }
798            ivs.addFilter(filter);
799            return true;
800        }
801
802        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
803                int userId, int verificationId, String packageName) {
804            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
805                    verifierUid, userId, packageName);
806            ivs.setPendingState();
807            synchronized (mPackages) {
808                mIntentFilterVerificationStates.append(verificationId, ivs);
809                mCurrentIntentFilterVerifications.add(verificationId);
810            }
811            return ivs;
812        }
813    }
814
815    private static boolean hasValidDomains(ActivityIntentInfo filter) {
816        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
817                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
818                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
819    }
820
821    private IntentFilterVerifier mIntentFilterVerifier;
822
823    // Set of pending broadcasts for aggregating enable/disable of components.
824    static class PendingPackageBroadcasts {
825        // for each user id, a map of <package name -> components within that package>
826        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
827
828        public PendingPackageBroadcasts() {
829            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
830        }
831
832        public ArrayList<String> get(int userId, String packageName) {
833            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
834            return packages.get(packageName);
835        }
836
837        public void put(int userId, String packageName, ArrayList<String> components) {
838            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
839            packages.put(packageName, components);
840        }
841
842        public void remove(int userId, String packageName) {
843            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
844            if (packages != null) {
845                packages.remove(packageName);
846            }
847        }
848
849        public void remove(int userId) {
850            mUidMap.remove(userId);
851        }
852
853        public int userIdCount() {
854            return mUidMap.size();
855        }
856
857        public int userIdAt(int n) {
858            return mUidMap.keyAt(n);
859        }
860
861        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
862            return mUidMap.get(userId);
863        }
864
865        public int size() {
866            // total number of pending broadcast entries across all userIds
867            int num = 0;
868            for (int i = 0; i< mUidMap.size(); i++) {
869                num += mUidMap.valueAt(i).size();
870            }
871            return num;
872        }
873
874        public void clear() {
875            mUidMap.clear();
876        }
877
878        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
879            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
880            if (map == null) {
881                map = new ArrayMap<String, ArrayList<String>>();
882                mUidMap.put(userId, map);
883            }
884            return map;
885        }
886    }
887    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
888
889    // Service Connection to remote media container service to copy
890    // package uri's from external media onto secure containers
891    // or internal storage.
892    private IMediaContainerService mContainerService = null;
893
894    static final int SEND_PENDING_BROADCAST = 1;
895    static final int MCS_BOUND = 3;
896    static final int END_COPY = 4;
897    static final int INIT_COPY = 5;
898    static final int MCS_UNBIND = 6;
899    static final int START_CLEANING_PACKAGE = 7;
900    static final int FIND_INSTALL_LOC = 8;
901    static final int POST_INSTALL = 9;
902    static final int MCS_RECONNECT = 10;
903    static final int MCS_GIVE_UP = 11;
904    static final int UPDATED_MEDIA_STATUS = 12;
905    static final int WRITE_SETTINGS = 13;
906    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
907    static final int PACKAGE_VERIFIED = 15;
908    static final int CHECK_PENDING_VERIFICATION = 16;
909    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
910    static final int INTENT_FILTER_VERIFIED = 18;
911
912    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
913
914    // Delay time in millisecs
915    static final int BROADCAST_DELAY = 10 * 1000;
916
917    static UserManagerService sUserManager;
918
919    // Stores a list of users whose package restrictions file needs to be updated
920    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
921
922    final private DefaultContainerConnection mDefContainerConn =
923            new DefaultContainerConnection();
924    class DefaultContainerConnection implements ServiceConnection {
925        public void onServiceConnected(ComponentName name, IBinder service) {
926            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
927            IMediaContainerService imcs =
928                IMediaContainerService.Stub.asInterface(service);
929            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
930        }
931
932        public void onServiceDisconnected(ComponentName name) {
933            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
934        }
935    }
936
937    // Recordkeeping of restore-after-install operations that are currently in flight
938    // between the Package Manager and the Backup Manager
939    class PostInstallData {
940        public InstallArgs args;
941        public PackageInstalledInfo res;
942
943        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
944            args = _a;
945            res = _r;
946        }
947    }
948
949    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
950    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
951
952    // XML tags for backup/restore of various bits of state
953    private static final String TAG_PREFERRED_BACKUP = "pa";
954    private static final String TAG_DEFAULT_APPS = "da";
955    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
956
957    final String mRequiredVerifierPackage;
958    final String mRequiredInstallerPackage;
959
960    private final PackageUsage mPackageUsage = new PackageUsage();
961
962    private class PackageUsage {
963        private static final int WRITE_INTERVAL
964            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
965
966        private final Object mFileLock = new Object();
967        private final AtomicLong mLastWritten = new AtomicLong(0);
968        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
969
970        private boolean mIsHistoricalPackageUsageAvailable = true;
971
972        boolean isHistoricalPackageUsageAvailable() {
973            return mIsHistoricalPackageUsageAvailable;
974        }
975
976        void write(boolean force) {
977            if (force) {
978                writeInternal();
979                return;
980            }
981            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
982                && !DEBUG_DEXOPT) {
983                return;
984            }
985            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
986                new Thread("PackageUsage_DiskWriter") {
987                    @Override
988                    public void run() {
989                        try {
990                            writeInternal();
991                        } finally {
992                            mBackgroundWriteRunning.set(false);
993                        }
994                    }
995                }.start();
996            }
997        }
998
999        private void writeInternal() {
1000            synchronized (mPackages) {
1001                synchronized (mFileLock) {
1002                    AtomicFile file = getFile();
1003                    FileOutputStream f = null;
1004                    try {
1005                        f = file.startWrite();
1006                        BufferedOutputStream out = new BufferedOutputStream(f);
1007                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1008                        StringBuilder sb = new StringBuilder();
1009                        for (PackageParser.Package pkg : mPackages.values()) {
1010                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1011                                continue;
1012                            }
1013                            sb.setLength(0);
1014                            sb.append(pkg.packageName);
1015                            sb.append(' ');
1016                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1017                            sb.append('\n');
1018                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1019                        }
1020                        out.flush();
1021                        file.finishWrite(f);
1022                    } catch (IOException e) {
1023                        if (f != null) {
1024                            file.failWrite(f);
1025                        }
1026                        Log.e(TAG, "Failed to write package usage times", e);
1027                    }
1028                }
1029            }
1030            mLastWritten.set(SystemClock.elapsedRealtime());
1031        }
1032
1033        void readLP() {
1034            synchronized (mFileLock) {
1035                AtomicFile file = getFile();
1036                BufferedInputStream in = null;
1037                try {
1038                    in = new BufferedInputStream(file.openRead());
1039                    StringBuffer sb = new StringBuffer();
1040                    while (true) {
1041                        String packageName = readToken(in, sb, ' ');
1042                        if (packageName == null) {
1043                            break;
1044                        }
1045                        String timeInMillisString = readToken(in, sb, '\n');
1046                        if (timeInMillisString == null) {
1047                            throw new IOException("Failed to find last usage time for package "
1048                                                  + packageName);
1049                        }
1050                        PackageParser.Package pkg = mPackages.get(packageName);
1051                        if (pkg == null) {
1052                            continue;
1053                        }
1054                        long timeInMillis;
1055                        try {
1056                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1057                        } catch (NumberFormatException e) {
1058                            throw new IOException("Failed to parse " + timeInMillisString
1059                                                  + " as a long.", e);
1060                        }
1061                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1062                    }
1063                } catch (FileNotFoundException expected) {
1064                    mIsHistoricalPackageUsageAvailable = false;
1065                } catch (IOException e) {
1066                    Log.w(TAG, "Failed to read package usage times", e);
1067                } finally {
1068                    IoUtils.closeQuietly(in);
1069                }
1070            }
1071            mLastWritten.set(SystemClock.elapsedRealtime());
1072        }
1073
1074        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1075                throws IOException {
1076            sb.setLength(0);
1077            while (true) {
1078                int ch = in.read();
1079                if (ch == -1) {
1080                    if (sb.length() == 0) {
1081                        return null;
1082                    }
1083                    throw new IOException("Unexpected EOF");
1084                }
1085                if (ch == endOfToken) {
1086                    return sb.toString();
1087                }
1088                sb.append((char)ch);
1089            }
1090        }
1091
1092        private AtomicFile getFile() {
1093            File dataDir = Environment.getDataDirectory();
1094            File systemDir = new File(dataDir, "system");
1095            File fname = new File(systemDir, "package-usage.list");
1096            return new AtomicFile(fname);
1097        }
1098    }
1099
1100    class PackageHandler extends Handler {
1101        private boolean mBound = false;
1102        final ArrayList<HandlerParams> mPendingInstalls =
1103            new ArrayList<HandlerParams>();
1104
1105        private boolean connectToService() {
1106            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1107                    " DefaultContainerService");
1108            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1109            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1110            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1111                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1112                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1113                mBound = true;
1114                return true;
1115            }
1116            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1117            return false;
1118        }
1119
1120        private void disconnectService() {
1121            mContainerService = null;
1122            mBound = false;
1123            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1124            mContext.unbindService(mDefContainerConn);
1125            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1126        }
1127
1128        PackageHandler(Looper looper) {
1129            super(looper);
1130        }
1131
1132        public void handleMessage(Message msg) {
1133            try {
1134                doHandleMessage(msg);
1135            } finally {
1136                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1137            }
1138        }
1139
1140        void doHandleMessage(Message msg) {
1141            switch (msg.what) {
1142                case INIT_COPY: {
1143                    HandlerParams params = (HandlerParams) msg.obj;
1144                    int idx = mPendingInstalls.size();
1145                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1146                    // If a bind was already initiated we dont really
1147                    // need to do anything. The pending install
1148                    // will be processed later on.
1149                    if (!mBound) {
1150                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1151                                System.identityHashCode(mHandler));
1152                        // If this is the only one pending we might
1153                        // have to bind to the service again.
1154                        if (!connectToService()) {
1155                            Slog.e(TAG, "Failed to bind to media container service");
1156                            params.serviceError();
1157                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1158                                    System.identityHashCode(mHandler));
1159                            if (params.traceMethod != null) {
1160                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1161                                        params.traceCookie);
1162                            }
1163                            return;
1164                        } else {
1165                            // Once we bind to the service, the first
1166                            // pending request will be processed.
1167                            mPendingInstalls.add(idx, params);
1168                        }
1169                    } else {
1170                        mPendingInstalls.add(idx, params);
1171                        // Already bound to the service. Just make
1172                        // sure we trigger off processing the first request.
1173                        if (idx == 0) {
1174                            mHandler.sendEmptyMessage(MCS_BOUND);
1175                        }
1176                    }
1177                    break;
1178                }
1179                case MCS_BOUND: {
1180                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1181                    if (msg.obj != null) {
1182                        mContainerService = (IMediaContainerService) msg.obj;
1183                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1184                                System.identityHashCode(mHandler));
1185                    }
1186                    if (mContainerService == null) {
1187                        if (!mBound) {
1188                            // Something seriously wrong since we are not bound and we are not
1189                            // waiting for connection. Bail out.
1190                            Slog.e(TAG, "Cannot bind to media container service");
1191                            for (HandlerParams params : mPendingInstalls) {
1192                                // Indicate service bind error
1193                                params.serviceError();
1194                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1195                                        System.identityHashCode(params));
1196                                if (params.traceMethod != null) {
1197                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1198                                            params.traceMethod, params.traceCookie);
1199                                }
1200                                return;
1201                            }
1202                            mPendingInstalls.clear();
1203                        } else {
1204                            Slog.w(TAG, "Waiting to connect to media container service");
1205                        }
1206                    } else if (mPendingInstalls.size() > 0) {
1207                        HandlerParams params = mPendingInstalls.get(0);
1208                        if (params != null) {
1209                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1210                                    System.identityHashCode(params));
1211                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1212                            if (params.startCopy()) {
1213                                // We are done...  look for more work or to
1214                                // go idle.
1215                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1216                                        "Checking for more work or unbind...");
1217                                // Delete pending install
1218                                if (mPendingInstalls.size() > 0) {
1219                                    mPendingInstalls.remove(0);
1220                                }
1221                                if (mPendingInstalls.size() == 0) {
1222                                    if (mBound) {
1223                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1224                                                "Posting delayed MCS_UNBIND");
1225                                        removeMessages(MCS_UNBIND);
1226                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1227                                        // Unbind after a little delay, to avoid
1228                                        // continual thrashing.
1229                                        sendMessageDelayed(ubmsg, 10000);
1230                                    }
1231                                } else {
1232                                    // There are more pending requests in queue.
1233                                    // Just post MCS_BOUND message to trigger processing
1234                                    // of next pending install.
1235                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1236                                            "Posting MCS_BOUND for next work");
1237                                    mHandler.sendEmptyMessage(MCS_BOUND);
1238                                }
1239                            }
1240                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1241                        }
1242                    } else {
1243                        // Should never happen ideally.
1244                        Slog.w(TAG, "Empty queue");
1245                    }
1246                    break;
1247                }
1248                case MCS_RECONNECT: {
1249                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1250                    if (mPendingInstalls.size() > 0) {
1251                        if (mBound) {
1252                            disconnectService();
1253                        }
1254                        if (!connectToService()) {
1255                            Slog.e(TAG, "Failed to bind to media container service");
1256                            for (HandlerParams params : mPendingInstalls) {
1257                                // Indicate service bind error
1258                                params.serviceError();
1259                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1260                                        System.identityHashCode(params));
1261                            }
1262                            mPendingInstalls.clear();
1263                        }
1264                    }
1265                    break;
1266                }
1267                case MCS_UNBIND: {
1268                    // If there is no actual work left, then time to unbind.
1269                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1270
1271                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1272                        if (mBound) {
1273                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1274
1275                            disconnectService();
1276                        }
1277                    } else if (mPendingInstalls.size() > 0) {
1278                        // There are more pending requests in queue.
1279                        // Just post MCS_BOUND message to trigger processing
1280                        // of next pending install.
1281                        mHandler.sendEmptyMessage(MCS_BOUND);
1282                    }
1283
1284                    break;
1285                }
1286                case MCS_GIVE_UP: {
1287                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1288                    HandlerParams params = mPendingInstalls.remove(0);
1289                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1290                            System.identityHashCode(params));
1291                    break;
1292                }
1293                case SEND_PENDING_BROADCAST: {
1294                    String packages[];
1295                    ArrayList<String> components[];
1296                    int size = 0;
1297                    int uids[];
1298                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1299                    synchronized (mPackages) {
1300                        if (mPendingBroadcasts == null) {
1301                            return;
1302                        }
1303                        size = mPendingBroadcasts.size();
1304                        if (size <= 0) {
1305                            // Nothing to be done. Just return
1306                            return;
1307                        }
1308                        packages = new String[size];
1309                        components = new ArrayList[size];
1310                        uids = new int[size];
1311                        int i = 0;  // filling out the above arrays
1312
1313                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1314                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1315                            Iterator<Map.Entry<String, ArrayList<String>>> it
1316                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1317                                            .entrySet().iterator();
1318                            while (it.hasNext() && i < size) {
1319                                Map.Entry<String, ArrayList<String>> ent = it.next();
1320                                packages[i] = ent.getKey();
1321                                components[i] = ent.getValue();
1322                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1323                                uids[i] = (ps != null)
1324                                        ? UserHandle.getUid(packageUserId, ps.appId)
1325                                        : -1;
1326                                i++;
1327                            }
1328                        }
1329                        size = i;
1330                        mPendingBroadcasts.clear();
1331                    }
1332                    // Send broadcasts
1333                    for (int i = 0; i < size; i++) {
1334                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1335                    }
1336                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1337                    break;
1338                }
1339                case START_CLEANING_PACKAGE: {
1340                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1341                    final String packageName = (String)msg.obj;
1342                    final int userId = msg.arg1;
1343                    final boolean andCode = msg.arg2 != 0;
1344                    synchronized (mPackages) {
1345                        if (userId == UserHandle.USER_ALL) {
1346                            int[] users = sUserManager.getUserIds();
1347                            for (int user : users) {
1348                                mSettings.addPackageToCleanLPw(
1349                                        new PackageCleanItem(user, packageName, andCode));
1350                            }
1351                        } else {
1352                            mSettings.addPackageToCleanLPw(
1353                                    new PackageCleanItem(userId, packageName, andCode));
1354                        }
1355                    }
1356                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1357                    startCleaningPackages();
1358                } break;
1359                case POST_INSTALL: {
1360                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1361                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1362                    mRunningInstalls.delete(msg.arg1);
1363                    boolean deleteOld = false;
1364
1365                    if (data != null) {
1366                        InstallArgs args = data.args;
1367                        PackageInstalledInfo res = data.res;
1368
1369                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1370                            final String packageName = res.pkg.applicationInfo.packageName;
1371                            res.removedInfo.sendBroadcast(false, true, false);
1372                            Bundle extras = new Bundle(1);
1373                            extras.putInt(Intent.EXTRA_UID, res.uid);
1374
1375                            // Now that we successfully installed the package, grant runtime
1376                            // permissions if requested before broadcasting the install.
1377                            if ((args.installFlags
1378                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1379                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1380                                        args.installGrantPermissions);
1381                            }
1382
1383                            // Determine the set of users who are adding this
1384                            // package for the first time vs. those who are seeing
1385                            // an update.
1386                            int[] firstUsers;
1387                            int[] updateUsers = new int[0];
1388                            if (res.origUsers == null || res.origUsers.length == 0) {
1389                                firstUsers = res.newUsers;
1390                            } else {
1391                                firstUsers = new int[0];
1392                                for (int i=0; i<res.newUsers.length; i++) {
1393                                    int user = res.newUsers[i];
1394                                    boolean isNew = true;
1395                                    for (int j=0; j<res.origUsers.length; j++) {
1396                                        if (res.origUsers[j] == user) {
1397                                            isNew = false;
1398                                            break;
1399                                        }
1400                                    }
1401                                    if (isNew) {
1402                                        int[] newFirst = new int[firstUsers.length+1];
1403                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1404                                                firstUsers.length);
1405                                        newFirst[firstUsers.length] = user;
1406                                        firstUsers = newFirst;
1407                                    } else {
1408                                        int[] newUpdate = new int[updateUsers.length+1];
1409                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1410                                                updateUsers.length);
1411                                        newUpdate[updateUsers.length] = user;
1412                                        updateUsers = newUpdate;
1413                                    }
1414                                }
1415                            }
1416                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1417                                    packageName, extras, null, null, firstUsers);
1418                            final boolean update = res.removedInfo.removedPackage != null;
1419                            if (update) {
1420                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1421                            }
1422                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1423                                    packageName, extras, null, null, updateUsers);
1424                            if (update) {
1425                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1426                                        packageName, extras, null, null, updateUsers);
1427                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1428                                        null, null, packageName, null, updateUsers);
1429
1430                                // treat asec-hosted packages like removable media on upgrade
1431                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1432                                    if (DEBUG_INSTALL) {
1433                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1434                                                + " is ASEC-hosted -> AVAILABLE");
1435                                    }
1436                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1437                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1438                                    pkgList.add(packageName);
1439                                    sendResourcesChangedBroadcast(true, true,
1440                                            pkgList,uidArray, null);
1441                                }
1442                            }
1443                            if (res.removedInfo.args != null) {
1444                                // Remove the replaced package's older resources safely now
1445                                deleteOld = true;
1446                            }
1447
1448                            // If this app is a browser and it's newly-installed for some
1449                            // users, clear any default-browser state in those users
1450                            if (firstUsers.length > 0) {
1451                                // the app's nature doesn't depend on the user, so we can just
1452                                // check its browser nature in any user and generalize.
1453                                if (packageIsBrowser(packageName, firstUsers[0])) {
1454                                    synchronized (mPackages) {
1455                                        for (int userId : firstUsers) {
1456                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1457                                        }
1458                                    }
1459                                }
1460                            }
1461                            // Log current value of "unknown sources" setting
1462                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1463                                getUnknownSourcesSettings());
1464                        }
1465                        // Force a gc to clear up things
1466                        Runtime.getRuntime().gc();
1467                        // We delete after a gc for applications  on sdcard.
1468                        if (deleteOld) {
1469                            synchronized (mInstallLock) {
1470                                res.removedInfo.args.doPostDeleteLI(true);
1471                            }
1472                        }
1473                        if (args.observer != null) {
1474                            try {
1475                                Bundle extras = extrasForInstallResult(res);
1476                                args.observer.onPackageInstalled(res.name, res.returnCode,
1477                                        res.returnMsg, extras);
1478                            } catch (RemoteException e) {
1479                                Slog.i(TAG, "Observer no longer exists.");
1480                            }
1481                        }
1482                        if (args.traceMethod != null) {
1483                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1484                                    args.traceCookie);
1485                        }
1486                        return;
1487                    } else {
1488                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1489                    }
1490
1491                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1492                } break;
1493                case UPDATED_MEDIA_STATUS: {
1494                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1495                    boolean reportStatus = msg.arg1 == 1;
1496                    boolean doGc = msg.arg2 == 1;
1497                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1498                    if (doGc) {
1499                        // Force a gc to clear up stale containers.
1500                        Runtime.getRuntime().gc();
1501                    }
1502                    if (msg.obj != null) {
1503                        @SuppressWarnings("unchecked")
1504                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1505                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1506                        // Unload containers
1507                        unloadAllContainers(args);
1508                    }
1509                    if (reportStatus) {
1510                        try {
1511                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1512                            PackageHelper.getMountService().finishMediaUpdate();
1513                        } catch (RemoteException e) {
1514                            Log.e(TAG, "MountService not running?");
1515                        }
1516                    }
1517                } break;
1518                case WRITE_SETTINGS: {
1519                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1520                    synchronized (mPackages) {
1521                        removeMessages(WRITE_SETTINGS);
1522                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1523                        mSettings.writeLPr();
1524                        mDirtyUsers.clear();
1525                    }
1526                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1527                } break;
1528                case WRITE_PACKAGE_RESTRICTIONS: {
1529                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1530                    synchronized (mPackages) {
1531                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1532                        for (int userId : mDirtyUsers) {
1533                            mSettings.writePackageRestrictionsLPr(userId);
1534                        }
1535                        mDirtyUsers.clear();
1536                    }
1537                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1538                } break;
1539                case CHECK_PENDING_VERIFICATION: {
1540                    final int verificationId = msg.arg1;
1541                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1542
1543                    if ((state != null) && !state.timeoutExtended()) {
1544                        final InstallArgs args = state.getInstallArgs();
1545                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1546
1547                        Slog.i(TAG, "Verification timed out for " + originUri);
1548                        mPendingVerification.remove(verificationId);
1549
1550                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1551
1552                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1553                            Slog.i(TAG, "Continuing with installation of " + originUri);
1554                            state.setVerifierResponse(Binder.getCallingUid(),
1555                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1556                            broadcastPackageVerified(verificationId, originUri,
1557                                    PackageManager.VERIFICATION_ALLOW,
1558                                    state.getInstallArgs().getUser());
1559                            try {
1560                                ret = args.copyApk(mContainerService, true);
1561                            } catch (RemoteException e) {
1562                                Slog.e(TAG, "Could not contact the ContainerService");
1563                            }
1564                        } else {
1565                            broadcastPackageVerified(verificationId, originUri,
1566                                    PackageManager.VERIFICATION_REJECT,
1567                                    state.getInstallArgs().getUser());
1568                        }
1569
1570                        Trace.asyncTraceEnd(
1571                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1572
1573                        processPendingInstall(args, ret);
1574                        mHandler.sendEmptyMessage(MCS_UNBIND);
1575                    }
1576                    break;
1577                }
1578                case PACKAGE_VERIFIED: {
1579                    final int verificationId = msg.arg1;
1580
1581                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1582                    if (state == null) {
1583                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1584                        break;
1585                    }
1586
1587                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1588
1589                    state.setVerifierResponse(response.callerUid, response.code);
1590
1591                    if (state.isVerificationComplete()) {
1592                        mPendingVerification.remove(verificationId);
1593
1594                        final InstallArgs args = state.getInstallArgs();
1595                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1596
1597                        int ret;
1598                        if (state.isInstallAllowed()) {
1599                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1600                            broadcastPackageVerified(verificationId, originUri,
1601                                    response.code, state.getInstallArgs().getUser());
1602                            try {
1603                                ret = args.copyApk(mContainerService, true);
1604                            } catch (RemoteException e) {
1605                                Slog.e(TAG, "Could not contact the ContainerService");
1606                            }
1607                        } else {
1608                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1609                        }
1610
1611                        Trace.asyncTraceEnd(
1612                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1613
1614                        processPendingInstall(args, ret);
1615                        mHandler.sendEmptyMessage(MCS_UNBIND);
1616                    }
1617
1618                    break;
1619                }
1620                case START_INTENT_FILTER_VERIFICATIONS: {
1621                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1622                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1623                            params.replacing, params.pkg);
1624                    break;
1625                }
1626                case INTENT_FILTER_VERIFIED: {
1627                    final int verificationId = msg.arg1;
1628
1629                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1630                            verificationId);
1631                    if (state == null) {
1632                        Slog.w(TAG, "Invalid IntentFilter verification token "
1633                                + verificationId + " received");
1634                        break;
1635                    }
1636
1637                    final int userId = state.getUserId();
1638
1639                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1640                            "Processing IntentFilter verification with token:"
1641                            + verificationId + " and userId:" + userId);
1642
1643                    final IntentFilterVerificationResponse response =
1644                            (IntentFilterVerificationResponse) msg.obj;
1645
1646                    state.setVerifierResponse(response.callerUid, response.code);
1647
1648                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1649                            "IntentFilter verification with token:" + verificationId
1650                            + " and userId:" + userId
1651                            + " is settings verifier response with response code:"
1652                            + response.code);
1653
1654                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1655                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1656                                + response.getFailedDomainsString());
1657                    }
1658
1659                    if (state.isVerificationComplete()) {
1660                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1661                    } else {
1662                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1663                                "IntentFilter verification with token:" + verificationId
1664                                + " was not said to be complete");
1665                    }
1666
1667                    break;
1668                }
1669            }
1670        }
1671    }
1672
1673    private StorageEventListener mStorageListener = new StorageEventListener() {
1674        @Override
1675        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1676            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1677                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1678                    final String volumeUuid = vol.getFsUuid();
1679
1680                    // Clean up any users or apps that were removed or recreated
1681                    // while this volume was missing
1682                    reconcileUsers(volumeUuid);
1683                    reconcileApps(volumeUuid);
1684
1685                    // Clean up any install sessions that expired or were
1686                    // cancelled while this volume was missing
1687                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1688
1689                    loadPrivatePackages(vol);
1690
1691                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1692                    unloadPrivatePackages(vol);
1693                }
1694            }
1695
1696            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1697                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1698                    updateExternalMediaStatus(true, false);
1699                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1700                    updateExternalMediaStatus(false, false);
1701                }
1702            }
1703        }
1704
1705        @Override
1706        public void onVolumeForgotten(String fsUuid) {
1707            if (TextUtils.isEmpty(fsUuid)) {
1708                Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1709                return;
1710            }
1711
1712            // Remove any apps installed on the forgotten volume
1713            synchronized (mPackages) {
1714                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1715                for (PackageSetting ps : packages) {
1716                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1717                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1718                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1719                }
1720
1721                mSettings.onVolumeForgotten(fsUuid);
1722                mSettings.writeLPr();
1723            }
1724        }
1725    };
1726
1727    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1728            String[] grantedPermissions) {
1729        if (userId >= UserHandle.USER_SYSTEM) {
1730            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1731        } else if (userId == UserHandle.USER_ALL) {
1732            final int[] userIds;
1733            synchronized (mPackages) {
1734                userIds = UserManagerService.getInstance().getUserIds();
1735            }
1736            for (int someUserId : userIds) {
1737                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1738            }
1739        }
1740
1741        // We could have touched GID membership, so flush out packages.list
1742        synchronized (mPackages) {
1743            mSettings.writePackageListLPr();
1744        }
1745    }
1746
1747    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1748            String[] grantedPermissions) {
1749        SettingBase sb = (SettingBase) pkg.mExtras;
1750        if (sb == null) {
1751            return;
1752        }
1753
1754        PermissionsState permissionsState = sb.getPermissionsState();
1755
1756        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1757                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1758
1759        synchronized (mPackages) {
1760            for (String permission : pkg.requestedPermissions) {
1761                BasePermission bp = mSettings.mPermissions.get(permission);
1762                if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1763                        && (grantedPermissions == null
1764                               || ArrayUtils.contains(grantedPermissions, permission))) {
1765                    final int flags = permissionsState.getPermissionFlags(permission, userId);
1766                    // Installer cannot change immutable permissions.
1767                    if ((flags & immutableFlags) == 0) {
1768                        grantRuntimePermission(pkg.packageName, permission, userId);
1769                    }
1770                }
1771            }
1772        }
1773    }
1774
1775    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1776        Bundle extras = null;
1777        switch (res.returnCode) {
1778            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1779                extras = new Bundle();
1780                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1781                        res.origPermission);
1782                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1783                        res.origPackage);
1784                break;
1785            }
1786            case PackageManager.INSTALL_SUCCEEDED: {
1787                extras = new Bundle();
1788                extras.putBoolean(Intent.EXTRA_REPLACING,
1789                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1790                break;
1791            }
1792        }
1793        return extras;
1794    }
1795
1796    void scheduleWriteSettingsLocked() {
1797        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1798            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1799        }
1800    }
1801
1802    void scheduleWritePackageRestrictionsLocked(int userId) {
1803        if (!sUserManager.exists(userId)) return;
1804        mDirtyUsers.add(userId);
1805        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1806            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1807        }
1808    }
1809
1810    public static PackageManagerService main(Context context, Installer installer,
1811            boolean factoryTest, boolean onlyCore) {
1812        PackageManagerService m = new PackageManagerService(context, installer,
1813                factoryTest, onlyCore);
1814        m.enableSystemUserApps();
1815        ServiceManager.addService("package", m);
1816        return m;
1817    }
1818
1819    private void enableSystemUserApps() {
1820        if (!UserManager.isSplitSystemUser()) {
1821            return;
1822        }
1823        // For system user, enable apps based on the following conditions:
1824        // - app is whitelisted or belong to one of these groups:
1825        //   -- system app which has no launcher icons
1826        //   -- system app which has INTERACT_ACROSS_USERS permission
1827        //   -- system IME app
1828        // - app is not in the blacklist
1829        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1830        Set<String> enableApps = new ArraySet<>();
1831        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
1832                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
1833                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
1834        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
1835        enableApps.addAll(wlApps);
1836        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
1837        enableApps.removeAll(blApps);
1838
1839        List<String> systemApps = queryHelper.queryApps(0, /* systemAppsOnly */ true,
1840                UserHandle.SYSTEM);
1841        final int systemAppsSize = systemApps.size();
1842        synchronized (mPackages) {
1843            for (int i = 0; i < systemAppsSize; i++) {
1844                String pName = systemApps.get(i);
1845                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
1846                // Should not happen, but we shouldn't be failing if it does
1847                if (pkgSetting == null) {
1848                    continue;
1849                }
1850                boolean installed = enableApps.contains(pName);
1851                pkgSetting.setInstalled(installed, UserHandle.USER_SYSTEM);
1852            }
1853        }
1854    }
1855
1856    static String[] splitString(String str, char sep) {
1857        int count = 1;
1858        int i = 0;
1859        while ((i=str.indexOf(sep, i)) >= 0) {
1860            count++;
1861            i++;
1862        }
1863
1864        String[] res = new String[count];
1865        i=0;
1866        count = 0;
1867        int lastI=0;
1868        while ((i=str.indexOf(sep, i)) >= 0) {
1869            res[count] = str.substring(lastI, i);
1870            count++;
1871            i++;
1872            lastI = i;
1873        }
1874        res[count] = str.substring(lastI, str.length());
1875        return res;
1876    }
1877
1878    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1879        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1880                Context.DISPLAY_SERVICE);
1881        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1882    }
1883
1884    public PackageManagerService(Context context, Installer installer,
1885            boolean factoryTest, boolean onlyCore) {
1886        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1887                SystemClock.uptimeMillis());
1888
1889        if (mSdkVersion <= 0) {
1890            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1891        }
1892
1893        mContext = context;
1894        mFactoryTest = factoryTest;
1895        mOnlyCore = onlyCore;
1896        mMetrics = new DisplayMetrics();
1897        mSettings = new Settings(mPackages);
1898        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1899                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1900        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1901                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1902        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1903                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1904        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1905                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1906        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1907                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1908        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1909                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1910
1911        String separateProcesses = SystemProperties.get("debug.separate_processes");
1912        if (separateProcesses != null && separateProcesses.length() > 0) {
1913            if ("*".equals(separateProcesses)) {
1914                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1915                mSeparateProcesses = null;
1916                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1917            } else {
1918                mDefParseFlags = 0;
1919                mSeparateProcesses = separateProcesses.split(",");
1920                Slog.w(TAG, "Running with debug.separate_processes: "
1921                        + separateProcesses);
1922            }
1923        } else {
1924            mDefParseFlags = 0;
1925            mSeparateProcesses = null;
1926        }
1927
1928        mInstaller = installer;
1929        mPackageDexOptimizer = new PackageDexOptimizer(this);
1930        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1931
1932        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1933                FgThread.get().getLooper());
1934
1935        getDefaultDisplayMetrics(context, mMetrics);
1936
1937        SystemConfig systemConfig = SystemConfig.getInstance();
1938        mGlobalGids = systemConfig.getGlobalGids();
1939        mSystemPermissions = systemConfig.getSystemPermissions();
1940        mAvailableFeatures = systemConfig.getAvailableFeatures();
1941
1942        synchronized (mInstallLock) {
1943        // writer
1944        synchronized (mPackages) {
1945            mHandlerThread = new ServiceThread(TAG,
1946                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1947            mHandlerThread.start();
1948            mHandler = new PackageHandler(mHandlerThread.getLooper());
1949            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1950
1951            File dataDir = Environment.getDataDirectory();
1952            mAppDataDir = new File(dataDir, "data");
1953            mAppInstallDir = new File(dataDir, "app");
1954            mAppLib32InstallDir = new File(dataDir, "app-lib");
1955            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1956            mUserAppDataDir = new File(dataDir, "user");
1957            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1958
1959            sUserManager = new UserManagerService(context, this, mPackages);
1960
1961            // Propagate permission configuration in to package manager.
1962            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1963                    = systemConfig.getPermissions();
1964            for (int i=0; i<permConfig.size(); i++) {
1965                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1966                BasePermission bp = mSettings.mPermissions.get(perm.name);
1967                if (bp == null) {
1968                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1969                    mSettings.mPermissions.put(perm.name, bp);
1970                }
1971                if (perm.gids != null) {
1972                    bp.setGids(perm.gids, perm.perUser);
1973                }
1974            }
1975
1976            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1977            for (int i=0; i<libConfig.size(); i++) {
1978                mSharedLibraries.put(libConfig.keyAt(i),
1979                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1980            }
1981
1982            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1983
1984            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
1985
1986            String customResolverActivity = Resources.getSystem().getString(
1987                    R.string.config_customResolverActivity);
1988            if (TextUtils.isEmpty(customResolverActivity)) {
1989                customResolverActivity = null;
1990            } else {
1991                mCustomResolverComponentName = ComponentName.unflattenFromString(
1992                        customResolverActivity);
1993            }
1994
1995            long startTime = SystemClock.uptimeMillis();
1996
1997            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1998                    startTime);
1999
2000            // Set flag to monitor and not change apk file paths when
2001            // scanning install directories.
2002            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2003
2004            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2005            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2006
2007            if (bootClassPath == null) {
2008                Slog.w(TAG, "No BOOTCLASSPATH found!");
2009            }
2010
2011            if (systemServerClassPath == null) {
2012                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2013            }
2014
2015            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2016            final String[] dexCodeInstructionSets =
2017                    getDexCodeInstructionSets(
2018                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2019
2020            /**
2021             * Ensure all external libraries have had dexopt run on them.
2022             */
2023            if (mSharedLibraries.size() > 0) {
2024                // NOTE: For now, we're compiling these system "shared libraries"
2025                // (and framework jars) into all available architectures. It's possible
2026                // to compile them only when we come across an app that uses them (there's
2027                // already logic for that in scanPackageLI) but that adds some complexity.
2028                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2029                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2030                        final String lib = libEntry.path;
2031                        if (lib == null) {
2032                            continue;
2033                        }
2034
2035                        try {
2036                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
2037                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2038                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2039                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/);
2040                            }
2041                        } catch (FileNotFoundException e) {
2042                            Slog.w(TAG, "Library not found: " + lib);
2043                        } catch (IOException e) {
2044                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2045                                    + e.getMessage());
2046                        }
2047                    }
2048                }
2049            }
2050
2051            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2052
2053            final VersionInfo ver = mSettings.getInternalVersion();
2054            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2055            // when upgrading from pre-M, promote system app permissions from install to runtime
2056            mPromoteSystemApps =
2057                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2058
2059            // save off the names of pre-existing system packages prior to scanning; we don't
2060            // want to automatically grant runtime permissions for new system apps
2061            if (mPromoteSystemApps) {
2062                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2063                while (pkgSettingIter.hasNext()) {
2064                    PackageSetting ps = pkgSettingIter.next();
2065                    if (isSystemApp(ps)) {
2066                        mExistingSystemPackages.add(ps.name);
2067                    }
2068                }
2069            }
2070
2071            // Collect vendor overlay packages.
2072            // (Do this before scanning any apps.)
2073            // For security and version matching reason, only consider
2074            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2075            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2076            scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2077                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2078
2079            // Find base frameworks (resource packages without code).
2080            scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2081                    | PackageParser.PARSE_IS_SYSTEM_DIR
2082                    | PackageParser.PARSE_IS_PRIVILEGED,
2083                    scanFlags | SCAN_NO_DEX, 0);
2084
2085            // Collected privileged system packages.
2086            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2087            scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2088                    | PackageParser.PARSE_IS_SYSTEM_DIR
2089                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2090
2091            // Collect ordinary system packages.
2092            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2093            scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2094                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2095
2096            // Collect all vendor packages.
2097            File vendorAppDir = new File("/vendor/app");
2098            try {
2099                vendorAppDir = vendorAppDir.getCanonicalFile();
2100            } catch (IOException e) {
2101                // failed to look up canonical path, continue with original one
2102            }
2103            scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2104                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2105
2106            // Collect all OEM packages.
2107            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2108            scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2109                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2110
2111            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2112            mInstaller.moveFiles();
2113
2114            // Prune any system packages that no longer exist.
2115            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2116            if (!mOnlyCore) {
2117                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2118                while (psit.hasNext()) {
2119                    PackageSetting ps = psit.next();
2120
2121                    /*
2122                     * If this is not a system app, it can't be a
2123                     * disable system app.
2124                     */
2125                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2126                        continue;
2127                    }
2128
2129                    /*
2130                     * If the package is scanned, it's not erased.
2131                     */
2132                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2133                    if (scannedPkg != null) {
2134                        /*
2135                         * If the system app is both scanned and in the
2136                         * disabled packages list, then it must have been
2137                         * added via OTA. Remove it from the currently
2138                         * scanned package so the previously user-installed
2139                         * application can be scanned.
2140                         */
2141                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2142                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2143                                    + ps.name + "; removing system app.  Last known codePath="
2144                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2145                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2146                                    + scannedPkg.mVersionCode);
2147                            removePackageLI(ps, true);
2148                            mExpectingBetter.put(ps.name, ps.codePath);
2149                        }
2150
2151                        continue;
2152                    }
2153
2154                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2155                        psit.remove();
2156                        logCriticalInfo(Log.WARN, "System package " + ps.name
2157                                + " no longer exists; wiping its data");
2158                        removeDataDirsLI(null, ps.name);
2159                    } else {
2160                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2161                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2162                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2163                        }
2164                    }
2165                }
2166            }
2167
2168            //look for any incomplete package installations
2169            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2170            //clean up list
2171            for(int i = 0; i < deletePkgsList.size(); i++) {
2172                //clean up here
2173                cleanupInstallFailedPackage(deletePkgsList.get(i));
2174            }
2175            //delete tmp files
2176            deleteTempPackageFiles();
2177
2178            // Remove any shared userIDs that have no associated packages
2179            mSettings.pruneSharedUsersLPw();
2180
2181            if (!mOnlyCore) {
2182                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2183                        SystemClock.uptimeMillis());
2184                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2185
2186                scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2187                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2188
2189                /**
2190                 * Remove disable package settings for any updated system
2191                 * apps that were removed via an OTA. If they're not a
2192                 * previously-updated app, remove them completely.
2193                 * Otherwise, just revoke their system-level permissions.
2194                 */
2195                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2196                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2197                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2198
2199                    String msg;
2200                    if (deletedPkg == null) {
2201                        msg = "Updated system package " + deletedAppName
2202                                + " no longer exists; wiping its data";
2203                        removeDataDirsLI(null, deletedAppName);
2204                    } else {
2205                        msg = "Updated system app + " + deletedAppName
2206                                + " no longer present; removing system privileges for "
2207                                + deletedAppName;
2208
2209                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2210
2211                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2212                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2213                    }
2214                    logCriticalInfo(Log.WARN, msg);
2215                }
2216
2217                /**
2218                 * Make sure all system apps that we expected to appear on
2219                 * the userdata partition actually showed up. If they never
2220                 * appeared, crawl back and revive the system version.
2221                 */
2222                for (int i = 0; i < mExpectingBetter.size(); i++) {
2223                    final String packageName = mExpectingBetter.keyAt(i);
2224                    if (!mPackages.containsKey(packageName)) {
2225                        final File scanFile = mExpectingBetter.valueAt(i);
2226
2227                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2228                                + " but never showed up; reverting to system");
2229
2230                        final int reparseFlags;
2231                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2232                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2233                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2234                                    | PackageParser.PARSE_IS_PRIVILEGED;
2235                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2236                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2237                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2238                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2239                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2240                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2241                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2242                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2243                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2244                        } else {
2245                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2246                            continue;
2247                        }
2248
2249                        mSettings.enableSystemPackageLPw(packageName);
2250
2251                        try {
2252                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2253                        } catch (PackageManagerException e) {
2254                            Slog.e(TAG, "Failed to parse original system package: "
2255                                    + e.getMessage());
2256                        }
2257                    }
2258                }
2259            }
2260            mExpectingBetter.clear();
2261
2262            // Now that we know all of the shared libraries, update all clients to have
2263            // the correct library paths.
2264            updateAllSharedLibrariesLPw();
2265
2266            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2267                // NOTE: We ignore potential failures here during a system scan (like
2268                // the rest of the commands above) because there's precious little we
2269                // can do about it. A settings error is reported, though.
2270                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2271                        false /* boot complete */);
2272            }
2273
2274            // Now that we know all the packages we are keeping,
2275            // read and update their last usage times.
2276            mPackageUsage.readLP();
2277
2278            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2279                    SystemClock.uptimeMillis());
2280            Slog.i(TAG, "Time to scan packages: "
2281                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2282                    + " seconds");
2283
2284            // If the platform SDK has changed since the last time we booted,
2285            // we need to re-grant app permission to catch any new ones that
2286            // appear.  This is really a hack, and means that apps can in some
2287            // cases get permissions that the user didn't initially explicitly
2288            // allow...  it would be nice to have some better way to handle
2289            // this situation.
2290            int updateFlags = UPDATE_PERMISSIONS_ALL;
2291            if (ver.sdkVersion != mSdkVersion) {
2292                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2293                        + mSdkVersion + "; regranting permissions for internal storage");
2294                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2295            }
2296            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2297            ver.sdkVersion = mSdkVersion;
2298
2299            // If this is the first boot or an update from pre-M, and it is a normal
2300            // boot, then we need to initialize the default preferred apps across
2301            // all defined users.
2302            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2303                for (UserInfo user : sUserManager.getUsers(true)) {
2304                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2305                    applyFactoryDefaultBrowserLPw(user.id);
2306                    primeDomainVerificationsLPw(user.id);
2307                }
2308            }
2309
2310            // If this is first boot after an OTA, and a normal boot, then
2311            // we need to clear code cache directories.
2312            if (mIsUpgrade && !onlyCore) {
2313                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2314                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2315                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2316                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2317                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2318                    }
2319                }
2320                ver.fingerprint = Build.FINGERPRINT;
2321            }
2322
2323            checkDefaultBrowser();
2324
2325            // clear only after permissions and other defaults have been updated
2326            mExistingSystemPackages.clear();
2327            mPromoteSystemApps = false;
2328
2329            // All the changes are done during package scanning.
2330            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2331
2332            // can downgrade to reader
2333            mSettings.writeLPr();
2334
2335            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2336                    SystemClock.uptimeMillis());
2337
2338            mRequiredVerifierPackage = getRequiredVerifierLPr();
2339            mRequiredInstallerPackage = getRequiredInstallerLPr();
2340
2341            mInstallerService = new PackageInstallerService(context, this);
2342
2343            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2344            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2345                    mIntentFilterVerifierComponent);
2346
2347        } // synchronized (mPackages)
2348        } // synchronized (mInstallLock)
2349
2350        // Now after opening every single application zip, make sure they
2351        // are all flushed.  Not really needed, but keeps things nice and
2352        // tidy.
2353        Runtime.getRuntime().gc();
2354
2355        // The initial scanning above does many calls into installd while
2356        // holding the mPackages lock, but we're mostly interested in yelling
2357        // once we have a booted system.
2358        mInstaller.setWarnIfHeld(mPackages);
2359
2360        // Expose private service for system components to use.
2361        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2362    }
2363
2364    @Override
2365    public boolean isFirstBoot() {
2366        return !mRestoredSettings;
2367    }
2368
2369    @Override
2370    public boolean isOnlyCoreApps() {
2371        return mOnlyCore;
2372    }
2373
2374    @Override
2375    public boolean isUpgrade() {
2376        return mIsUpgrade;
2377    }
2378
2379    private String getRequiredVerifierLPr() {
2380        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2381        // We only care about verifier that's installed under system user.
2382        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2383                PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM);
2384
2385        String requiredVerifier = null;
2386
2387        final int N = receivers.size();
2388        for (int i = 0; i < N; i++) {
2389            final ResolveInfo info = receivers.get(i);
2390
2391            if (info.activityInfo == null) {
2392                continue;
2393            }
2394
2395            final String packageName = info.activityInfo.packageName;
2396
2397            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2398                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2399                continue;
2400            }
2401
2402            if (requiredVerifier != null) {
2403                throw new RuntimeException("There can be only one required verifier");
2404            }
2405
2406            requiredVerifier = packageName;
2407        }
2408
2409        return requiredVerifier;
2410    }
2411
2412    private String getRequiredInstallerLPr() {
2413        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2414        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2415        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2416
2417        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2418                PACKAGE_MIME_TYPE, 0, UserHandle.USER_SYSTEM);
2419
2420        String requiredInstaller = null;
2421
2422        final int N = installers.size();
2423        for (int i = 0; i < N; i++) {
2424            final ResolveInfo info = installers.get(i);
2425            final String packageName = info.activityInfo.packageName;
2426
2427            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2428                continue;
2429            }
2430
2431            if (requiredInstaller != null) {
2432                throw new RuntimeException("There must be one required installer");
2433            }
2434
2435            requiredInstaller = packageName;
2436        }
2437
2438        if (requiredInstaller == null) {
2439            throw new RuntimeException("There must be one required installer");
2440        }
2441
2442        return requiredInstaller;
2443    }
2444
2445    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2446        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2447        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2448                PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM);
2449
2450        ComponentName verifierComponentName = null;
2451
2452        int priority = -1000;
2453        final int N = receivers.size();
2454        for (int i = 0; i < N; i++) {
2455            final ResolveInfo info = receivers.get(i);
2456
2457            if (info.activityInfo == null) {
2458                continue;
2459            }
2460
2461            final String packageName = info.activityInfo.packageName;
2462
2463            final PackageSetting ps = mSettings.mPackages.get(packageName);
2464            if (ps == null) {
2465                continue;
2466            }
2467
2468            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2469                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2470                continue;
2471            }
2472
2473            // Select the IntentFilterVerifier with the highest priority
2474            if (priority < info.priority) {
2475                priority = info.priority;
2476                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2477                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2478                        + verifierComponentName + " with priority: " + info.priority);
2479            }
2480        }
2481
2482        return verifierComponentName;
2483    }
2484
2485    private void primeDomainVerificationsLPw(int userId) {
2486        if (DEBUG_DOMAIN_VERIFICATION) {
2487            Slog.d(TAG, "Priming domain verifications in user " + userId);
2488        }
2489
2490        SystemConfig systemConfig = SystemConfig.getInstance();
2491        ArraySet<String> packages = systemConfig.getLinkedApps();
2492        ArraySet<String> domains = new ArraySet<String>();
2493
2494        for (String packageName : packages) {
2495            PackageParser.Package pkg = mPackages.get(packageName);
2496            if (pkg != null) {
2497                if (!pkg.isSystemApp()) {
2498                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2499                    continue;
2500                }
2501
2502                domains.clear();
2503                for (PackageParser.Activity a : pkg.activities) {
2504                    for (ActivityIntentInfo filter : a.intents) {
2505                        if (hasValidDomains(filter)) {
2506                            domains.addAll(filter.getHostsList());
2507                        }
2508                    }
2509                }
2510
2511                if (domains.size() > 0) {
2512                    if (DEBUG_DOMAIN_VERIFICATION) {
2513                        Slog.v(TAG, "      + " + packageName);
2514                    }
2515                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2516                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2517                    // and then 'always' in the per-user state actually used for intent resolution.
2518                    final IntentFilterVerificationInfo ivi;
2519                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2520                            new ArrayList<String>(domains));
2521                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2522                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2523                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2524                } else {
2525                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2526                            + "' does not handle web links");
2527                }
2528            } else {
2529                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2530            }
2531        }
2532
2533        scheduleWritePackageRestrictionsLocked(userId);
2534        scheduleWriteSettingsLocked();
2535    }
2536
2537    private void applyFactoryDefaultBrowserLPw(int userId) {
2538        // The default browser app's package name is stored in a string resource,
2539        // with a product-specific overlay used for vendor customization.
2540        String browserPkg = mContext.getResources().getString(
2541                com.android.internal.R.string.default_browser);
2542        if (!TextUtils.isEmpty(browserPkg)) {
2543            // non-empty string => required to be a known package
2544            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2545            if (ps == null) {
2546                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2547                browserPkg = null;
2548            } else {
2549                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2550            }
2551        }
2552
2553        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2554        // default.  If there's more than one, just leave everything alone.
2555        if (browserPkg == null) {
2556            calculateDefaultBrowserLPw(userId);
2557        }
2558    }
2559
2560    private void calculateDefaultBrowserLPw(int userId) {
2561        List<String> allBrowsers = resolveAllBrowserApps(userId);
2562        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2563        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2564    }
2565
2566    private List<String> resolveAllBrowserApps(int userId) {
2567        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2568        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2569                PackageManager.MATCH_ALL, userId);
2570
2571        final int count = list.size();
2572        List<String> result = new ArrayList<String>(count);
2573        for (int i=0; i<count; i++) {
2574            ResolveInfo info = list.get(i);
2575            if (info.activityInfo == null
2576                    || !info.handleAllWebDataURI
2577                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2578                    || result.contains(info.activityInfo.packageName)) {
2579                continue;
2580            }
2581            result.add(info.activityInfo.packageName);
2582        }
2583
2584        return result;
2585    }
2586
2587    private boolean packageIsBrowser(String packageName, int userId) {
2588        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2589                PackageManager.MATCH_ALL, userId);
2590        final int N = list.size();
2591        for (int i = 0; i < N; i++) {
2592            ResolveInfo info = list.get(i);
2593            if (packageName.equals(info.activityInfo.packageName)) {
2594                return true;
2595            }
2596        }
2597        return false;
2598    }
2599
2600    private void checkDefaultBrowser() {
2601        final int myUserId = UserHandle.myUserId();
2602        final String packageName = getDefaultBrowserPackageName(myUserId);
2603        if (packageName != null) {
2604            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2605            if (info == null) {
2606                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2607                synchronized (mPackages) {
2608                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2609                }
2610            }
2611        }
2612    }
2613
2614    @Override
2615    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2616            throws RemoteException {
2617        try {
2618            return super.onTransact(code, data, reply, flags);
2619        } catch (RuntimeException e) {
2620            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2621                Slog.wtf(TAG, "Package Manager Crash", e);
2622            }
2623            throw e;
2624        }
2625    }
2626
2627    void cleanupInstallFailedPackage(PackageSetting ps) {
2628        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2629
2630        removeDataDirsLI(ps.volumeUuid, ps.name);
2631        if (ps.codePath != null) {
2632            if (ps.codePath.isDirectory()) {
2633                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2634            } else {
2635                ps.codePath.delete();
2636            }
2637        }
2638        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2639            if (ps.resourcePath.isDirectory()) {
2640                FileUtils.deleteContents(ps.resourcePath);
2641            }
2642            ps.resourcePath.delete();
2643        }
2644        mSettings.removePackageLPw(ps.name);
2645    }
2646
2647    static int[] appendInts(int[] cur, int[] add) {
2648        if (add == null) return cur;
2649        if (cur == null) return add;
2650        final int N = add.length;
2651        for (int i=0; i<N; i++) {
2652            cur = appendInt(cur, add[i]);
2653        }
2654        return cur;
2655    }
2656
2657    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2658        if (!sUserManager.exists(userId)) return null;
2659        final PackageSetting ps = (PackageSetting) p.mExtras;
2660        if (ps == null) {
2661            return null;
2662        }
2663
2664        final PermissionsState permissionsState = ps.getPermissionsState();
2665
2666        final int[] gids = permissionsState.computeGids(userId);
2667        final Set<String> permissions = permissionsState.getPermissions(userId);
2668        final PackageUserState state = ps.readUserState(userId);
2669
2670        return PackageParser.generatePackageInfo(p, gids, flags,
2671                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2672    }
2673
2674    @Override
2675    public boolean isPackageFrozen(String packageName) {
2676        synchronized (mPackages) {
2677            final PackageSetting ps = mSettings.mPackages.get(packageName);
2678            if (ps != null) {
2679                return ps.frozen;
2680            }
2681        }
2682        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2683        return true;
2684    }
2685
2686    @Override
2687    public boolean isPackageAvailable(String packageName, int userId) {
2688        if (!sUserManager.exists(userId)) return false;
2689        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2690        synchronized (mPackages) {
2691            PackageParser.Package p = mPackages.get(packageName);
2692            if (p != null) {
2693                final PackageSetting ps = (PackageSetting) p.mExtras;
2694                if (ps != null) {
2695                    final PackageUserState state = ps.readUserState(userId);
2696                    if (state != null) {
2697                        return PackageParser.isAvailable(state);
2698                    }
2699                }
2700            }
2701        }
2702        return false;
2703    }
2704
2705    @Override
2706    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2707        if (!sUserManager.exists(userId)) return null;
2708        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2709        // reader
2710        synchronized (mPackages) {
2711            PackageParser.Package p = mPackages.get(packageName);
2712            if (DEBUG_PACKAGE_INFO)
2713                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2714            if (p != null) {
2715                return generatePackageInfo(p, flags, userId);
2716            }
2717            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2718                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2719            }
2720        }
2721        return null;
2722    }
2723
2724    @Override
2725    public String[] currentToCanonicalPackageNames(String[] names) {
2726        String[] out = new String[names.length];
2727        // reader
2728        synchronized (mPackages) {
2729            for (int i=names.length-1; i>=0; i--) {
2730                PackageSetting ps = mSettings.mPackages.get(names[i]);
2731                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2732            }
2733        }
2734        return out;
2735    }
2736
2737    @Override
2738    public String[] canonicalToCurrentPackageNames(String[] names) {
2739        String[] out = new String[names.length];
2740        // reader
2741        synchronized (mPackages) {
2742            for (int i=names.length-1; i>=0; i--) {
2743                String cur = mSettings.mRenamedPackages.get(names[i]);
2744                out[i] = cur != null ? cur : names[i];
2745            }
2746        }
2747        return out;
2748    }
2749
2750    @Override
2751    public int getPackageUid(String packageName, int userId) {
2752        return getPackageUidEtc(packageName, 0, userId);
2753    }
2754
2755    @Override
2756    public int getPackageUidEtc(String packageName, int flags, int userId) {
2757        if (!sUserManager.exists(userId)) return -1;
2758        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2759
2760        // reader
2761        synchronized (mPackages) {
2762            final PackageParser.Package p = mPackages.get(packageName);
2763            if (p != null) {
2764                return UserHandle.getUid(userId, p.applicationInfo.uid);
2765            }
2766            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2767                final PackageSetting ps = mSettings.mPackages.get(packageName);
2768                if (ps != null) {
2769                    return UserHandle.getUid(userId, ps.appId);
2770                }
2771            }
2772        }
2773
2774        return -1;
2775    }
2776
2777    @Override
2778    public int[] getPackageGids(String packageName, int userId) {
2779        return getPackageGidsEtc(packageName, 0, userId);
2780    }
2781
2782    @Override
2783    public int[] getPackageGidsEtc(String packageName, int flags, int userId) {
2784        if (!sUserManager.exists(userId)) {
2785            return null;
2786        }
2787
2788        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2789                "getPackageGids");
2790
2791        // reader
2792        synchronized (mPackages) {
2793            final PackageParser.Package p = mPackages.get(packageName);
2794            if (p != null) {
2795                PackageSetting ps = (PackageSetting) p.mExtras;
2796                return ps.getPermissionsState().computeGids(userId);
2797            }
2798            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2799                final PackageSetting ps = mSettings.mPackages.get(packageName);
2800                if (ps != null) {
2801                    return ps.getPermissionsState().computeGids(userId);
2802                }
2803            }
2804        }
2805
2806        return null;
2807    }
2808
2809    static PermissionInfo generatePermissionInfo(
2810            BasePermission bp, int flags) {
2811        if (bp.perm != null) {
2812            return PackageParser.generatePermissionInfo(bp.perm, flags);
2813        }
2814        PermissionInfo pi = new PermissionInfo();
2815        pi.name = bp.name;
2816        pi.packageName = bp.sourcePackage;
2817        pi.nonLocalizedLabel = bp.name;
2818        pi.protectionLevel = bp.protectionLevel;
2819        return pi;
2820    }
2821
2822    @Override
2823    public PermissionInfo getPermissionInfo(String name, int flags) {
2824        // reader
2825        synchronized (mPackages) {
2826            final BasePermission p = mSettings.mPermissions.get(name);
2827            if (p != null) {
2828                return generatePermissionInfo(p, flags);
2829            }
2830            return null;
2831        }
2832    }
2833
2834    @Override
2835    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2836        // reader
2837        synchronized (mPackages) {
2838            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2839            for (BasePermission p : mSettings.mPermissions.values()) {
2840                if (group == null) {
2841                    if (p.perm == null || p.perm.info.group == null) {
2842                        out.add(generatePermissionInfo(p, flags));
2843                    }
2844                } else {
2845                    if (p.perm != null && group.equals(p.perm.info.group)) {
2846                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2847                    }
2848                }
2849            }
2850
2851            if (out.size() > 0) {
2852                return out;
2853            }
2854            return mPermissionGroups.containsKey(group) ? out : null;
2855        }
2856    }
2857
2858    @Override
2859    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2860        // reader
2861        synchronized (mPackages) {
2862            return PackageParser.generatePermissionGroupInfo(
2863                    mPermissionGroups.get(name), flags);
2864        }
2865    }
2866
2867    @Override
2868    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2869        // reader
2870        synchronized (mPackages) {
2871            final int N = mPermissionGroups.size();
2872            ArrayList<PermissionGroupInfo> out
2873                    = new ArrayList<PermissionGroupInfo>(N);
2874            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2875                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2876            }
2877            return out;
2878        }
2879    }
2880
2881    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2882            int userId) {
2883        if (!sUserManager.exists(userId)) return null;
2884        PackageSetting ps = mSettings.mPackages.get(packageName);
2885        if (ps != null) {
2886            if (ps.pkg == null) {
2887                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2888                        flags, userId);
2889                if (pInfo != null) {
2890                    return pInfo.applicationInfo;
2891                }
2892                return null;
2893            }
2894            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2895                    ps.readUserState(userId), userId);
2896        }
2897        return null;
2898    }
2899
2900    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2901            int userId) {
2902        if (!sUserManager.exists(userId)) return null;
2903        PackageSetting ps = mSettings.mPackages.get(packageName);
2904        if (ps != null) {
2905            PackageParser.Package pkg = ps.pkg;
2906            if (pkg == null) {
2907                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2908                    return null;
2909                }
2910                // Only data remains, so we aren't worried about code paths
2911                pkg = new PackageParser.Package(packageName);
2912                pkg.applicationInfo.packageName = packageName;
2913                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2914                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2915                pkg.applicationInfo.uid = ps.appId;
2916                pkg.applicationInfo.initForUser(userId);
2917                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2918                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2919            }
2920            return generatePackageInfo(pkg, flags, userId);
2921        }
2922        return null;
2923    }
2924
2925    @Override
2926    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2927        if (!sUserManager.exists(userId)) return null;
2928        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2929        // writer
2930        synchronized (mPackages) {
2931            PackageParser.Package p = mPackages.get(packageName);
2932            if (DEBUG_PACKAGE_INFO) Log.v(
2933                    TAG, "getApplicationInfo " + packageName
2934                    + ": " + p);
2935            if (p != null) {
2936                PackageSetting ps = mSettings.mPackages.get(packageName);
2937                if (ps == null) return null;
2938                // Note: isEnabledLP() does not apply here - always return info
2939                return PackageParser.generateApplicationInfo(
2940                        p, flags, ps.readUserState(userId), userId);
2941            }
2942            if ("android".equals(packageName)||"system".equals(packageName)) {
2943                return mAndroidApplication;
2944            }
2945            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2946                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2947            }
2948        }
2949        return null;
2950    }
2951
2952    @Override
2953    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2954            final IPackageDataObserver observer) {
2955        mContext.enforceCallingOrSelfPermission(
2956                android.Manifest.permission.CLEAR_APP_CACHE, null);
2957        // Queue up an async operation since clearing cache may take a little while.
2958        mHandler.post(new Runnable() {
2959            public void run() {
2960                mHandler.removeCallbacks(this);
2961                int retCode = -1;
2962                synchronized (mInstallLock) {
2963                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2964                    if (retCode < 0) {
2965                        Slog.w(TAG, "Couldn't clear application caches");
2966                    }
2967                }
2968                if (observer != null) {
2969                    try {
2970                        observer.onRemoveCompleted(null, (retCode >= 0));
2971                    } catch (RemoteException e) {
2972                        Slog.w(TAG, "RemoveException when invoking call back");
2973                    }
2974                }
2975            }
2976        });
2977    }
2978
2979    @Override
2980    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2981            final IntentSender pi) {
2982        mContext.enforceCallingOrSelfPermission(
2983                android.Manifest.permission.CLEAR_APP_CACHE, null);
2984        // Queue up an async operation since clearing cache may take a little while.
2985        mHandler.post(new Runnable() {
2986            public void run() {
2987                mHandler.removeCallbacks(this);
2988                int retCode = -1;
2989                synchronized (mInstallLock) {
2990                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2991                    if (retCode < 0) {
2992                        Slog.w(TAG, "Couldn't clear application caches");
2993                    }
2994                }
2995                if(pi != null) {
2996                    try {
2997                        // Callback via pending intent
2998                        int code = (retCode >= 0) ? 1 : 0;
2999                        pi.sendIntent(null, code, null,
3000                                null, null);
3001                    } catch (SendIntentException e1) {
3002                        Slog.i(TAG, "Failed to send pending intent");
3003                    }
3004                }
3005            }
3006        });
3007    }
3008
3009    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3010        synchronized (mInstallLock) {
3011            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
3012                throw new IOException("Failed to free enough space");
3013            }
3014        }
3015    }
3016
3017    /**
3018     * Augment the given flags depending on current user running state. This is
3019     * purposefully done before acquiring {@link #mPackages} lock.
3020     */
3021    private int augmentFlagsForUser(int flags, int userId) {
3022        if (SystemProperties.getBoolean(StorageManager.PROP_HAS_FBE, false)) {
3023            final IMountService mount = IMountService.Stub
3024                    .asInterface(ServiceManager.getService(Context.STORAGE_SERVICE));
3025            if (mount == null) {
3026                // We must be early in boot, so the best we can do is assume the
3027                // user is fully running.
3028                return flags;
3029            }
3030            final long token = Binder.clearCallingIdentity();
3031            try {
3032                if (!mount.isUserKeyUnlocked(userId)) {
3033                    flags |= PackageManager.FLAG_USER_RUNNING_WITH_AMNESIA;
3034                }
3035            } catch (RemoteException e) {
3036                throw e.rethrowAsRuntimeException();
3037            } finally {
3038                Binder.restoreCallingIdentity(token);
3039            }
3040        }
3041        return flags;
3042    }
3043
3044    @Override
3045    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3046        if (!sUserManager.exists(userId)) return null;
3047        flags = augmentFlagsForUser(flags, userId);
3048        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
3049        synchronized (mPackages) {
3050            PackageParser.Activity a = mActivities.mActivities.get(component);
3051
3052            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3053            if (a != null && mSettings.isEnabledAndVisibleLPr(a.info, flags, userId)) {
3054                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3055                if (ps == null) return null;
3056                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3057                        userId);
3058            }
3059            if (mResolveComponentName.equals(component)) {
3060                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3061                        new PackageUserState(), userId);
3062            }
3063        }
3064        return null;
3065    }
3066
3067    @Override
3068    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3069            String resolvedType) {
3070        synchronized (mPackages) {
3071            if (component.equals(mResolveComponentName)) {
3072                // The resolver supports EVERYTHING!
3073                return true;
3074            }
3075            PackageParser.Activity a = mActivities.mActivities.get(component);
3076            if (a == null) {
3077                return false;
3078            }
3079            for (int i=0; i<a.intents.size(); i++) {
3080                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3081                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3082                    return true;
3083                }
3084            }
3085            return false;
3086        }
3087    }
3088
3089    @Override
3090    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3091        if (!sUserManager.exists(userId)) return null;
3092        flags = augmentFlagsForUser(flags, userId);
3093        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3094        synchronized (mPackages) {
3095            PackageParser.Activity a = mReceivers.mActivities.get(component);
3096            if (DEBUG_PACKAGE_INFO) Log.v(
3097                TAG, "getReceiverInfo " + component + ": " + a);
3098            if (a != null && mSettings.isEnabledAndVisibleLPr(a.info, flags, userId)) {
3099                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3100                if (ps == null) return null;
3101                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3102                        userId);
3103            }
3104        }
3105        return null;
3106    }
3107
3108    @Override
3109    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3110        if (!sUserManager.exists(userId)) return null;
3111        flags = augmentFlagsForUser(flags, userId);
3112        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3113        synchronized (mPackages) {
3114            PackageParser.Service s = mServices.mServices.get(component);
3115            if (DEBUG_PACKAGE_INFO) Log.v(
3116                TAG, "getServiceInfo " + component + ": " + s);
3117            if (s != null && mSettings.isEnabledAndVisibleLPr(s.info, flags, userId)) {
3118                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3119                if (ps == null) return null;
3120                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3121                        userId);
3122            }
3123        }
3124        return null;
3125    }
3126
3127    @Override
3128    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3129        if (!sUserManager.exists(userId)) return null;
3130        flags = augmentFlagsForUser(flags, userId);
3131        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3132        synchronized (mPackages) {
3133            PackageParser.Provider p = mProviders.mProviders.get(component);
3134            if (DEBUG_PACKAGE_INFO) Log.v(
3135                TAG, "getProviderInfo " + component + ": " + p);
3136            if (p != null && mSettings.isEnabledAndVisibleLPr(p.info, flags, userId)) {
3137                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3138                if (ps == null) return null;
3139                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3140                        userId);
3141            }
3142        }
3143        return null;
3144    }
3145
3146    @Override
3147    public String[] getSystemSharedLibraryNames() {
3148        Set<String> libSet;
3149        synchronized (mPackages) {
3150            libSet = mSharedLibraries.keySet();
3151            int size = libSet.size();
3152            if (size > 0) {
3153                String[] libs = new String[size];
3154                libSet.toArray(libs);
3155                return libs;
3156            }
3157        }
3158        return null;
3159    }
3160
3161    /**
3162     * @hide
3163     */
3164    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3165        synchronized (mPackages) {
3166            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3167            if (lib != null && lib.apk != null) {
3168                return mPackages.get(lib.apk);
3169            }
3170        }
3171        return null;
3172    }
3173
3174    @Override
3175    public FeatureInfo[] getSystemAvailableFeatures() {
3176        Collection<FeatureInfo> featSet;
3177        synchronized (mPackages) {
3178            featSet = mAvailableFeatures.values();
3179            int size = featSet.size();
3180            if (size > 0) {
3181                FeatureInfo[] features = new FeatureInfo[size+1];
3182                featSet.toArray(features);
3183                FeatureInfo fi = new FeatureInfo();
3184                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3185                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3186                features[size] = fi;
3187                return features;
3188            }
3189        }
3190        return null;
3191    }
3192
3193    @Override
3194    public boolean hasSystemFeature(String name) {
3195        synchronized (mPackages) {
3196            return mAvailableFeatures.containsKey(name);
3197        }
3198    }
3199
3200    private void checkValidCaller(int uid, int userId) {
3201        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3202            return;
3203
3204        throw new SecurityException("Caller uid=" + uid
3205                + " is not privileged to communicate with user=" + userId);
3206    }
3207
3208    @Override
3209    public int checkPermission(String permName, String pkgName, int userId) {
3210        if (!sUserManager.exists(userId)) {
3211            return PackageManager.PERMISSION_DENIED;
3212        }
3213
3214        synchronized (mPackages) {
3215            final PackageParser.Package p = mPackages.get(pkgName);
3216            if (p != null && p.mExtras != null) {
3217                final PackageSetting ps = (PackageSetting) p.mExtras;
3218                final PermissionsState permissionsState = ps.getPermissionsState();
3219                if (permissionsState.hasPermission(permName, userId)) {
3220                    return PackageManager.PERMISSION_GRANTED;
3221                }
3222                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3223                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3224                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3225                    return PackageManager.PERMISSION_GRANTED;
3226                }
3227            }
3228        }
3229
3230        return PackageManager.PERMISSION_DENIED;
3231    }
3232
3233    @Override
3234    public int checkUidPermission(String permName, int uid) {
3235        final int userId = UserHandle.getUserId(uid);
3236
3237        if (!sUserManager.exists(userId)) {
3238            return PackageManager.PERMISSION_DENIED;
3239        }
3240
3241        synchronized (mPackages) {
3242            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3243            if (obj != null) {
3244                final SettingBase ps = (SettingBase) obj;
3245                final PermissionsState permissionsState = ps.getPermissionsState();
3246                if (permissionsState.hasPermission(permName, userId)) {
3247                    return PackageManager.PERMISSION_GRANTED;
3248                }
3249                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3250                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3251                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3252                    return PackageManager.PERMISSION_GRANTED;
3253                }
3254            } else {
3255                ArraySet<String> perms = mSystemPermissions.get(uid);
3256                if (perms != null) {
3257                    if (perms.contains(permName)) {
3258                        return PackageManager.PERMISSION_GRANTED;
3259                    }
3260                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3261                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3262                        return PackageManager.PERMISSION_GRANTED;
3263                    }
3264                }
3265            }
3266        }
3267
3268        return PackageManager.PERMISSION_DENIED;
3269    }
3270
3271    @Override
3272    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3273        if (UserHandle.getCallingUserId() != userId) {
3274            mContext.enforceCallingPermission(
3275                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3276                    "isPermissionRevokedByPolicy for user " + userId);
3277        }
3278
3279        if (checkPermission(permission, packageName, userId)
3280                == PackageManager.PERMISSION_GRANTED) {
3281            return false;
3282        }
3283
3284        final long identity = Binder.clearCallingIdentity();
3285        try {
3286            final int flags = getPermissionFlags(permission, packageName, userId);
3287            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3288        } finally {
3289            Binder.restoreCallingIdentity(identity);
3290        }
3291    }
3292
3293    @Override
3294    public String getPermissionControllerPackageName() {
3295        synchronized (mPackages) {
3296            return mRequiredInstallerPackage;
3297        }
3298    }
3299
3300    /**
3301     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3302     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3303     * @param checkShell TODO(yamasani):
3304     * @param message the message to log on security exception
3305     */
3306    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3307            boolean checkShell, String message) {
3308        if (userId < 0) {
3309            throw new IllegalArgumentException("Invalid userId " + userId);
3310        }
3311        if (checkShell) {
3312            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3313        }
3314        if (userId == UserHandle.getUserId(callingUid)) return;
3315        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3316            if (requireFullPermission) {
3317                mContext.enforceCallingOrSelfPermission(
3318                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3319            } else {
3320                try {
3321                    mContext.enforceCallingOrSelfPermission(
3322                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3323                } catch (SecurityException se) {
3324                    mContext.enforceCallingOrSelfPermission(
3325                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3326                }
3327            }
3328        }
3329    }
3330
3331    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3332        if (callingUid == Process.SHELL_UID) {
3333            if (userHandle >= 0
3334                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3335                throw new SecurityException("Shell does not have permission to access user "
3336                        + userHandle);
3337            } else if (userHandle < 0) {
3338                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3339                        + Debug.getCallers(3));
3340            }
3341        }
3342    }
3343
3344    private BasePermission findPermissionTreeLP(String permName) {
3345        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3346            if (permName.startsWith(bp.name) &&
3347                    permName.length() > bp.name.length() &&
3348                    permName.charAt(bp.name.length()) == '.') {
3349                return bp;
3350            }
3351        }
3352        return null;
3353    }
3354
3355    private BasePermission checkPermissionTreeLP(String permName) {
3356        if (permName != null) {
3357            BasePermission bp = findPermissionTreeLP(permName);
3358            if (bp != null) {
3359                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3360                    return bp;
3361                }
3362                throw new SecurityException("Calling uid "
3363                        + Binder.getCallingUid()
3364                        + " is not allowed to add to permission tree "
3365                        + bp.name + " owned by uid " + bp.uid);
3366            }
3367        }
3368        throw new SecurityException("No permission tree found for " + permName);
3369    }
3370
3371    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3372        if (s1 == null) {
3373            return s2 == null;
3374        }
3375        if (s2 == null) {
3376            return false;
3377        }
3378        if (s1.getClass() != s2.getClass()) {
3379            return false;
3380        }
3381        return s1.equals(s2);
3382    }
3383
3384    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3385        if (pi1.icon != pi2.icon) return false;
3386        if (pi1.logo != pi2.logo) return false;
3387        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3388        if (!compareStrings(pi1.name, pi2.name)) return false;
3389        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3390        // We'll take care of setting this one.
3391        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3392        // These are not currently stored in settings.
3393        //if (!compareStrings(pi1.group, pi2.group)) return false;
3394        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3395        //if (pi1.labelRes != pi2.labelRes) return false;
3396        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3397        return true;
3398    }
3399
3400    int permissionInfoFootprint(PermissionInfo info) {
3401        int size = info.name.length();
3402        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3403        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3404        return size;
3405    }
3406
3407    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3408        int size = 0;
3409        for (BasePermission perm : mSettings.mPermissions.values()) {
3410            if (perm.uid == tree.uid) {
3411                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3412            }
3413        }
3414        return size;
3415    }
3416
3417    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3418        // We calculate the max size of permissions defined by this uid and throw
3419        // if that plus the size of 'info' would exceed our stated maximum.
3420        if (tree.uid != Process.SYSTEM_UID) {
3421            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3422            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3423                throw new SecurityException("Permission tree size cap exceeded");
3424            }
3425        }
3426    }
3427
3428    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3429        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3430            throw new SecurityException("Label must be specified in permission");
3431        }
3432        BasePermission tree = checkPermissionTreeLP(info.name);
3433        BasePermission bp = mSettings.mPermissions.get(info.name);
3434        boolean added = bp == null;
3435        boolean changed = true;
3436        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3437        if (added) {
3438            enforcePermissionCapLocked(info, tree);
3439            bp = new BasePermission(info.name, tree.sourcePackage,
3440                    BasePermission.TYPE_DYNAMIC);
3441        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3442            throw new SecurityException(
3443                    "Not allowed to modify non-dynamic permission "
3444                    + info.name);
3445        } else {
3446            if (bp.protectionLevel == fixedLevel
3447                    && bp.perm.owner.equals(tree.perm.owner)
3448                    && bp.uid == tree.uid
3449                    && comparePermissionInfos(bp.perm.info, info)) {
3450                changed = false;
3451            }
3452        }
3453        bp.protectionLevel = fixedLevel;
3454        info = new PermissionInfo(info);
3455        info.protectionLevel = fixedLevel;
3456        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3457        bp.perm.info.packageName = tree.perm.info.packageName;
3458        bp.uid = tree.uid;
3459        if (added) {
3460            mSettings.mPermissions.put(info.name, bp);
3461        }
3462        if (changed) {
3463            if (!async) {
3464                mSettings.writeLPr();
3465            } else {
3466                scheduleWriteSettingsLocked();
3467            }
3468        }
3469        return added;
3470    }
3471
3472    @Override
3473    public boolean addPermission(PermissionInfo info) {
3474        synchronized (mPackages) {
3475            return addPermissionLocked(info, false);
3476        }
3477    }
3478
3479    @Override
3480    public boolean addPermissionAsync(PermissionInfo info) {
3481        synchronized (mPackages) {
3482            return addPermissionLocked(info, true);
3483        }
3484    }
3485
3486    @Override
3487    public void removePermission(String name) {
3488        synchronized (mPackages) {
3489            checkPermissionTreeLP(name);
3490            BasePermission bp = mSettings.mPermissions.get(name);
3491            if (bp != null) {
3492                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3493                    throw new SecurityException(
3494                            "Not allowed to modify non-dynamic permission "
3495                            + name);
3496                }
3497                mSettings.mPermissions.remove(name);
3498                mSettings.writeLPr();
3499            }
3500        }
3501    }
3502
3503    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3504            BasePermission bp) {
3505        int index = pkg.requestedPermissions.indexOf(bp.name);
3506        if (index == -1) {
3507            throw new SecurityException("Package " + pkg.packageName
3508                    + " has not requested permission " + bp.name);
3509        }
3510        if (!bp.isRuntime() && !bp.isDevelopment()) {
3511            throw new SecurityException("Permission " + bp.name
3512                    + " is not a changeable permission type");
3513        }
3514    }
3515
3516    @Override
3517    public void grantRuntimePermission(String packageName, String name, final int userId) {
3518        if (!sUserManager.exists(userId)) {
3519            Log.e(TAG, "No such user:" + userId);
3520            return;
3521        }
3522
3523        mContext.enforceCallingOrSelfPermission(
3524                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3525                "grantRuntimePermission");
3526
3527        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3528                "grantRuntimePermission");
3529
3530        final int uid;
3531        final SettingBase sb;
3532
3533        synchronized (mPackages) {
3534            final PackageParser.Package pkg = mPackages.get(packageName);
3535            if (pkg == null) {
3536                throw new IllegalArgumentException("Unknown package: " + packageName);
3537            }
3538
3539            final BasePermission bp = mSettings.mPermissions.get(name);
3540            if (bp == null) {
3541                throw new IllegalArgumentException("Unknown permission: " + name);
3542            }
3543
3544            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3545
3546            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3547            sb = (SettingBase) pkg.mExtras;
3548            if (sb == null) {
3549                throw new IllegalArgumentException("Unknown package: " + packageName);
3550            }
3551
3552            final PermissionsState permissionsState = sb.getPermissionsState();
3553
3554            final int flags = permissionsState.getPermissionFlags(name, userId);
3555            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3556                throw new SecurityException("Cannot grant system fixed permission: "
3557                        + name + " for package: " + packageName);
3558            }
3559
3560            if (bp.isDevelopment()) {
3561                // Development permissions must be handled specially, since they are not
3562                // normal runtime permissions.  For now they apply to all users.
3563                if (permissionsState.grantInstallPermission(bp) !=
3564                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3565                    scheduleWriteSettingsLocked();
3566                }
3567                return;
3568            }
3569
3570            final int result = permissionsState.grantRuntimePermission(bp, userId);
3571            switch (result) {
3572                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3573                    return;
3574                }
3575
3576                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3577                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3578                    mHandler.post(new Runnable() {
3579                        @Override
3580                        public void run() {
3581                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3582                        }
3583                    });
3584                }
3585                break;
3586            }
3587
3588            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3589
3590            // Not critical if that is lost - app has to request again.
3591            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3592        }
3593
3594        // Only need to do this if user is initialized. Otherwise it's a new user
3595        // and there are no processes running as the user yet and there's no need
3596        // to make an expensive call to remount processes for the changed permissions.
3597        if (READ_EXTERNAL_STORAGE.equals(name)
3598                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3599            final long token = Binder.clearCallingIdentity();
3600            try {
3601                if (sUserManager.isInitialized(userId)) {
3602                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3603                            MountServiceInternal.class);
3604                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3605                }
3606            } finally {
3607                Binder.restoreCallingIdentity(token);
3608            }
3609        }
3610    }
3611
3612    @Override
3613    public void revokeRuntimePermission(String packageName, String name, int userId) {
3614        if (!sUserManager.exists(userId)) {
3615            Log.e(TAG, "No such user:" + userId);
3616            return;
3617        }
3618
3619        mContext.enforceCallingOrSelfPermission(
3620                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3621                "revokeRuntimePermission");
3622
3623        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3624                "revokeRuntimePermission");
3625
3626        final int appId;
3627
3628        synchronized (mPackages) {
3629            final PackageParser.Package pkg = mPackages.get(packageName);
3630            if (pkg == null) {
3631                throw new IllegalArgumentException("Unknown package: " + packageName);
3632            }
3633
3634            final BasePermission bp = mSettings.mPermissions.get(name);
3635            if (bp == null) {
3636                throw new IllegalArgumentException("Unknown permission: " + name);
3637            }
3638
3639            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3640
3641            SettingBase sb = (SettingBase) pkg.mExtras;
3642            if (sb == null) {
3643                throw new IllegalArgumentException("Unknown package: " + packageName);
3644            }
3645
3646            final PermissionsState permissionsState = sb.getPermissionsState();
3647
3648            final int flags = permissionsState.getPermissionFlags(name, userId);
3649            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3650                throw new SecurityException("Cannot revoke system fixed permission: "
3651                        + name + " for package: " + packageName);
3652            }
3653
3654            if (bp.isDevelopment()) {
3655                // Development permissions must be handled specially, since they are not
3656                // normal runtime permissions.  For now they apply to all users.
3657                if (permissionsState.revokeInstallPermission(bp) !=
3658                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3659                    scheduleWriteSettingsLocked();
3660                }
3661                return;
3662            }
3663
3664            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3665                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3666                return;
3667            }
3668
3669            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3670
3671            // Critical, after this call app should never have the permission.
3672            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3673
3674            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3675        }
3676
3677        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3678    }
3679
3680    @Override
3681    public void resetRuntimePermissions() {
3682        mContext.enforceCallingOrSelfPermission(
3683                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3684                "revokeRuntimePermission");
3685
3686        int callingUid = Binder.getCallingUid();
3687        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3688            mContext.enforceCallingOrSelfPermission(
3689                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3690                    "resetRuntimePermissions");
3691        }
3692
3693        synchronized (mPackages) {
3694            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3695            for (int userId : UserManagerService.getInstance().getUserIds()) {
3696                final int packageCount = mPackages.size();
3697                for (int i = 0; i < packageCount; i++) {
3698                    PackageParser.Package pkg = mPackages.valueAt(i);
3699                    if (!(pkg.mExtras instanceof PackageSetting)) {
3700                        continue;
3701                    }
3702                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3703                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3704                }
3705            }
3706        }
3707    }
3708
3709    @Override
3710    public int getPermissionFlags(String name, String packageName, int userId) {
3711        if (!sUserManager.exists(userId)) {
3712            return 0;
3713        }
3714
3715        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3716
3717        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3718                "getPermissionFlags");
3719
3720        synchronized (mPackages) {
3721            final PackageParser.Package pkg = mPackages.get(packageName);
3722            if (pkg == null) {
3723                throw new IllegalArgumentException("Unknown package: " + packageName);
3724            }
3725
3726            final BasePermission bp = mSettings.mPermissions.get(name);
3727            if (bp == null) {
3728                throw new IllegalArgumentException("Unknown permission: " + name);
3729            }
3730
3731            SettingBase sb = (SettingBase) pkg.mExtras;
3732            if (sb == null) {
3733                throw new IllegalArgumentException("Unknown package: " + packageName);
3734            }
3735
3736            PermissionsState permissionsState = sb.getPermissionsState();
3737            return permissionsState.getPermissionFlags(name, userId);
3738        }
3739    }
3740
3741    @Override
3742    public void updatePermissionFlags(String name, String packageName, int flagMask,
3743            int flagValues, int userId) {
3744        if (!sUserManager.exists(userId)) {
3745            return;
3746        }
3747
3748        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3749
3750        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3751                "updatePermissionFlags");
3752
3753        // Only the system can change these flags and nothing else.
3754        if (getCallingUid() != Process.SYSTEM_UID) {
3755            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3756            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3757            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3758            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3759        }
3760
3761        synchronized (mPackages) {
3762            final PackageParser.Package pkg = mPackages.get(packageName);
3763            if (pkg == null) {
3764                throw new IllegalArgumentException("Unknown package: " + packageName);
3765            }
3766
3767            final BasePermission bp = mSettings.mPermissions.get(name);
3768            if (bp == null) {
3769                throw new IllegalArgumentException("Unknown permission: " + name);
3770            }
3771
3772            SettingBase sb = (SettingBase) pkg.mExtras;
3773            if (sb == null) {
3774                throw new IllegalArgumentException("Unknown package: " + packageName);
3775            }
3776
3777            PermissionsState permissionsState = sb.getPermissionsState();
3778
3779            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3780
3781            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3782                // Install and runtime permissions are stored in different places,
3783                // so figure out what permission changed and persist the change.
3784                if (permissionsState.getInstallPermissionState(name) != null) {
3785                    scheduleWriteSettingsLocked();
3786                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3787                        || hadState) {
3788                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3789                }
3790            }
3791        }
3792    }
3793
3794    /**
3795     * Update the permission flags for all packages and runtime permissions of a user in order
3796     * to allow device or profile owner to remove POLICY_FIXED.
3797     */
3798    @Override
3799    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3800        if (!sUserManager.exists(userId)) {
3801            return;
3802        }
3803
3804        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
3805
3806        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3807                "updatePermissionFlagsForAllApps");
3808
3809        // Only the system can change system fixed flags.
3810        if (getCallingUid() != Process.SYSTEM_UID) {
3811            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3812            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3813        }
3814
3815        synchronized (mPackages) {
3816            boolean changed = false;
3817            final int packageCount = mPackages.size();
3818            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3819                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3820                SettingBase sb = (SettingBase) pkg.mExtras;
3821                if (sb == null) {
3822                    continue;
3823                }
3824                PermissionsState permissionsState = sb.getPermissionsState();
3825                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3826                        userId, flagMask, flagValues);
3827            }
3828            if (changed) {
3829                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3830            }
3831        }
3832    }
3833
3834    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
3835        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
3836                != PackageManager.PERMISSION_GRANTED
3837            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
3838                != PackageManager.PERMISSION_GRANTED) {
3839            throw new SecurityException(message + " requires "
3840                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
3841                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
3842        }
3843    }
3844
3845    @Override
3846    public boolean shouldShowRequestPermissionRationale(String permissionName,
3847            String packageName, int userId) {
3848        if (UserHandle.getCallingUserId() != userId) {
3849            mContext.enforceCallingPermission(
3850                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3851                    "canShowRequestPermissionRationale for user " + userId);
3852        }
3853
3854        final int uid = getPackageUid(packageName, userId);
3855        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3856            return false;
3857        }
3858
3859        if (checkPermission(permissionName, packageName, userId)
3860                == PackageManager.PERMISSION_GRANTED) {
3861            return false;
3862        }
3863
3864        final int flags;
3865
3866        final long identity = Binder.clearCallingIdentity();
3867        try {
3868            flags = getPermissionFlags(permissionName,
3869                    packageName, userId);
3870        } finally {
3871            Binder.restoreCallingIdentity(identity);
3872        }
3873
3874        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3875                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3876                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3877
3878        if ((flags & fixedFlags) != 0) {
3879            return false;
3880        }
3881
3882        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3883    }
3884
3885    @Override
3886    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3887        mContext.enforceCallingOrSelfPermission(
3888                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3889                "addOnPermissionsChangeListener");
3890
3891        synchronized (mPackages) {
3892            mOnPermissionChangeListeners.addListenerLocked(listener);
3893        }
3894    }
3895
3896    @Override
3897    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3898        synchronized (mPackages) {
3899            mOnPermissionChangeListeners.removeListenerLocked(listener);
3900        }
3901    }
3902
3903    @Override
3904    public boolean isProtectedBroadcast(String actionName) {
3905        synchronized (mPackages) {
3906            return mProtectedBroadcasts.contains(actionName);
3907        }
3908    }
3909
3910    @Override
3911    public int checkSignatures(String pkg1, String pkg2) {
3912        synchronized (mPackages) {
3913            final PackageParser.Package p1 = mPackages.get(pkg1);
3914            final PackageParser.Package p2 = mPackages.get(pkg2);
3915            if (p1 == null || p1.mExtras == null
3916                    || p2 == null || p2.mExtras == null) {
3917                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3918            }
3919            return compareSignatures(p1.mSignatures, p2.mSignatures);
3920        }
3921    }
3922
3923    @Override
3924    public int checkUidSignatures(int uid1, int uid2) {
3925        // Map to base uids.
3926        uid1 = UserHandle.getAppId(uid1);
3927        uid2 = UserHandle.getAppId(uid2);
3928        // reader
3929        synchronized (mPackages) {
3930            Signature[] s1;
3931            Signature[] s2;
3932            Object obj = mSettings.getUserIdLPr(uid1);
3933            if (obj != null) {
3934                if (obj instanceof SharedUserSetting) {
3935                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3936                } else if (obj instanceof PackageSetting) {
3937                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3938                } else {
3939                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3940                }
3941            } else {
3942                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3943            }
3944            obj = mSettings.getUserIdLPr(uid2);
3945            if (obj != null) {
3946                if (obj instanceof SharedUserSetting) {
3947                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3948                } else if (obj instanceof PackageSetting) {
3949                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3950                } else {
3951                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3952                }
3953            } else {
3954                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3955            }
3956            return compareSignatures(s1, s2);
3957        }
3958    }
3959
3960    private void killUid(int appId, int userId, String reason) {
3961        final long identity = Binder.clearCallingIdentity();
3962        try {
3963            IActivityManager am = ActivityManagerNative.getDefault();
3964            if (am != null) {
3965                try {
3966                    am.killUid(appId, userId, reason);
3967                } catch (RemoteException e) {
3968                    /* ignore - same process */
3969                }
3970            }
3971        } finally {
3972            Binder.restoreCallingIdentity(identity);
3973        }
3974    }
3975
3976    /**
3977     * Compares two sets of signatures. Returns:
3978     * <br />
3979     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3980     * <br />
3981     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3982     * <br />
3983     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3984     * <br />
3985     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3986     * <br />
3987     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3988     */
3989    static int compareSignatures(Signature[] s1, Signature[] s2) {
3990        if (s1 == null) {
3991            return s2 == null
3992                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3993                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3994        }
3995
3996        if (s2 == null) {
3997            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3998        }
3999
4000        if (s1.length != s2.length) {
4001            return PackageManager.SIGNATURE_NO_MATCH;
4002        }
4003
4004        // Since both signature sets are of size 1, we can compare without HashSets.
4005        if (s1.length == 1) {
4006            return s1[0].equals(s2[0]) ?
4007                    PackageManager.SIGNATURE_MATCH :
4008                    PackageManager.SIGNATURE_NO_MATCH;
4009        }
4010
4011        ArraySet<Signature> set1 = new ArraySet<Signature>();
4012        for (Signature sig : s1) {
4013            set1.add(sig);
4014        }
4015        ArraySet<Signature> set2 = new ArraySet<Signature>();
4016        for (Signature sig : s2) {
4017            set2.add(sig);
4018        }
4019        // Make sure s2 contains all signatures in s1.
4020        if (set1.equals(set2)) {
4021            return PackageManager.SIGNATURE_MATCH;
4022        }
4023        return PackageManager.SIGNATURE_NO_MATCH;
4024    }
4025
4026    /**
4027     * If the database version for this type of package (internal storage or
4028     * external storage) is less than the version where package signatures
4029     * were updated, return true.
4030     */
4031    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4032        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4033        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4034    }
4035
4036    /**
4037     * Used for backward compatibility to make sure any packages with
4038     * certificate chains get upgraded to the new style. {@code existingSigs}
4039     * will be in the old format (since they were stored on disk from before the
4040     * system upgrade) and {@code scannedSigs} will be in the newer format.
4041     */
4042    private int compareSignaturesCompat(PackageSignatures existingSigs,
4043            PackageParser.Package scannedPkg) {
4044        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4045            return PackageManager.SIGNATURE_NO_MATCH;
4046        }
4047
4048        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4049        for (Signature sig : existingSigs.mSignatures) {
4050            existingSet.add(sig);
4051        }
4052        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4053        for (Signature sig : scannedPkg.mSignatures) {
4054            try {
4055                Signature[] chainSignatures = sig.getChainSignatures();
4056                for (Signature chainSig : chainSignatures) {
4057                    scannedCompatSet.add(chainSig);
4058                }
4059            } catch (CertificateEncodingException e) {
4060                scannedCompatSet.add(sig);
4061            }
4062        }
4063        /*
4064         * Make sure the expanded scanned set contains all signatures in the
4065         * existing one.
4066         */
4067        if (scannedCompatSet.equals(existingSet)) {
4068            // Migrate the old signatures to the new scheme.
4069            existingSigs.assignSignatures(scannedPkg.mSignatures);
4070            // The new KeySets will be re-added later in the scanning process.
4071            synchronized (mPackages) {
4072                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4073            }
4074            return PackageManager.SIGNATURE_MATCH;
4075        }
4076        return PackageManager.SIGNATURE_NO_MATCH;
4077    }
4078
4079    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4080        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4081        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4082    }
4083
4084    private int compareSignaturesRecover(PackageSignatures existingSigs,
4085            PackageParser.Package scannedPkg) {
4086        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4087            return PackageManager.SIGNATURE_NO_MATCH;
4088        }
4089
4090        String msg = null;
4091        try {
4092            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4093                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4094                        + scannedPkg.packageName);
4095                return PackageManager.SIGNATURE_MATCH;
4096            }
4097        } catch (CertificateException e) {
4098            msg = e.getMessage();
4099        }
4100
4101        logCriticalInfo(Log.INFO,
4102                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4103        return PackageManager.SIGNATURE_NO_MATCH;
4104    }
4105
4106    @Override
4107    public String[] getPackagesForUid(int uid) {
4108        uid = UserHandle.getAppId(uid);
4109        // reader
4110        synchronized (mPackages) {
4111            Object obj = mSettings.getUserIdLPr(uid);
4112            if (obj instanceof SharedUserSetting) {
4113                final SharedUserSetting sus = (SharedUserSetting) obj;
4114                final int N = sus.packages.size();
4115                final String[] res = new String[N];
4116                final Iterator<PackageSetting> it = sus.packages.iterator();
4117                int i = 0;
4118                while (it.hasNext()) {
4119                    res[i++] = it.next().name;
4120                }
4121                return res;
4122            } else if (obj instanceof PackageSetting) {
4123                final PackageSetting ps = (PackageSetting) obj;
4124                return new String[] { ps.name };
4125            }
4126        }
4127        return null;
4128    }
4129
4130    @Override
4131    public String getNameForUid(int uid) {
4132        // reader
4133        synchronized (mPackages) {
4134            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4135            if (obj instanceof SharedUserSetting) {
4136                final SharedUserSetting sus = (SharedUserSetting) obj;
4137                return sus.name + ":" + sus.userId;
4138            } else if (obj instanceof PackageSetting) {
4139                final PackageSetting ps = (PackageSetting) obj;
4140                return ps.name;
4141            }
4142        }
4143        return null;
4144    }
4145
4146    @Override
4147    public int getUidForSharedUser(String sharedUserName) {
4148        if(sharedUserName == null) {
4149            return -1;
4150        }
4151        // reader
4152        synchronized (mPackages) {
4153            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4154            if (suid == null) {
4155                return -1;
4156            }
4157            return suid.userId;
4158        }
4159    }
4160
4161    @Override
4162    public int getFlagsForUid(int uid) {
4163        synchronized (mPackages) {
4164            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4165            if (obj instanceof SharedUserSetting) {
4166                final SharedUserSetting sus = (SharedUserSetting) obj;
4167                return sus.pkgFlags;
4168            } else if (obj instanceof PackageSetting) {
4169                final PackageSetting ps = (PackageSetting) obj;
4170                return ps.pkgFlags;
4171            }
4172        }
4173        return 0;
4174    }
4175
4176    @Override
4177    public int getPrivateFlagsForUid(int uid) {
4178        synchronized (mPackages) {
4179            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4180            if (obj instanceof SharedUserSetting) {
4181                final SharedUserSetting sus = (SharedUserSetting) obj;
4182                return sus.pkgPrivateFlags;
4183            } else if (obj instanceof PackageSetting) {
4184                final PackageSetting ps = (PackageSetting) obj;
4185                return ps.pkgPrivateFlags;
4186            }
4187        }
4188        return 0;
4189    }
4190
4191    @Override
4192    public boolean isUidPrivileged(int uid) {
4193        uid = UserHandle.getAppId(uid);
4194        // reader
4195        synchronized (mPackages) {
4196            Object obj = mSettings.getUserIdLPr(uid);
4197            if (obj instanceof SharedUserSetting) {
4198                final SharedUserSetting sus = (SharedUserSetting) obj;
4199                final Iterator<PackageSetting> it = sus.packages.iterator();
4200                while (it.hasNext()) {
4201                    if (it.next().isPrivileged()) {
4202                        return true;
4203                    }
4204                }
4205            } else if (obj instanceof PackageSetting) {
4206                final PackageSetting ps = (PackageSetting) obj;
4207                return ps.isPrivileged();
4208            }
4209        }
4210        return false;
4211    }
4212
4213    @Override
4214    public String[] getAppOpPermissionPackages(String permissionName) {
4215        synchronized (mPackages) {
4216            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4217            if (pkgs == null) {
4218                return null;
4219            }
4220            return pkgs.toArray(new String[pkgs.size()]);
4221        }
4222    }
4223
4224    @Override
4225    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4226            int flags, int userId) {
4227        if (!sUserManager.exists(userId)) return null;
4228        flags = augmentFlagsForUser(flags, userId);
4229        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4230        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4231        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4232    }
4233
4234    @Override
4235    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4236            IntentFilter filter, int match, ComponentName activity) {
4237        final int userId = UserHandle.getCallingUserId();
4238        if (DEBUG_PREFERRED) {
4239            Log.v(TAG, "setLastChosenActivity intent=" + intent
4240                + " resolvedType=" + resolvedType
4241                + " flags=" + flags
4242                + " filter=" + filter
4243                + " match=" + match
4244                + " activity=" + activity);
4245            filter.dump(new PrintStreamPrinter(System.out), "    ");
4246        }
4247        intent.setComponent(null);
4248        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4249        // Find any earlier preferred or last chosen entries and nuke them
4250        findPreferredActivity(intent, resolvedType,
4251                flags, query, 0, false, true, false, userId);
4252        // Add the new activity as the last chosen for this filter
4253        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4254                "Setting last chosen");
4255    }
4256
4257    @Override
4258    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4259        final int userId = UserHandle.getCallingUserId();
4260        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4261        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4262        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4263                false, false, false, userId);
4264    }
4265
4266    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4267            int flags, List<ResolveInfo> query, int userId) {
4268        if (query != null) {
4269            final int N = query.size();
4270            if (N == 1) {
4271                return query.get(0);
4272            } else if (N > 1) {
4273                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4274                // If there is more than one activity with the same priority,
4275                // then let the user decide between them.
4276                ResolveInfo r0 = query.get(0);
4277                ResolveInfo r1 = query.get(1);
4278                if (DEBUG_INTENT_MATCHING || debug) {
4279                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4280                            + r1.activityInfo.name + "=" + r1.priority);
4281                }
4282                // If the first activity has a higher priority, or a different
4283                // default, then it is always desireable to pick it.
4284                if (r0.priority != r1.priority
4285                        || r0.preferredOrder != r1.preferredOrder
4286                        || r0.isDefault != r1.isDefault) {
4287                    return query.get(0);
4288                }
4289                // If we have saved a preference for a preferred activity for
4290                // this Intent, use that.
4291                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4292                        flags, query, r0.priority, true, false, debug, userId);
4293                if (ri != null) {
4294                    return ri;
4295                }
4296                ri = new ResolveInfo(mResolveInfo);
4297                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4298                ri.activityInfo.applicationInfo = new ApplicationInfo(
4299                        ri.activityInfo.applicationInfo);
4300                if (userId != 0) {
4301                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4302                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4303                }
4304                // Make sure that the resolver is displayable in car mode
4305                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4306                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4307                return ri;
4308            }
4309        }
4310        return null;
4311    }
4312
4313    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4314            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4315        final int N = query.size();
4316        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4317                .get(userId);
4318        // Get the list of persistent preferred activities that handle the intent
4319        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4320        List<PersistentPreferredActivity> pprefs = ppir != null
4321                ? ppir.queryIntent(intent, resolvedType,
4322                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4323                : null;
4324        if (pprefs != null && pprefs.size() > 0) {
4325            final int M = pprefs.size();
4326            for (int i=0; i<M; i++) {
4327                final PersistentPreferredActivity ppa = pprefs.get(i);
4328                if (DEBUG_PREFERRED || debug) {
4329                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4330                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4331                            + "\n  component=" + ppa.mComponent);
4332                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4333                }
4334                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4335                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4336                if (DEBUG_PREFERRED || debug) {
4337                    Slog.v(TAG, "Found persistent preferred activity:");
4338                    if (ai != null) {
4339                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4340                    } else {
4341                        Slog.v(TAG, "  null");
4342                    }
4343                }
4344                if (ai == null) {
4345                    // This previously registered persistent preferred activity
4346                    // component is no longer known. Ignore it and do NOT remove it.
4347                    continue;
4348                }
4349                for (int j=0; j<N; j++) {
4350                    final ResolveInfo ri = query.get(j);
4351                    if (!ri.activityInfo.applicationInfo.packageName
4352                            .equals(ai.applicationInfo.packageName)) {
4353                        continue;
4354                    }
4355                    if (!ri.activityInfo.name.equals(ai.name)) {
4356                        continue;
4357                    }
4358                    //  Found a persistent preference that can handle the intent.
4359                    if (DEBUG_PREFERRED || debug) {
4360                        Slog.v(TAG, "Returning persistent preferred activity: " +
4361                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4362                    }
4363                    return ri;
4364                }
4365            }
4366        }
4367        return null;
4368    }
4369
4370    // TODO: handle preferred activities missing while user has amnesia
4371    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4372            List<ResolveInfo> query, int priority, boolean always,
4373            boolean removeMatches, boolean debug, int userId) {
4374        if (!sUserManager.exists(userId)) return null;
4375        flags = augmentFlagsForUser(flags, userId);
4376        // writer
4377        synchronized (mPackages) {
4378            if (intent.getSelector() != null) {
4379                intent = intent.getSelector();
4380            }
4381            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4382
4383            // Try to find a matching persistent preferred activity.
4384            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4385                    debug, userId);
4386
4387            // If a persistent preferred activity matched, use it.
4388            if (pri != null) {
4389                return pri;
4390            }
4391
4392            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4393            // Get the list of preferred activities that handle the intent
4394            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4395            List<PreferredActivity> prefs = pir != null
4396                    ? pir.queryIntent(intent, resolvedType,
4397                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4398                    : null;
4399            if (prefs != null && prefs.size() > 0) {
4400                boolean changed = false;
4401                try {
4402                    // First figure out how good the original match set is.
4403                    // We will only allow preferred activities that came
4404                    // from the same match quality.
4405                    int match = 0;
4406
4407                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4408
4409                    final int N = query.size();
4410                    for (int j=0; j<N; j++) {
4411                        final ResolveInfo ri = query.get(j);
4412                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4413                                + ": 0x" + Integer.toHexString(match));
4414                        if (ri.match > match) {
4415                            match = ri.match;
4416                        }
4417                    }
4418
4419                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4420                            + Integer.toHexString(match));
4421
4422                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4423                    final int M = prefs.size();
4424                    for (int i=0; i<M; i++) {
4425                        final PreferredActivity pa = prefs.get(i);
4426                        if (DEBUG_PREFERRED || debug) {
4427                            Slog.v(TAG, "Checking PreferredActivity ds="
4428                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4429                                    + "\n  component=" + pa.mPref.mComponent);
4430                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4431                        }
4432                        if (pa.mPref.mMatch != match) {
4433                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4434                                    + Integer.toHexString(pa.mPref.mMatch));
4435                            continue;
4436                        }
4437                        // If it's not an "always" type preferred activity and that's what we're
4438                        // looking for, skip it.
4439                        if (always && !pa.mPref.mAlways) {
4440                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4441                            continue;
4442                        }
4443                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4444                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4445                        if (DEBUG_PREFERRED || debug) {
4446                            Slog.v(TAG, "Found preferred activity:");
4447                            if (ai != null) {
4448                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4449                            } else {
4450                                Slog.v(TAG, "  null");
4451                            }
4452                        }
4453                        if (ai == null) {
4454                            // This previously registered preferred activity
4455                            // component is no longer known.  Most likely an update
4456                            // to the app was installed and in the new version this
4457                            // component no longer exists.  Clean it up by removing
4458                            // it from the preferred activities list, and skip it.
4459                            Slog.w(TAG, "Removing dangling preferred activity: "
4460                                    + pa.mPref.mComponent);
4461                            pir.removeFilter(pa);
4462                            changed = true;
4463                            continue;
4464                        }
4465                        for (int j=0; j<N; j++) {
4466                            final ResolveInfo ri = query.get(j);
4467                            if (!ri.activityInfo.applicationInfo.packageName
4468                                    .equals(ai.applicationInfo.packageName)) {
4469                                continue;
4470                            }
4471                            if (!ri.activityInfo.name.equals(ai.name)) {
4472                                continue;
4473                            }
4474
4475                            if (removeMatches) {
4476                                pir.removeFilter(pa);
4477                                changed = true;
4478                                if (DEBUG_PREFERRED) {
4479                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4480                                }
4481                                break;
4482                            }
4483
4484                            // Okay we found a previously set preferred or last chosen app.
4485                            // If the result set is different from when this
4486                            // was created, we need to clear it and re-ask the
4487                            // user their preference, if we're looking for an "always" type entry.
4488                            if (always && !pa.mPref.sameSet(query)) {
4489                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4490                                        + intent + " type " + resolvedType);
4491                                if (DEBUG_PREFERRED) {
4492                                    Slog.v(TAG, "Removing preferred activity since set changed "
4493                                            + pa.mPref.mComponent);
4494                                }
4495                                pir.removeFilter(pa);
4496                                // Re-add the filter as a "last chosen" entry (!always)
4497                                PreferredActivity lastChosen = new PreferredActivity(
4498                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4499                                pir.addFilter(lastChosen);
4500                                changed = true;
4501                                return null;
4502                            }
4503
4504                            // Yay! Either the set matched or we're looking for the last chosen
4505                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4506                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4507                            return ri;
4508                        }
4509                    }
4510                } finally {
4511                    if (changed) {
4512                        if (DEBUG_PREFERRED) {
4513                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4514                        }
4515                        scheduleWritePackageRestrictionsLocked(userId);
4516                    }
4517                }
4518            }
4519        }
4520        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4521        return null;
4522    }
4523
4524    /*
4525     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4526     */
4527    @Override
4528    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4529            int targetUserId) {
4530        mContext.enforceCallingOrSelfPermission(
4531                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4532        List<CrossProfileIntentFilter> matches =
4533                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4534        if (matches != null) {
4535            int size = matches.size();
4536            for (int i = 0; i < size; i++) {
4537                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4538            }
4539        }
4540        if (hasWebURI(intent)) {
4541            // cross-profile app linking works only towards the parent.
4542            final UserInfo parent = getProfileParent(sourceUserId);
4543            synchronized(mPackages) {
4544                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4545                        intent, resolvedType, 0, sourceUserId, parent.id);
4546                return xpDomainInfo != null;
4547            }
4548        }
4549        return false;
4550    }
4551
4552    private UserInfo getProfileParent(int userId) {
4553        final long identity = Binder.clearCallingIdentity();
4554        try {
4555            return sUserManager.getProfileParent(userId);
4556        } finally {
4557            Binder.restoreCallingIdentity(identity);
4558        }
4559    }
4560
4561    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4562            String resolvedType, int userId) {
4563        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4564        if (resolver != null) {
4565            return resolver.queryIntent(intent, resolvedType, false, userId);
4566        }
4567        return null;
4568    }
4569
4570    @Override
4571    public List<ResolveInfo> queryIntentActivities(Intent intent,
4572            String resolvedType, int flags, int userId) {
4573        if (!sUserManager.exists(userId)) return Collections.emptyList();
4574        flags = augmentFlagsForUser(flags, userId);
4575        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4576        ComponentName comp = intent.getComponent();
4577        if (comp == null) {
4578            if (intent.getSelector() != null) {
4579                intent = intent.getSelector();
4580                comp = intent.getComponent();
4581            }
4582        }
4583
4584        if (comp != null) {
4585            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4586            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4587            if (ai != null) {
4588                final ResolveInfo ri = new ResolveInfo();
4589                ri.activityInfo = ai;
4590                list.add(ri);
4591            }
4592            return list;
4593        }
4594
4595        // reader
4596        synchronized (mPackages) {
4597            final String pkgName = intent.getPackage();
4598            if (pkgName == null) {
4599                List<CrossProfileIntentFilter> matchingFilters =
4600                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4601                // Check for results that need to skip the current profile.
4602                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4603                        resolvedType, flags, userId);
4604                if (xpResolveInfo != null) {
4605                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4606                    result.add(xpResolveInfo);
4607                    return filterIfNotSystemUser(result, userId);
4608                }
4609
4610                // Check for results in the current profile.
4611                List<ResolveInfo> result = mActivities.queryIntent(
4612                        intent, resolvedType, flags, userId);
4613
4614                // Check for cross profile results.
4615                xpResolveInfo = queryCrossProfileIntents(
4616                        matchingFilters, intent, resolvedType, flags, userId);
4617                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4618                    result.add(xpResolveInfo);
4619                    Collections.sort(result, mResolvePrioritySorter);
4620                }
4621                result = filterIfNotSystemUser(result, userId);
4622                if (hasWebURI(intent)) {
4623                    CrossProfileDomainInfo xpDomainInfo = null;
4624                    final UserInfo parent = getProfileParent(userId);
4625                    if (parent != null) {
4626                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4627                                flags, userId, parent.id);
4628                    }
4629                    if (xpDomainInfo != null) {
4630                        if (xpResolveInfo != null) {
4631                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4632                            // in the result.
4633                            result.remove(xpResolveInfo);
4634                        }
4635                        if (result.size() == 0) {
4636                            result.add(xpDomainInfo.resolveInfo);
4637                            return result;
4638                        }
4639                    } else if (result.size() <= 1) {
4640                        return result;
4641                    }
4642                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4643                            xpDomainInfo, userId);
4644                    Collections.sort(result, mResolvePrioritySorter);
4645                }
4646                return result;
4647            }
4648            final PackageParser.Package pkg = mPackages.get(pkgName);
4649            if (pkg != null) {
4650                return filterIfNotSystemUser(
4651                        mActivities.queryIntentForPackage(
4652                                intent, resolvedType, flags, pkg.activities, userId),
4653                        userId);
4654            }
4655            return new ArrayList<ResolveInfo>();
4656        }
4657    }
4658
4659    private static class CrossProfileDomainInfo {
4660        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4661        ResolveInfo resolveInfo;
4662        /* Best domain verification status of the activities found in the other profile */
4663        int bestDomainVerificationStatus;
4664    }
4665
4666    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4667            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4668        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4669                sourceUserId)) {
4670            return null;
4671        }
4672        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4673                resolvedType, flags, parentUserId);
4674
4675        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4676            return null;
4677        }
4678        CrossProfileDomainInfo result = null;
4679        int size = resultTargetUser.size();
4680        for (int i = 0; i < size; i++) {
4681            ResolveInfo riTargetUser = resultTargetUser.get(i);
4682            // Intent filter verification is only for filters that specify a host. So don't return
4683            // those that handle all web uris.
4684            if (riTargetUser.handleAllWebDataURI) {
4685                continue;
4686            }
4687            String packageName = riTargetUser.activityInfo.packageName;
4688            PackageSetting ps = mSettings.mPackages.get(packageName);
4689            if (ps == null) {
4690                continue;
4691            }
4692            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4693            int status = (int)(verificationState >> 32);
4694            if (result == null) {
4695                result = new CrossProfileDomainInfo();
4696                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
4697                        sourceUserId, parentUserId);
4698                result.bestDomainVerificationStatus = status;
4699            } else {
4700                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4701                        result.bestDomainVerificationStatus);
4702            }
4703        }
4704        // Don't consider matches with status NEVER across profiles.
4705        if (result != null && result.bestDomainVerificationStatus
4706                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4707            return null;
4708        }
4709        return result;
4710    }
4711
4712    /**
4713     * Verification statuses are ordered from the worse to the best, except for
4714     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4715     */
4716    private int bestDomainVerificationStatus(int status1, int status2) {
4717        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4718            return status2;
4719        }
4720        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4721            return status1;
4722        }
4723        return (int) MathUtils.max(status1, status2);
4724    }
4725
4726    private boolean isUserEnabled(int userId) {
4727        long callingId = Binder.clearCallingIdentity();
4728        try {
4729            UserInfo userInfo = sUserManager.getUserInfo(userId);
4730            return userInfo != null && userInfo.isEnabled();
4731        } finally {
4732            Binder.restoreCallingIdentity(callingId);
4733        }
4734    }
4735
4736    /**
4737     * Filter out activities with systemUserOnly flag set, when current user is not System.
4738     *
4739     * @return filtered list
4740     */
4741    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
4742        if (userId == UserHandle.USER_SYSTEM) {
4743            return resolveInfos;
4744        }
4745        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4746            ResolveInfo info = resolveInfos.get(i);
4747            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
4748                resolveInfos.remove(i);
4749            }
4750        }
4751        return resolveInfos;
4752    }
4753
4754    private static boolean hasWebURI(Intent intent) {
4755        if (intent.getData() == null) {
4756            return false;
4757        }
4758        final String scheme = intent.getScheme();
4759        if (TextUtils.isEmpty(scheme)) {
4760            return false;
4761        }
4762        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4763    }
4764
4765    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
4766            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
4767            int userId) {
4768        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
4769
4770        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4771            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
4772                    candidates.size());
4773        }
4774
4775        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4776        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4777        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4778        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
4779        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4780        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4781
4782        synchronized (mPackages) {
4783            final int count = candidates.size();
4784            // First, try to use linked apps. Partition the candidates into four lists:
4785            // one for the final results, one for the "do not use ever", one for "undefined status"
4786            // and finally one for "browser app type".
4787            for (int n=0; n<count; n++) {
4788                ResolveInfo info = candidates.get(n);
4789                String packageName = info.activityInfo.packageName;
4790                PackageSetting ps = mSettings.mPackages.get(packageName);
4791                if (ps != null) {
4792                    // Add to the special match all list (Browser use case)
4793                    if (info.handleAllWebDataURI) {
4794                        matchAllList.add(info);
4795                        continue;
4796                    }
4797                    // Try to get the status from User settings first
4798                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4799                    int status = (int)(packedStatus >> 32);
4800                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
4801                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4802                        if (DEBUG_DOMAIN_VERIFICATION) {
4803                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
4804                                    + " : linkgen=" + linkGeneration);
4805                        }
4806                        // Use link-enabled generation as preferredOrder, i.e.
4807                        // prefer newly-enabled over earlier-enabled.
4808                        info.preferredOrder = linkGeneration;
4809                        alwaysList.add(info);
4810                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4811                        if (DEBUG_DOMAIN_VERIFICATION) {
4812                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4813                        }
4814                        neverList.add(info);
4815                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4816                        if (DEBUG_DOMAIN_VERIFICATION) {
4817                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
4818                        }
4819                        alwaysAskList.add(info);
4820                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4821                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4822                        if (DEBUG_DOMAIN_VERIFICATION) {
4823                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4824                        }
4825                        undefinedList.add(info);
4826                    }
4827                }
4828            }
4829
4830            // We'll want to include browser possibilities in a few cases
4831            boolean includeBrowser = false;
4832
4833            // First try to add the "always" resolution(s) for the current user, if any
4834            if (alwaysList.size() > 0) {
4835                result.addAll(alwaysList);
4836            } else {
4837                // Add all undefined apps as we want them to appear in the disambiguation dialog.
4838                result.addAll(undefinedList);
4839                // Maybe add one for the other profile.
4840                if (xpDomainInfo != null && (
4841                        xpDomainInfo.bestDomainVerificationStatus
4842                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
4843                    result.add(xpDomainInfo.resolveInfo);
4844                }
4845                includeBrowser = true;
4846            }
4847
4848            // The presence of any 'always ask' alternatives means we'll also offer browsers.
4849            // If there were 'always' entries their preferred order has been set, so we also
4850            // back that off to make the alternatives equivalent
4851            if (alwaysAskList.size() > 0) {
4852                for (ResolveInfo i : result) {
4853                    i.preferredOrder = 0;
4854                }
4855                result.addAll(alwaysAskList);
4856                includeBrowser = true;
4857            }
4858
4859            if (includeBrowser) {
4860                // Also add browsers (all of them or only the default one)
4861                if (DEBUG_DOMAIN_VERIFICATION) {
4862                    Slog.v(TAG, "   ...including browsers in candidate set");
4863                }
4864                if ((matchFlags & MATCH_ALL) != 0) {
4865                    result.addAll(matchAllList);
4866                } else {
4867                    // Browser/generic handling case.  If there's a default browser, go straight
4868                    // to that (but only if there is no other higher-priority match).
4869                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
4870                    int maxMatchPrio = 0;
4871                    ResolveInfo defaultBrowserMatch = null;
4872                    final int numCandidates = matchAllList.size();
4873                    for (int n = 0; n < numCandidates; n++) {
4874                        ResolveInfo info = matchAllList.get(n);
4875                        // track the highest overall match priority...
4876                        if (info.priority > maxMatchPrio) {
4877                            maxMatchPrio = info.priority;
4878                        }
4879                        // ...and the highest-priority default browser match
4880                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4881                            if (defaultBrowserMatch == null
4882                                    || (defaultBrowserMatch.priority < info.priority)) {
4883                                if (debug) {
4884                                    Slog.v(TAG, "Considering default browser match " + info);
4885                                }
4886                                defaultBrowserMatch = info;
4887                            }
4888                        }
4889                    }
4890                    if (defaultBrowserMatch != null
4891                            && defaultBrowserMatch.priority >= maxMatchPrio
4892                            && !TextUtils.isEmpty(defaultBrowserPackageName))
4893                    {
4894                        if (debug) {
4895                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
4896                        }
4897                        result.add(defaultBrowserMatch);
4898                    } else {
4899                        result.addAll(matchAllList);
4900                    }
4901                }
4902
4903                // If there is nothing selected, add all candidates and remove the ones that the user
4904                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4905                if (result.size() == 0) {
4906                    result.addAll(candidates);
4907                    result.removeAll(neverList);
4908                }
4909            }
4910        }
4911        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4912            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4913                    result.size());
4914            for (ResolveInfo info : result) {
4915                Slog.v(TAG, "  + " + info.activityInfo);
4916            }
4917        }
4918        return result;
4919    }
4920
4921    // Returns a packed value as a long:
4922    //
4923    // high 'int'-sized word: link status: undefined/ask/never/always.
4924    // low 'int'-sized word: relative priority among 'always' results.
4925    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4926        long result = ps.getDomainVerificationStatusForUser(userId);
4927        // if none available, get the master status
4928        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4929            if (ps.getIntentFilterVerificationInfo() != null) {
4930                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
4931            }
4932        }
4933        return result;
4934    }
4935
4936    private ResolveInfo querySkipCurrentProfileIntents(
4937            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4938            int flags, int sourceUserId) {
4939        if (matchingFilters != null) {
4940            int size = matchingFilters.size();
4941            for (int i = 0; i < size; i ++) {
4942                CrossProfileIntentFilter filter = matchingFilters.get(i);
4943                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4944                    // Checking if there are activities in the target user that can handle the
4945                    // intent.
4946                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
4947                            resolvedType, flags, sourceUserId);
4948                    if (resolveInfo != null) {
4949                        return resolveInfo;
4950                    }
4951                }
4952            }
4953        }
4954        return null;
4955    }
4956
4957    // Return matching ResolveInfo if any for skip current profile intent filters.
4958    private ResolveInfo queryCrossProfileIntents(
4959            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4960            int flags, int sourceUserId) {
4961        if (matchingFilters != null) {
4962            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4963            // match the same intent. For performance reasons, it is better not to
4964            // run queryIntent twice for the same userId
4965            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4966            int size = matchingFilters.size();
4967            for (int i = 0; i < size; i++) {
4968                CrossProfileIntentFilter filter = matchingFilters.get(i);
4969                int targetUserId = filter.getTargetUserId();
4970                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4971                        && !alreadyTriedUserIds.get(targetUserId)) {
4972                    // Checking if there are activities in the target user that can handle the
4973                    // intent.
4974                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
4975                            resolvedType, flags, sourceUserId);
4976                    if (resolveInfo != null) return resolveInfo;
4977                    alreadyTriedUserIds.put(targetUserId, true);
4978                }
4979            }
4980        }
4981        return null;
4982    }
4983
4984    /**
4985     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
4986     * will forward the intent to the filter's target user.
4987     * Otherwise, returns null.
4988     */
4989    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
4990            String resolvedType, int flags, int sourceUserId) {
4991        int targetUserId = filter.getTargetUserId();
4992        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4993                resolvedType, flags, targetUserId);
4994        if (resultTargetUser != null && !resultTargetUser.isEmpty()
4995                && isUserEnabled(targetUserId)) {
4996            return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId);
4997        }
4998        return null;
4999    }
5000
5001    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5002            int sourceUserId, int targetUserId) {
5003        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5004        long ident = Binder.clearCallingIdentity();
5005        boolean targetIsProfile;
5006        try {
5007            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5008        } finally {
5009            Binder.restoreCallingIdentity(ident);
5010        }
5011        String className;
5012        if (targetIsProfile) {
5013            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5014        } else {
5015            className = FORWARD_INTENT_TO_PARENT;
5016        }
5017        ComponentName forwardingActivityComponentName = new ComponentName(
5018                mAndroidApplication.packageName, className);
5019        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5020                sourceUserId);
5021        if (!targetIsProfile) {
5022            forwardingActivityInfo.showUserIcon = targetUserId;
5023            forwardingResolveInfo.noResourceId = true;
5024        }
5025        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5026        forwardingResolveInfo.priority = 0;
5027        forwardingResolveInfo.preferredOrder = 0;
5028        forwardingResolveInfo.match = 0;
5029        forwardingResolveInfo.isDefault = true;
5030        forwardingResolveInfo.filter = filter;
5031        forwardingResolveInfo.targetUserId = targetUserId;
5032        return forwardingResolveInfo;
5033    }
5034
5035    @Override
5036    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5037            Intent[] specifics, String[] specificTypes, Intent intent,
5038            String resolvedType, int flags, int userId) {
5039        if (!sUserManager.exists(userId)) return Collections.emptyList();
5040        flags = augmentFlagsForUser(flags, userId);
5041        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
5042                false, "query intent activity options");
5043        final String resultsAction = intent.getAction();
5044
5045        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
5046                | PackageManager.GET_RESOLVED_FILTER, userId);
5047
5048        if (DEBUG_INTENT_MATCHING) {
5049            Log.v(TAG, "Query " + intent + ": " + results);
5050        }
5051
5052        int specificsPos = 0;
5053        int N;
5054
5055        // todo: note that the algorithm used here is O(N^2).  This
5056        // isn't a problem in our current environment, but if we start running
5057        // into situations where we have more than 5 or 10 matches then this
5058        // should probably be changed to something smarter...
5059
5060        // First we go through and resolve each of the specific items
5061        // that were supplied, taking care of removing any corresponding
5062        // duplicate items in the generic resolve list.
5063        if (specifics != null) {
5064            for (int i=0; i<specifics.length; i++) {
5065                final Intent sintent = specifics[i];
5066                if (sintent == null) {
5067                    continue;
5068                }
5069
5070                if (DEBUG_INTENT_MATCHING) {
5071                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5072                }
5073
5074                String action = sintent.getAction();
5075                if (resultsAction != null && resultsAction.equals(action)) {
5076                    // If this action was explicitly requested, then don't
5077                    // remove things that have it.
5078                    action = null;
5079                }
5080
5081                ResolveInfo ri = null;
5082                ActivityInfo ai = null;
5083
5084                ComponentName comp = sintent.getComponent();
5085                if (comp == null) {
5086                    ri = resolveIntent(
5087                        sintent,
5088                        specificTypes != null ? specificTypes[i] : null,
5089                            flags, userId);
5090                    if (ri == null) {
5091                        continue;
5092                    }
5093                    if (ri == mResolveInfo) {
5094                        // ACK!  Must do something better with this.
5095                    }
5096                    ai = ri.activityInfo;
5097                    comp = new ComponentName(ai.applicationInfo.packageName,
5098                            ai.name);
5099                } else {
5100                    ai = getActivityInfo(comp, flags, userId);
5101                    if (ai == null) {
5102                        continue;
5103                    }
5104                }
5105
5106                // Look for any generic query activities that are duplicates
5107                // of this specific one, and remove them from the results.
5108                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5109                N = results.size();
5110                int j;
5111                for (j=specificsPos; j<N; j++) {
5112                    ResolveInfo sri = results.get(j);
5113                    if ((sri.activityInfo.name.equals(comp.getClassName())
5114                            && sri.activityInfo.applicationInfo.packageName.equals(
5115                                    comp.getPackageName()))
5116                        || (action != null && sri.filter.matchAction(action))) {
5117                        results.remove(j);
5118                        if (DEBUG_INTENT_MATCHING) Log.v(
5119                            TAG, "Removing duplicate item from " + j
5120                            + " due to specific " + specificsPos);
5121                        if (ri == null) {
5122                            ri = sri;
5123                        }
5124                        j--;
5125                        N--;
5126                    }
5127                }
5128
5129                // Add this specific item to its proper place.
5130                if (ri == null) {
5131                    ri = new ResolveInfo();
5132                    ri.activityInfo = ai;
5133                }
5134                results.add(specificsPos, ri);
5135                ri.specificIndex = i;
5136                specificsPos++;
5137            }
5138        }
5139
5140        // Now we go through the remaining generic results and remove any
5141        // duplicate actions that are found here.
5142        N = results.size();
5143        for (int i=specificsPos; i<N-1; i++) {
5144            final ResolveInfo rii = results.get(i);
5145            if (rii.filter == null) {
5146                continue;
5147            }
5148
5149            // Iterate over all of the actions of this result's intent
5150            // filter...  typically this should be just one.
5151            final Iterator<String> it = rii.filter.actionsIterator();
5152            if (it == null) {
5153                continue;
5154            }
5155            while (it.hasNext()) {
5156                final String action = it.next();
5157                if (resultsAction != null && resultsAction.equals(action)) {
5158                    // If this action was explicitly requested, then don't
5159                    // remove things that have it.
5160                    continue;
5161                }
5162                for (int j=i+1; j<N; j++) {
5163                    final ResolveInfo rij = results.get(j);
5164                    if (rij.filter != null && rij.filter.hasAction(action)) {
5165                        results.remove(j);
5166                        if (DEBUG_INTENT_MATCHING) Log.v(
5167                            TAG, "Removing duplicate item from " + j
5168                            + " due to action " + action + " at " + i);
5169                        j--;
5170                        N--;
5171                    }
5172                }
5173            }
5174
5175            // If the caller didn't request filter information, drop it now
5176            // so we don't have to marshall/unmarshall it.
5177            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5178                rii.filter = null;
5179            }
5180        }
5181
5182        // Filter out the caller activity if so requested.
5183        if (caller != null) {
5184            N = results.size();
5185            for (int i=0; i<N; i++) {
5186                ActivityInfo ainfo = results.get(i).activityInfo;
5187                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5188                        && caller.getClassName().equals(ainfo.name)) {
5189                    results.remove(i);
5190                    break;
5191                }
5192            }
5193        }
5194
5195        // If the caller didn't request filter information,
5196        // drop them now so we don't have to
5197        // marshall/unmarshall it.
5198        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5199            N = results.size();
5200            for (int i=0; i<N; i++) {
5201                results.get(i).filter = null;
5202            }
5203        }
5204
5205        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5206        return results;
5207    }
5208
5209    @Override
5210    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5211            int userId) {
5212        if (!sUserManager.exists(userId)) return Collections.emptyList();
5213        flags = augmentFlagsForUser(flags, userId);
5214        ComponentName comp = intent.getComponent();
5215        if (comp == null) {
5216            if (intent.getSelector() != null) {
5217                intent = intent.getSelector();
5218                comp = intent.getComponent();
5219            }
5220        }
5221        if (comp != null) {
5222            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5223            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5224            if (ai != null) {
5225                ResolveInfo ri = new ResolveInfo();
5226                ri.activityInfo = ai;
5227                list.add(ri);
5228            }
5229            return list;
5230        }
5231
5232        // reader
5233        synchronized (mPackages) {
5234            String pkgName = intent.getPackage();
5235            if (pkgName == null) {
5236                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5237            }
5238            final PackageParser.Package pkg = mPackages.get(pkgName);
5239            if (pkg != null) {
5240                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5241                        userId);
5242            }
5243            return null;
5244        }
5245    }
5246
5247    @Override
5248    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5249        if (!sUserManager.exists(userId)) return null;
5250        flags = augmentFlagsForUser(flags, userId);
5251        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5252        if (query != null) {
5253            if (query.size() >= 1) {
5254                // If there is more than one service with the same priority,
5255                // just arbitrarily pick the first one.
5256                return query.get(0);
5257            }
5258        }
5259        return null;
5260    }
5261
5262    @Override
5263    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5264            int userId) {
5265        if (!sUserManager.exists(userId)) return Collections.emptyList();
5266        flags = augmentFlagsForUser(flags, userId);
5267        ComponentName comp = intent.getComponent();
5268        if (comp == null) {
5269            if (intent.getSelector() != null) {
5270                intent = intent.getSelector();
5271                comp = intent.getComponent();
5272            }
5273        }
5274        if (comp != null) {
5275            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5276            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5277            if (si != null) {
5278                final ResolveInfo ri = new ResolveInfo();
5279                ri.serviceInfo = si;
5280                list.add(ri);
5281            }
5282            return list;
5283        }
5284
5285        // reader
5286        synchronized (mPackages) {
5287            String pkgName = intent.getPackage();
5288            if (pkgName == null) {
5289                return mServices.queryIntent(intent, resolvedType, flags, userId);
5290            }
5291            final PackageParser.Package pkg = mPackages.get(pkgName);
5292            if (pkg != null) {
5293                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5294                        userId);
5295            }
5296            return null;
5297        }
5298    }
5299
5300    @Override
5301    public List<ResolveInfo> queryIntentContentProviders(
5302            Intent intent, String resolvedType, int flags, int userId) {
5303        if (!sUserManager.exists(userId)) return Collections.emptyList();
5304        flags = augmentFlagsForUser(flags, userId);
5305        ComponentName comp = intent.getComponent();
5306        if (comp == null) {
5307            if (intent.getSelector() != null) {
5308                intent = intent.getSelector();
5309                comp = intent.getComponent();
5310            }
5311        }
5312        if (comp != null) {
5313            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5314            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5315            if (pi != null) {
5316                final ResolveInfo ri = new ResolveInfo();
5317                ri.providerInfo = pi;
5318                list.add(ri);
5319            }
5320            return list;
5321        }
5322
5323        // reader
5324        synchronized (mPackages) {
5325            String pkgName = intent.getPackage();
5326            if (pkgName == null) {
5327                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5328            }
5329            final PackageParser.Package pkg = mPackages.get(pkgName);
5330            if (pkg != null) {
5331                return mProviders.queryIntentForPackage(
5332                        intent, resolvedType, flags, pkg.providers, userId);
5333            }
5334            return null;
5335        }
5336    }
5337
5338    @Override
5339    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5340        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5341
5342        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5343
5344        // writer
5345        synchronized (mPackages) {
5346            ArrayList<PackageInfo> list;
5347            if (listUninstalled) {
5348                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5349                for (PackageSetting ps : mSettings.mPackages.values()) {
5350                    PackageInfo pi;
5351                    if (ps.pkg != null) {
5352                        pi = generatePackageInfo(ps.pkg, flags, userId);
5353                    } else {
5354                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5355                    }
5356                    if (pi != null) {
5357                        list.add(pi);
5358                    }
5359                }
5360            } else {
5361                list = new ArrayList<PackageInfo>(mPackages.size());
5362                for (PackageParser.Package p : mPackages.values()) {
5363                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5364                    if (pi != null) {
5365                        list.add(pi);
5366                    }
5367                }
5368            }
5369
5370            return new ParceledListSlice<PackageInfo>(list);
5371        }
5372    }
5373
5374    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5375            String[] permissions, boolean[] tmp, int flags, int userId) {
5376        int numMatch = 0;
5377        final PermissionsState permissionsState = ps.getPermissionsState();
5378        for (int i=0; i<permissions.length; i++) {
5379            final String permission = permissions[i];
5380            if (permissionsState.hasPermission(permission, userId)) {
5381                tmp[i] = true;
5382                numMatch++;
5383            } else {
5384                tmp[i] = false;
5385            }
5386        }
5387        if (numMatch == 0) {
5388            return;
5389        }
5390        PackageInfo pi;
5391        if (ps.pkg != null) {
5392            pi = generatePackageInfo(ps.pkg, flags, userId);
5393        } else {
5394            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5395        }
5396        // The above might return null in cases of uninstalled apps or install-state
5397        // skew across users/profiles.
5398        if (pi != null) {
5399            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5400                if (numMatch == permissions.length) {
5401                    pi.requestedPermissions = permissions;
5402                } else {
5403                    pi.requestedPermissions = new String[numMatch];
5404                    numMatch = 0;
5405                    for (int i=0; i<permissions.length; i++) {
5406                        if (tmp[i]) {
5407                            pi.requestedPermissions[numMatch] = permissions[i];
5408                            numMatch++;
5409                        }
5410                    }
5411                }
5412            }
5413            list.add(pi);
5414        }
5415    }
5416
5417    @Override
5418    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5419            String[] permissions, int flags, int userId) {
5420        if (!sUserManager.exists(userId)) return null;
5421        flags = augmentFlagsForUser(flags, userId);
5422        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5423
5424        // writer
5425        synchronized (mPackages) {
5426            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5427            boolean[] tmpBools = new boolean[permissions.length];
5428            if (listUninstalled) {
5429                for (PackageSetting ps : mSettings.mPackages.values()) {
5430                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5431                }
5432            } else {
5433                for (PackageParser.Package pkg : mPackages.values()) {
5434                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5435                    if (ps != null) {
5436                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5437                                userId);
5438                    }
5439                }
5440            }
5441
5442            return new ParceledListSlice<PackageInfo>(list);
5443        }
5444    }
5445
5446    @Override
5447    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5448        if (!sUserManager.exists(userId)) return null;
5449        flags = augmentFlagsForUser(flags, userId);
5450        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5451
5452        // writer
5453        synchronized (mPackages) {
5454            ArrayList<ApplicationInfo> list;
5455            if (listUninstalled) {
5456                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5457                for (PackageSetting ps : mSettings.mPackages.values()) {
5458                    ApplicationInfo ai;
5459                    if (ps.pkg != null) {
5460                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5461                                ps.readUserState(userId), userId);
5462                    } else {
5463                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5464                    }
5465                    if (ai != null) {
5466                        list.add(ai);
5467                    }
5468                }
5469            } else {
5470                list = new ArrayList<ApplicationInfo>(mPackages.size());
5471                for (PackageParser.Package p : mPackages.values()) {
5472                    if (p.mExtras != null) {
5473                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5474                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5475                        if (ai != null) {
5476                            list.add(ai);
5477                        }
5478                    }
5479                }
5480            }
5481
5482            return new ParceledListSlice<ApplicationInfo>(list);
5483        }
5484    }
5485
5486    public List<ApplicationInfo> getPersistentApplications(int flags) {
5487        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5488
5489        // reader
5490        synchronized (mPackages) {
5491            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5492            final int userId = UserHandle.getCallingUserId();
5493            while (i.hasNext()) {
5494                final PackageParser.Package p = i.next();
5495                if (p.applicationInfo != null
5496                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5497                        && (!mSafeMode || isSystemApp(p))) {
5498                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5499                    if (ps != null) {
5500                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5501                                ps.readUserState(userId), userId);
5502                        if (ai != null) {
5503                            finalList.add(ai);
5504                        }
5505                    }
5506                }
5507            }
5508        }
5509
5510        return finalList;
5511    }
5512
5513    @Override
5514    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5515        if (!sUserManager.exists(userId)) return null;
5516        flags = augmentFlagsForUser(flags, userId);
5517        // reader
5518        synchronized (mPackages) {
5519            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5520            PackageSetting ps = provider != null
5521                    ? mSettings.mPackages.get(provider.owner.packageName)
5522                    : null;
5523            return ps != null
5524                    && mSettings.isEnabledAndVisibleLPr(provider.info, flags, userId)
5525                    && (!mSafeMode || (provider.info.applicationInfo.flags
5526                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5527                    ? PackageParser.generateProviderInfo(provider, flags,
5528                            ps.readUserState(userId), userId)
5529                    : null;
5530        }
5531    }
5532
5533    /**
5534     * @deprecated
5535     */
5536    @Deprecated
5537    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5538        // reader
5539        synchronized (mPackages) {
5540            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5541                    .entrySet().iterator();
5542            final int userId = UserHandle.getCallingUserId();
5543            while (i.hasNext()) {
5544                Map.Entry<String, PackageParser.Provider> entry = i.next();
5545                PackageParser.Provider p = entry.getValue();
5546                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5547
5548                if (ps != null && p.syncable
5549                        && (!mSafeMode || (p.info.applicationInfo.flags
5550                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5551                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5552                            ps.readUserState(userId), userId);
5553                    if (info != null) {
5554                        outNames.add(entry.getKey());
5555                        outInfo.add(info);
5556                    }
5557                }
5558            }
5559        }
5560    }
5561
5562    @Override
5563    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
5564            int uid, int flags) {
5565        final int userId = processName != null ? UserHandle.getUserId(uid)
5566                : UserHandle.getCallingUserId();
5567        if (!sUserManager.exists(userId)) return null;
5568        flags = augmentFlagsForUser(flags, userId);
5569
5570        ArrayList<ProviderInfo> finalList = null;
5571        // reader
5572        synchronized (mPackages) {
5573            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5574            while (i.hasNext()) {
5575                final PackageParser.Provider p = i.next();
5576                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5577                if (ps != null && p.info.authority != null
5578                        && (processName == null
5579                                || (p.info.processName.equals(processName)
5580                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5581                        && mSettings.isEnabledAndVisibleLPr(p.info, flags, userId)
5582                        && (!mSafeMode
5583                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5584                    if (finalList == null) {
5585                        finalList = new ArrayList<ProviderInfo>(3);
5586                    }
5587                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5588                            ps.readUserState(userId), userId);
5589                    if (info != null) {
5590                        finalList.add(info);
5591                    }
5592                }
5593            }
5594        }
5595
5596        if (finalList != null) {
5597            Collections.sort(finalList, mProviderInitOrderSorter);
5598            return new ParceledListSlice<ProviderInfo>(finalList);
5599        }
5600
5601        return null;
5602    }
5603
5604    @Override
5605    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5606            int flags) {
5607        // reader
5608        synchronized (mPackages) {
5609            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5610            return PackageParser.generateInstrumentationInfo(i, flags);
5611        }
5612    }
5613
5614    @Override
5615    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5616            int flags) {
5617        ArrayList<InstrumentationInfo> finalList =
5618            new ArrayList<InstrumentationInfo>();
5619
5620        // reader
5621        synchronized (mPackages) {
5622            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5623            while (i.hasNext()) {
5624                final PackageParser.Instrumentation p = i.next();
5625                if (targetPackage == null
5626                        || targetPackage.equals(p.info.targetPackage)) {
5627                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5628                            flags);
5629                    if (ii != null) {
5630                        finalList.add(ii);
5631                    }
5632                }
5633            }
5634        }
5635
5636        return finalList;
5637    }
5638
5639    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5640        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5641        if (overlays == null) {
5642            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5643            return;
5644        }
5645        for (PackageParser.Package opkg : overlays.values()) {
5646            // Not much to do if idmap fails: we already logged the error
5647            // and we certainly don't want to abort installation of pkg simply
5648            // because an overlay didn't fit properly. For these reasons,
5649            // ignore the return value of createIdmapForPackagePairLI.
5650            createIdmapForPackagePairLI(pkg, opkg);
5651        }
5652    }
5653
5654    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5655            PackageParser.Package opkg) {
5656        if (!opkg.mTrustedOverlay) {
5657            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5658                    opkg.baseCodePath + ": overlay not trusted");
5659            return false;
5660        }
5661        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5662        if (overlaySet == null) {
5663            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5664                    opkg.baseCodePath + " but target package has no known overlays");
5665            return false;
5666        }
5667        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5668        // TODO: generate idmap for split APKs
5669        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5670            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5671                    + opkg.baseCodePath);
5672            return false;
5673        }
5674        PackageParser.Package[] overlayArray =
5675            overlaySet.values().toArray(new PackageParser.Package[0]);
5676        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5677            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5678                return p1.mOverlayPriority - p2.mOverlayPriority;
5679            }
5680        };
5681        Arrays.sort(overlayArray, cmp);
5682
5683        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5684        int i = 0;
5685        for (PackageParser.Package p : overlayArray) {
5686            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5687        }
5688        return true;
5689    }
5690
5691    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5692        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
5693        try {
5694            scanDirLI(dir, parseFlags, scanFlags, currentTime);
5695        } finally {
5696            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5697        }
5698    }
5699
5700    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5701        final File[] files = dir.listFiles();
5702        if (ArrayUtils.isEmpty(files)) {
5703            Log.d(TAG, "No files in app dir " + dir);
5704            return;
5705        }
5706
5707        if (DEBUG_PACKAGE_SCANNING) {
5708            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5709                    + " flags=0x" + Integer.toHexString(parseFlags));
5710        }
5711
5712        for (File file : files) {
5713            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5714                    && !PackageInstallerService.isStageName(file.getName());
5715            if (!isPackage) {
5716                // Ignore entries which are not packages
5717                continue;
5718            }
5719            try {
5720                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5721                        scanFlags, currentTime, null);
5722            } catch (PackageManagerException e) {
5723                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5724
5725                // Delete invalid userdata apps
5726                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5727                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5728                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5729                    if (file.isDirectory()) {
5730                        mInstaller.rmPackageDir(file.getAbsolutePath());
5731                    } else {
5732                        file.delete();
5733                    }
5734                }
5735            }
5736        }
5737    }
5738
5739    private static File getSettingsProblemFile() {
5740        File dataDir = Environment.getDataDirectory();
5741        File systemDir = new File(dataDir, "system");
5742        File fname = new File(systemDir, "uiderrors.txt");
5743        return fname;
5744    }
5745
5746    static void reportSettingsProblem(int priority, String msg) {
5747        logCriticalInfo(priority, msg);
5748    }
5749
5750    static void logCriticalInfo(int priority, String msg) {
5751        Slog.println(priority, TAG, msg);
5752        EventLogTags.writePmCriticalInfo(msg);
5753        try {
5754            File fname = getSettingsProblemFile();
5755            FileOutputStream out = new FileOutputStream(fname, true);
5756            PrintWriter pw = new FastPrintWriter(out);
5757            SimpleDateFormat formatter = new SimpleDateFormat();
5758            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5759            pw.println(dateString + ": " + msg);
5760            pw.close();
5761            FileUtils.setPermissions(
5762                    fname.toString(),
5763                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5764                    -1, -1);
5765        } catch (java.io.IOException e) {
5766        }
5767    }
5768
5769    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5770            PackageParser.Package pkg, File srcFile, int parseFlags)
5771            throws PackageManagerException {
5772        if (ps != null
5773                && ps.codePath.equals(srcFile)
5774                && ps.timeStamp == srcFile.lastModified()
5775                && !isCompatSignatureUpdateNeeded(pkg)
5776                && !isRecoverSignatureUpdateNeeded(pkg)) {
5777            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5778            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5779            ArraySet<PublicKey> signingKs;
5780            synchronized (mPackages) {
5781                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5782            }
5783            if (ps.signatures.mSignatures != null
5784                    && ps.signatures.mSignatures.length != 0
5785                    && signingKs != null) {
5786                // Optimization: reuse the existing cached certificates
5787                // if the package appears to be unchanged.
5788                pkg.mSignatures = ps.signatures.mSignatures;
5789                pkg.mSigningKeys = signingKs;
5790                return;
5791            }
5792
5793            Slog.w(TAG, "PackageSetting for " + ps.name
5794                    + " is missing signatures.  Collecting certs again to recover them.");
5795        } else {
5796            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5797        }
5798
5799        try {
5800            pp.collectCertificates(pkg, parseFlags);
5801            pp.collectManifestDigest(pkg);
5802        } catch (PackageParserException e) {
5803            throw PackageManagerException.from(e);
5804        }
5805    }
5806
5807    /**
5808     *  Traces a package scan.
5809     *  @see #scanPackageLI(File, int, int, long, UserHandle)
5810     */
5811    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
5812            long currentTime, UserHandle user) throws PackageManagerException {
5813        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
5814        try {
5815            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
5816        } finally {
5817            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5818        }
5819    }
5820
5821    /**
5822     *  Scans a package and returns the newly parsed package.
5823     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
5824     */
5825    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5826            long currentTime, UserHandle user) throws PackageManagerException {
5827        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5828        parseFlags |= mDefParseFlags;
5829        PackageParser pp = new PackageParser();
5830        pp.setSeparateProcesses(mSeparateProcesses);
5831        pp.setOnlyCoreApps(mOnlyCore);
5832        pp.setDisplayMetrics(mMetrics);
5833
5834        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5835            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5836        }
5837
5838        final PackageParser.Package pkg;
5839        try {
5840            pkg = pp.parsePackage(scanFile, parseFlags);
5841        } catch (PackageParserException e) {
5842            throw PackageManagerException.from(e);
5843        }
5844
5845        PackageSetting ps = null;
5846        PackageSetting updatedPkg;
5847        // reader
5848        synchronized (mPackages) {
5849            // Look to see if we already know about this package.
5850            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5851            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5852                // This package has been renamed to its original name.  Let's
5853                // use that.
5854                ps = mSettings.peekPackageLPr(oldName);
5855            }
5856            // If there was no original package, see one for the real package name.
5857            if (ps == null) {
5858                ps = mSettings.peekPackageLPr(pkg.packageName);
5859            }
5860            // Check to see if this package could be hiding/updating a system
5861            // package.  Must look for it either under the original or real
5862            // package name depending on our state.
5863            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5864            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5865        }
5866        boolean updatedPkgBetter = false;
5867        // First check if this is a system package that may involve an update
5868        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
5869            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5870            // it needs to drop FLAG_PRIVILEGED.
5871            if (locationIsPrivileged(scanFile)) {
5872                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5873            } else {
5874                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5875            }
5876
5877            if (ps != null && !ps.codePath.equals(scanFile)) {
5878                // The path has changed from what was last scanned...  check the
5879                // version of the new path against what we have stored to determine
5880                // what to do.
5881                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5882                if (pkg.mVersionCode <= ps.versionCode) {
5883                    // The system package has been updated and the code path does not match
5884                    // Ignore entry. Skip it.
5885                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5886                            + " ignored: updated version " + ps.versionCode
5887                            + " better than this " + pkg.mVersionCode);
5888                    if (!updatedPkg.codePath.equals(scanFile)) {
5889                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5890                                + ps.name + " changing from " + updatedPkg.codePathString
5891                                + " to " + scanFile);
5892                        updatedPkg.codePath = scanFile;
5893                        updatedPkg.codePathString = scanFile.toString();
5894                        updatedPkg.resourcePath = scanFile;
5895                        updatedPkg.resourcePathString = scanFile.toString();
5896                    }
5897                    updatedPkg.pkg = pkg;
5898                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5899                            "Package " + ps.name + " at " + scanFile
5900                                    + " ignored: updated version " + ps.versionCode
5901                                    + " better than this " + pkg.mVersionCode);
5902                } else {
5903                    // The current app on the system partition is better than
5904                    // what we have updated to on the data partition; switch
5905                    // back to the system partition version.
5906                    // At this point, its safely assumed that package installation for
5907                    // apps in system partition will go through. If not there won't be a working
5908                    // version of the app
5909                    // writer
5910                    synchronized (mPackages) {
5911                        // Just remove the loaded entries from package lists.
5912                        mPackages.remove(ps.name);
5913                    }
5914
5915                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5916                            + " reverting from " + ps.codePathString
5917                            + ": new version " + pkg.mVersionCode
5918                            + " better than installed " + ps.versionCode);
5919
5920                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5921                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5922                    synchronized (mInstallLock) {
5923                        args.cleanUpResourcesLI();
5924                    }
5925                    synchronized (mPackages) {
5926                        mSettings.enableSystemPackageLPw(ps.name);
5927                    }
5928                    updatedPkgBetter = true;
5929                }
5930            }
5931        }
5932
5933        if (updatedPkg != null) {
5934            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5935            // initially
5936            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5937
5938            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5939            // flag set initially
5940            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5941                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5942            }
5943        }
5944
5945        // Verify certificates against what was last scanned
5946        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5947
5948        /*
5949         * A new system app appeared, but we already had a non-system one of the
5950         * same name installed earlier.
5951         */
5952        boolean shouldHideSystemApp = false;
5953        if (updatedPkg == null && ps != null
5954                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5955            /*
5956             * Check to make sure the signatures match first. If they don't,
5957             * wipe the installed application and its data.
5958             */
5959            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5960                    != PackageManager.SIGNATURE_MATCH) {
5961                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5962                        + " signatures don't match existing userdata copy; removing");
5963                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5964                ps = null;
5965            } else {
5966                /*
5967                 * If the newly-added system app is an older version than the
5968                 * already installed version, hide it. It will be scanned later
5969                 * and re-added like an update.
5970                 */
5971                if (pkg.mVersionCode <= ps.versionCode) {
5972                    shouldHideSystemApp = true;
5973                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5974                            + " but new version " + pkg.mVersionCode + " better than installed "
5975                            + ps.versionCode + "; hiding system");
5976                } else {
5977                    /*
5978                     * The newly found system app is a newer version that the
5979                     * one previously installed. Simply remove the
5980                     * already-installed application and replace it with our own
5981                     * while keeping the application data.
5982                     */
5983                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5984                            + " reverting from " + ps.codePathString + ": new version "
5985                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5986                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5987                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5988                    synchronized (mInstallLock) {
5989                        args.cleanUpResourcesLI();
5990                    }
5991                }
5992            }
5993        }
5994
5995        // The apk is forward locked (not public) if its code and resources
5996        // are kept in different files. (except for app in either system or
5997        // vendor path).
5998        // TODO grab this value from PackageSettings
5999        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6000            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6001                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
6002            }
6003        }
6004
6005        // TODO: extend to support forward-locked splits
6006        String resourcePath = null;
6007        String baseResourcePath = null;
6008        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6009            if (ps != null && ps.resourcePathString != null) {
6010                resourcePath = ps.resourcePathString;
6011                baseResourcePath = ps.resourcePathString;
6012            } else {
6013                // Should not happen at all. Just log an error.
6014                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
6015            }
6016        } else {
6017            resourcePath = pkg.codePath;
6018            baseResourcePath = pkg.baseCodePath;
6019        }
6020
6021        // Set application objects path explicitly.
6022        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
6023        pkg.applicationInfo.setCodePath(pkg.codePath);
6024        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
6025        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
6026        pkg.applicationInfo.setResourcePath(resourcePath);
6027        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
6028        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
6029
6030        // Note that we invoke the following method only if we are about to unpack an application
6031        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6032                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6033
6034        /*
6035         * If the system app should be overridden by a previously installed
6036         * data, hide the system app now and let the /data/app scan pick it up
6037         * again.
6038         */
6039        if (shouldHideSystemApp) {
6040            synchronized (mPackages) {
6041                mSettings.disableSystemPackageLPw(pkg.packageName);
6042            }
6043        }
6044
6045        return scannedPkg;
6046    }
6047
6048    private static String fixProcessName(String defProcessName,
6049            String processName, int uid) {
6050        if (processName == null) {
6051            return defProcessName;
6052        }
6053        return processName;
6054    }
6055
6056    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6057            throws PackageManagerException {
6058        if (pkgSetting.signatures.mSignatures != null) {
6059            // Already existing package. Make sure signatures match
6060            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6061                    == PackageManager.SIGNATURE_MATCH;
6062            if (!match) {
6063                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6064                        == PackageManager.SIGNATURE_MATCH;
6065            }
6066            if (!match) {
6067                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6068                        == PackageManager.SIGNATURE_MATCH;
6069            }
6070            if (!match) {
6071                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6072                        + pkg.packageName + " signatures do not match the "
6073                        + "previously installed version; ignoring!");
6074            }
6075        }
6076
6077        // Check for shared user signatures
6078        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6079            // Already existing package. Make sure signatures match
6080            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6081                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6082            if (!match) {
6083                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6084                        == PackageManager.SIGNATURE_MATCH;
6085            }
6086            if (!match) {
6087                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6088                        == PackageManager.SIGNATURE_MATCH;
6089            }
6090            if (!match) {
6091                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6092                        "Package " + pkg.packageName
6093                        + " has no signatures that match those in shared user "
6094                        + pkgSetting.sharedUser.name + "; ignoring!");
6095            }
6096        }
6097    }
6098
6099    /**
6100     * Enforces that only the system UID or root's UID can call a method exposed
6101     * via Binder.
6102     *
6103     * @param message used as message if SecurityException is thrown
6104     * @throws SecurityException if the caller is not system or root
6105     */
6106    private static final void enforceSystemOrRoot(String message) {
6107        final int uid = Binder.getCallingUid();
6108        if (uid != Process.SYSTEM_UID && uid != 0) {
6109            throw new SecurityException(message);
6110        }
6111    }
6112
6113    @Override
6114    public void performFstrimIfNeeded() {
6115        enforceSystemOrRoot("Only the system can request fstrim");
6116
6117        // Before everything else, see whether we need to fstrim.
6118        try {
6119            IMountService ms = PackageHelper.getMountService();
6120            if (ms != null) {
6121                final boolean isUpgrade = isUpgrade();
6122                boolean doTrim = isUpgrade;
6123                if (doTrim) {
6124                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6125                } else {
6126                    final long interval = android.provider.Settings.Global.getLong(
6127                            mContext.getContentResolver(),
6128                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6129                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6130                    if (interval > 0) {
6131                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6132                        if (timeSinceLast > interval) {
6133                            doTrim = true;
6134                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6135                                    + "; running immediately");
6136                        }
6137                    }
6138                }
6139                if (doTrim) {
6140                    if (!isFirstBoot()) {
6141                        try {
6142                            ActivityManagerNative.getDefault().showBootMessage(
6143                                    mContext.getResources().getString(
6144                                            R.string.android_upgrading_fstrim), true);
6145                        } catch (RemoteException e) {
6146                        }
6147                    }
6148                    ms.runMaintenance();
6149                }
6150            } else {
6151                Slog.e(TAG, "Mount service unavailable!");
6152            }
6153        } catch (RemoteException e) {
6154            // Can't happen; MountService is local
6155        }
6156    }
6157
6158    private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) {
6159        List<ResolveInfo> ris = null;
6160        try {
6161            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6162                    intent, null, 0, userId);
6163        } catch (RemoteException e) {
6164        }
6165        ArraySet<String> pkgNames = new ArraySet<String>();
6166        if (ris != null) {
6167            for (ResolveInfo ri : ris) {
6168                pkgNames.add(ri.activityInfo.packageName);
6169            }
6170        }
6171        return pkgNames;
6172    }
6173
6174    @Override
6175    public void notifyPackageUse(String packageName) {
6176        synchronized (mPackages) {
6177            PackageParser.Package p = mPackages.get(packageName);
6178            if (p == null) {
6179                return;
6180            }
6181            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6182        }
6183    }
6184
6185    @Override
6186    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6187        return performDexOptTraced(packageName, instructionSet);
6188    }
6189
6190    public boolean performDexOpt(String packageName, String instructionSet) {
6191        return performDexOptTraced(packageName, instructionSet);
6192    }
6193
6194    private boolean performDexOptTraced(String packageName, String instructionSet) {
6195        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6196        try {
6197            return performDexOptInternal(packageName, instructionSet);
6198        } finally {
6199            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6200        }
6201    }
6202
6203    private boolean performDexOptInternal(String packageName, String instructionSet) {
6204        PackageParser.Package p;
6205        final String targetInstructionSet;
6206        synchronized (mPackages) {
6207            p = mPackages.get(packageName);
6208            if (p == null) {
6209                return false;
6210            }
6211            mPackageUsage.write(false);
6212
6213            targetInstructionSet = instructionSet != null ? instructionSet :
6214                    getPrimaryInstructionSet(p.applicationInfo);
6215            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6216                return false;
6217            }
6218        }
6219        long callingId = Binder.clearCallingIdentity();
6220        try {
6221            synchronized (mInstallLock) {
6222                final String[] instructionSets = new String[] { targetInstructionSet };
6223                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6224                        true /* inclDependencies */);
6225                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6226            }
6227        } finally {
6228            Binder.restoreCallingIdentity(callingId);
6229        }
6230    }
6231
6232    public ArraySet<String> getPackagesThatNeedDexOpt() {
6233        ArraySet<String> pkgs = null;
6234        synchronized (mPackages) {
6235            for (PackageParser.Package p : mPackages.values()) {
6236                if (DEBUG_DEXOPT) {
6237                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6238                }
6239                if (!p.mDexOptPerformed.isEmpty()) {
6240                    continue;
6241                }
6242                if (pkgs == null) {
6243                    pkgs = new ArraySet<String>();
6244                }
6245                pkgs.add(p.packageName);
6246            }
6247        }
6248        return pkgs;
6249    }
6250
6251    public void shutdown() {
6252        mPackageUsage.write(true);
6253    }
6254
6255    @Override
6256    public void forceDexOpt(String packageName) {
6257        enforceSystemOrRoot("forceDexOpt");
6258
6259        PackageParser.Package pkg;
6260        synchronized (mPackages) {
6261            pkg = mPackages.get(packageName);
6262            if (pkg == null) {
6263                throw new IllegalArgumentException("Missing package: " + packageName);
6264            }
6265        }
6266
6267        synchronized (mInstallLock) {
6268            final String[] instructionSets = new String[] {
6269                    getPrimaryInstructionSet(pkg.applicationInfo) };
6270
6271            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6272
6273            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6274                    true /* inclDependencies */);
6275
6276            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6277            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6278                throw new IllegalStateException("Failed to dexopt: " + res);
6279            }
6280        }
6281    }
6282
6283    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6284        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6285            Slog.w(TAG, "Unable to update from " + oldPkg.name
6286                    + " to " + newPkg.packageName
6287                    + ": old package not in system partition");
6288            return false;
6289        } else if (mPackages.get(oldPkg.name) != null) {
6290            Slog.w(TAG, "Unable to update from " + oldPkg.name
6291                    + " to " + newPkg.packageName
6292                    + ": old package still exists");
6293            return false;
6294        }
6295        return true;
6296    }
6297
6298    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6299        int[] users = sUserManager.getUserIds();
6300        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6301        if (res < 0) {
6302            return res;
6303        }
6304        for (int user : users) {
6305            if (user != 0) {
6306                res = mInstaller.createUserData(volumeUuid, packageName,
6307                        UserHandle.getUid(user, uid), user, seinfo);
6308                if (res < 0) {
6309                    return res;
6310                }
6311            }
6312        }
6313        return res;
6314    }
6315
6316    private int removeDataDirsLI(String volumeUuid, String packageName) {
6317        int[] users = sUserManager.getUserIds();
6318        int res = 0;
6319        for (int user : users) {
6320            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6321            if (resInner < 0) {
6322                res = resInner;
6323            }
6324        }
6325
6326        return res;
6327    }
6328
6329    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6330        int[] users = sUserManager.getUserIds();
6331        int res = 0;
6332        for (int user : users) {
6333            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6334            if (resInner < 0) {
6335                res = resInner;
6336            }
6337        }
6338        return res;
6339    }
6340
6341    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6342            PackageParser.Package changingLib) {
6343        if (file.path != null) {
6344            usesLibraryFiles.add(file.path);
6345            return;
6346        }
6347        PackageParser.Package p = mPackages.get(file.apk);
6348        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6349            // If we are doing this while in the middle of updating a library apk,
6350            // then we need to make sure to use that new apk for determining the
6351            // dependencies here.  (We haven't yet finished committing the new apk
6352            // to the package manager state.)
6353            if (p == null || p.packageName.equals(changingLib.packageName)) {
6354                p = changingLib;
6355            }
6356        }
6357        if (p != null) {
6358            usesLibraryFiles.addAll(p.getAllCodePaths());
6359        }
6360    }
6361
6362    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6363            PackageParser.Package changingLib) throws PackageManagerException {
6364        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6365            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6366            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6367            for (int i=0; i<N; i++) {
6368                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6369                if (file == null) {
6370                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6371                            "Package " + pkg.packageName + " requires unavailable shared library "
6372                            + pkg.usesLibraries.get(i) + "; failing!");
6373                }
6374                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6375            }
6376            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6377            for (int i=0; i<N; i++) {
6378                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6379                if (file == null) {
6380                    Slog.w(TAG, "Package " + pkg.packageName
6381                            + " desires unavailable shared library "
6382                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6383                } else {
6384                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6385                }
6386            }
6387            N = usesLibraryFiles.size();
6388            if (N > 0) {
6389                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6390            } else {
6391                pkg.usesLibraryFiles = null;
6392            }
6393        }
6394    }
6395
6396    private static boolean hasString(List<String> list, List<String> which) {
6397        if (list == null) {
6398            return false;
6399        }
6400        for (int i=list.size()-1; i>=0; i--) {
6401            for (int j=which.size()-1; j>=0; j--) {
6402                if (which.get(j).equals(list.get(i))) {
6403                    return true;
6404                }
6405            }
6406        }
6407        return false;
6408    }
6409
6410    private void updateAllSharedLibrariesLPw() {
6411        for (PackageParser.Package pkg : mPackages.values()) {
6412            try {
6413                updateSharedLibrariesLPw(pkg, null);
6414            } catch (PackageManagerException e) {
6415                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6416            }
6417        }
6418    }
6419
6420    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6421            PackageParser.Package changingPkg) {
6422        ArrayList<PackageParser.Package> res = null;
6423        for (PackageParser.Package pkg : mPackages.values()) {
6424            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6425                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6426                if (res == null) {
6427                    res = new ArrayList<PackageParser.Package>();
6428                }
6429                res.add(pkg);
6430                try {
6431                    updateSharedLibrariesLPw(pkg, changingPkg);
6432                } catch (PackageManagerException e) {
6433                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6434                }
6435            }
6436        }
6437        return res;
6438    }
6439
6440    /**
6441     * Derive the value of the {@code cpuAbiOverride} based on the provided
6442     * value and an optional stored value from the package settings.
6443     */
6444    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6445        String cpuAbiOverride = null;
6446
6447        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6448            cpuAbiOverride = null;
6449        } else if (abiOverride != null) {
6450            cpuAbiOverride = abiOverride;
6451        } else if (settings != null) {
6452            cpuAbiOverride = settings.cpuAbiOverrideString;
6453        }
6454
6455        return cpuAbiOverride;
6456    }
6457
6458    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
6459            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6460        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6461        try {
6462            return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
6463        } finally {
6464            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6465        }
6466    }
6467
6468    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6469            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6470        boolean success = false;
6471        try {
6472            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6473                    currentTime, user);
6474            success = true;
6475            return res;
6476        } finally {
6477            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6478                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6479            }
6480        }
6481    }
6482
6483    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6484            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6485        final File scanFile = new File(pkg.codePath);
6486        if (pkg.applicationInfo.getCodePath() == null ||
6487                pkg.applicationInfo.getResourcePath() == null) {
6488            // Bail out. The resource and code paths haven't been set.
6489            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6490                    "Code and resource paths haven't been set correctly");
6491        }
6492
6493        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6494            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6495        } else {
6496            // Only allow system apps to be flagged as core apps.
6497            pkg.coreApp = false;
6498        }
6499
6500        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6501            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6502        }
6503
6504        if (mCustomResolverComponentName != null &&
6505                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6506            setUpCustomResolverActivity(pkg);
6507        }
6508
6509        if (pkg.packageName.equals("android")) {
6510            synchronized (mPackages) {
6511                if (mAndroidApplication != null) {
6512                    Slog.w(TAG, "*************************************************");
6513                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6514                    Slog.w(TAG, " file=" + scanFile);
6515                    Slog.w(TAG, "*************************************************");
6516                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6517                            "Core android package being redefined.  Skipping.");
6518                }
6519
6520                // Set up information for our fall-back user intent resolution activity.
6521                mPlatformPackage = pkg;
6522                pkg.mVersionCode = mSdkVersion;
6523                mAndroidApplication = pkg.applicationInfo;
6524
6525                if (!mResolverReplaced) {
6526                    mResolveActivity.applicationInfo = mAndroidApplication;
6527                    mResolveActivity.name = ResolverActivity.class.getName();
6528                    mResolveActivity.packageName = mAndroidApplication.packageName;
6529                    mResolveActivity.processName = "system:ui";
6530                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6531                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6532                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6533                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6534                    mResolveActivity.exported = true;
6535                    mResolveActivity.enabled = true;
6536                    mResolveInfo.activityInfo = mResolveActivity;
6537                    mResolveInfo.priority = 0;
6538                    mResolveInfo.preferredOrder = 0;
6539                    mResolveInfo.match = 0;
6540                    mResolveComponentName = new ComponentName(
6541                            mAndroidApplication.packageName, mResolveActivity.name);
6542                }
6543            }
6544        }
6545
6546        if (DEBUG_PACKAGE_SCANNING) {
6547            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6548                Log.d(TAG, "Scanning package " + pkg.packageName);
6549        }
6550
6551        if (mPackages.containsKey(pkg.packageName)
6552                || mSharedLibraries.containsKey(pkg.packageName)) {
6553            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6554                    "Application package " + pkg.packageName
6555                    + " already installed.  Skipping duplicate.");
6556        }
6557
6558        // If we're only installing presumed-existing packages, require that the
6559        // scanned APK is both already known and at the path previously established
6560        // for it.  Previously unknown packages we pick up normally, but if we have an
6561        // a priori expectation about this package's install presence, enforce it.
6562        // With a singular exception for new system packages. When an OTA contains
6563        // a new system package, we allow the codepath to change from a system location
6564        // to the user-installed location. If we don't allow this change, any newer,
6565        // user-installed version of the application will be ignored.
6566        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6567            if (mExpectingBetter.containsKey(pkg.packageName)) {
6568                logCriticalInfo(Log.WARN,
6569                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6570            } else {
6571                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6572                if (known != null) {
6573                    if (DEBUG_PACKAGE_SCANNING) {
6574                        Log.d(TAG, "Examining " + pkg.codePath
6575                                + " and requiring known paths " + known.codePathString
6576                                + " & " + known.resourcePathString);
6577                    }
6578                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6579                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6580                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6581                                "Application package " + pkg.packageName
6582                                + " found at " + pkg.applicationInfo.getCodePath()
6583                                + " but expected at " + known.codePathString + "; ignoring.");
6584                    }
6585                }
6586            }
6587        }
6588
6589        // Initialize package source and resource directories
6590        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6591        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6592
6593        SharedUserSetting suid = null;
6594        PackageSetting pkgSetting = null;
6595
6596        if (!isSystemApp(pkg)) {
6597            // Only system apps can use these features.
6598            pkg.mOriginalPackages = null;
6599            pkg.mRealPackage = null;
6600            pkg.mAdoptPermissions = null;
6601        }
6602
6603        // writer
6604        synchronized (mPackages) {
6605            if (pkg.mSharedUserId != null) {
6606                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6607                if (suid == null) {
6608                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6609                            "Creating application package " + pkg.packageName
6610                            + " for shared user failed");
6611                }
6612                if (DEBUG_PACKAGE_SCANNING) {
6613                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6614                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6615                                + "): packages=" + suid.packages);
6616                }
6617            }
6618
6619            // Check if we are renaming from an original package name.
6620            PackageSetting origPackage = null;
6621            String realName = null;
6622            if (pkg.mOriginalPackages != null) {
6623                // This package may need to be renamed to a previously
6624                // installed name.  Let's check on that...
6625                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6626                if (pkg.mOriginalPackages.contains(renamed)) {
6627                    // This package had originally been installed as the
6628                    // original name, and we have already taken care of
6629                    // transitioning to the new one.  Just update the new
6630                    // one to continue using the old name.
6631                    realName = pkg.mRealPackage;
6632                    if (!pkg.packageName.equals(renamed)) {
6633                        // Callers into this function may have already taken
6634                        // care of renaming the package; only do it here if
6635                        // it is not already done.
6636                        pkg.setPackageName(renamed);
6637                    }
6638
6639                } else {
6640                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6641                        if ((origPackage = mSettings.peekPackageLPr(
6642                                pkg.mOriginalPackages.get(i))) != null) {
6643                            // We do have the package already installed under its
6644                            // original name...  should we use it?
6645                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6646                                // New package is not compatible with original.
6647                                origPackage = null;
6648                                continue;
6649                            } else if (origPackage.sharedUser != null) {
6650                                // Make sure uid is compatible between packages.
6651                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6652                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6653                                            + " to " + pkg.packageName + ": old uid "
6654                                            + origPackage.sharedUser.name
6655                                            + " differs from " + pkg.mSharedUserId);
6656                                    origPackage = null;
6657                                    continue;
6658                                }
6659                            } else {
6660                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6661                                        + pkg.packageName + " to old name " + origPackage.name);
6662                            }
6663                            break;
6664                        }
6665                    }
6666                }
6667            }
6668
6669            if (mTransferedPackages.contains(pkg.packageName)) {
6670                Slog.w(TAG, "Package " + pkg.packageName
6671                        + " was transferred to another, but its .apk remains");
6672            }
6673
6674            // Just create the setting, don't add it yet. For already existing packages
6675            // the PkgSetting exists already and doesn't have to be created.
6676            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6677                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6678                    pkg.applicationInfo.primaryCpuAbi,
6679                    pkg.applicationInfo.secondaryCpuAbi,
6680                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6681                    user, false);
6682            if (pkgSetting == null) {
6683                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6684                        "Creating application package " + pkg.packageName + " failed");
6685            }
6686
6687            if (pkgSetting.origPackage != null) {
6688                // If we are first transitioning from an original package,
6689                // fix up the new package's name now.  We need to do this after
6690                // looking up the package under its new name, so getPackageLP
6691                // can take care of fiddling things correctly.
6692                pkg.setPackageName(origPackage.name);
6693
6694                // File a report about this.
6695                String msg = "New package " + pkgSetting.realName
6696                        + " renamed to replace old package " + pkgSetting.name;
6697                reportSettingsProblem(Log.WARN, msg);
6698
6699                // Make a note of it.
6700                mTransferedPackages.add(origPackage.name);
6701
6702                // No longer need to retain this.
6703                pkgSetting.origPackage = null;
6704            }
6705
6706            if (realName != null) {
6707                // Make a note of it.
6708                mTransferedPackages.add(pkg.packageName);
6709            }
6710
6711            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6712                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6713            }
6714
6715            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6716                // Check all shared libraries and map to their actual file path.
6717                // We only do this here for apps not on a system dir, because those
6718                // are the only ones that can fail an install due to this.  We
6719                // will take care of the system apps by updating all of their
6720                // library paths after the scan is done.
6721                updateSharedLibrariesLPw(pkg, null);
6722            }
6723
6724            if (mFoundPolicyFile) {
6725                SELinuxMMAC.assignSeinfoValue(pkg);
6726            }
6727
6728            pkg.applicationInfo.uid = pkgSetting.appId;
6729            pkg.mExtras = pkgSetting;
6730            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6731                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6732                    // We just determined the app is signed correctly, so bring
6733                    // over the latest parsed certs.
6734                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6735                } else {
6736                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6737                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6738                                "Package " + pkg.packageName + " upgrade keys do not match the "
6739                                + "previously installed version");
6740                    } else {
6741                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6742                        String msg = "System package " + pkg.packageName
6743                            + " signature changed; retaining data.";
6744                        reportSettingsProblem(Log.WARN, msg);
6745                    }
6746                }
6747            } else {
6748                try {
6749                    verifySignaturesLP(pkgSetting, pkg);
6750                    // We just determined the app is signed correctly, so bring
6751                    // over the latest parsed certs.
6752                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6753                } catch (PackageManagerException e) {
6754                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6755                        throw e;
6756                    }
6757                    // The signature has changed, but this package is in the system
6758                    // image...  let's recover!
6759                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6760                    // However...  if this package is part of a shared user, but it
6761                    // doesn't match the signature of the shared user, let's fail.
6762                    // What this means is that you can't change the signatures
6763                    // associated with an overall shared user, which doesn't seem all
6764                    // that unreasonable.
6765                    if (pkgSetting.sharedUser != null) {
6766                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6767                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6768                            throw new PackageManagerException(
6769                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6770                                            "Signature mismatch for shared user : "
6771                                            + pkgSetting.sharedUser);
6772                        }
6773                    }
6774                    // File a report about this.
6775                    String msg = "System package " + pkg.packageName
6776                        + " signature changed; retaining data.";
6777                    reportSettingsProblem(Log.WARN, msg);
6778                }
6779            }
6780            // Verify that this new package doesn't have any content providers
6781            // that conflict with existing packages.  Only do this if the
6782            // package isn't already installed, since we don't want to break
6783            // things that are installed.
6784            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6785                final int N = pkg.providers.size();
6786                int i;
6787                for (i=0; i<N; i++) {
6788                    PackageParser.Provider p = pkg.providers.get(i);
6789                    if (p.info.authority != null) {
6790                        String names[] = p.info.authority.split(";");
6791                        for (int j = 0; j < names.length; j++) {
6792                            if (mProvidersByAuthority.containsKey(names[j])) {
6793                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6794                                final String otherPackageName =
6795                                        ((other != null && other.getComponentName() != null) ?
6796                                                other.getComponentName().getPackageName() : "?");
6797                                throw new PackageManagerException(
6798                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6799                                                "Can't install because provider name " + names[j]
6800                                                + " (in package " + pkg.applicationInfo.packageName
6801                                                + ") is already used by " + otherPackageName);
6802                            }
6803                        }
6804                    }
6805                }
6806            }
6807
6808            if (pkg.mAdoptPermissions != null) {
6809                // This package wants to adopt ownership of permissions from
6810                // another package.
6811                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6812                    final String origName = pkg.mAdoptPermissions.get(i);
6813                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6814                    if (orig != null) {
6815                        if (verifyPackageUpdateLPr(orig, pkg)) {
6816                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6817                                    + pkg.packageName);
6818                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6819                        }
6820                    }
6821                }
6822            }
6823        }
6824
6825        final String pkgName = pkg.packageName;
6826
6827        final long scanFileTime = scanFile.lastModified();
6828        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6829        pkg.applicationInfo.processName = fixProcessName(
6830                pkg.applicationInfo.packageName,
6831                pkg.applicationInfo.processName,
6832                pkg.applicationInfo.uid);
6833
6834        if (pkg != mPlatformPackage) {
6835            // This is a normal package, need to make its data directory.
6836            final File dataPath = Environment.getDataUserCredentialEncryptedPackageDirectory(
6837                    pkg.volumeUuid, UserHandle.USER_SYSTEM, pkg.packageName);
6838
6839            boolean uidError = false;
6840            if (dataPath.exists()) {
6841                int currentUid = 0;
6842                try {
6843                    StructStat stat = Os.stat(dataPath.getPath());
6844                    currentUid = stat.st_uid;
6845                } catch (ErrnoException e) {
6846                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6847                }
6848
6849                // If we have mismatched owners for the data path, we have a problem.
6850                if (currentUid != pkg.applicationInfo.uid) {
6851                    boolean recovered = false;
6852                    if (currentUid == 0) {
6853                        // The directory somehow became owned by root.  Wow.
6854                        // This is probably because the system was stopped while
6855                        // installd was in the middle of messing with its libs
6856                        // directory.  Ask installd to fix that.
6857                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6858                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6859                        if (ret >= 0) {
6860                            recovered = true;
6861                            String msg = "Package " + pkg.packageName
6862                                    + " unexpectedly changed to uid 0; recovered to " +
6863                                    + pkg.applicationInfo.uid;
6864                            reportSettingsProblem(Log.WARN, msg);
6865                        }
6866                    }
6867                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6868                            || (scanFlags&SCAN_BOOTING) != 0)) {
6869                        // If this is a system app, we can at least delete its
6870                        // current data so the application will still work.
6871                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6872                        if (ret >= 0) {
6873                            // TODO: Kill the processes first
6874                            // Old data gone!
6875                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6876                                    ? "System package " : "Third party package ";
6877                            String msg = prefix + pkg.packageName
6878                                    + " has changed from uid: "
6879                                    + currentUid + " to "
6880                                    + pkg.applicationInfo.uid + "; old data erased";
6881                            reportSettingsProblem(Log.WARN, msg);
6882                            recovered = true;
6883
6884                            // And now re-install the app.
6885                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6886                                    pkg.applicationInfo.seinfo);
6887                            if (ret == -1) {
6888                                // Ack should not happen!
6889                                msg = prefix + pkg.packageName
6890                                        + " could not have data directory re-created after delete.";
6891                                reportSettingsProblem(Log.WARN, msg);
6892                                throw new PackageManagerException(
6893                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6894                            }
6895                        }
6896                        if (!recovered) {
6897                            mHasSystemUidErrors = true;
6898                        }
6899                    } else if (!recovered) {
6900                        // If we allow this install to proceed, we will be broken.
6901                        // Abort, abort!
6902                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6903                                "scanPackageLI");
6904                    }
6905                    if (!recovered) {
6906                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6907                            + pkg.applicationInfo.uid + "/fs_"
6908                            + currentUid;
6909                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6910                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6911                        String msg = "Package " + pkg.packageName
6912                                + " has mismatched uid: "
6913                                + currentUid + " on disk, "
6914                                + pkg.applicationInfo.uid + " in settings";
6915                        // writer
6916                        synchronized (mPackages) {
6917                            mSettings.mReadMessages.append(msg);
6918                            mSettings.mReadMessages.append('\n');
6919                            uidError = true;
6920                            if (!pkgSetting.uidError) {
6921                                reportSettingsProblem(Log.ERROR, msg);
6922                            }
6923                        }
6924                    }
6925                }
6926
6927                if (mShouldRestoreconData) {
6928                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6929                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6930                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6931                }
6932            } else {
6933                if (DEBUG_PACKAGE_SCANNING) {
6934                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6935                        Log.v(TAG, "Want this data dir: " + dataPath);
6936                }
6937                //invoke installer to do the actual installation
6938                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6939                        pkg.applicationInfo.seinfo);
6940                if (ret < 0) {
6941                    // Error from installer
6942                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6943                            "Unable to create data dirs [errorCode=" + ret + "]");
6944                }
6945            }
6946
6947            // Get all of our default paths setup
6948            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
6949
6950            pkgSetting.uidError = uidError;
6951        }
6952
6953        final String path = scanFile.getPath();
6954        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6955
6956        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6957            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6958
6959            // Some system apps still use directory structure for native libraries
6960            // in which case we might end up not detecting abi solely based on apk
6961            // structure. Try to detect abi based on directory structure.
6962            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6963                    pkg.applicationInfo.primaryCpuAbi == null) {
6964                setBundledAppAbisAndRoots(pkg, pkgSetting);
6965                setNativeLibraryPaths(pkg);
6966            }
6967
6968        } else {
6969            if ((scanFlags & SCAN_MOVE) != 0) {
6970                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6971                // but we already have this packages package info in the PackageSetting. We just
6972                // use that and derive the native library path based on the new codepath.
6973                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6974                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6975            }
6976
6977            // Set native library paths again. For moves, the path will be updated based on the
6978            // ABIs we've determined above. For non-moves, the path will be updated based on the
6979            // ABIs we determined during compilation, but the path will depend on the final
6980            // package path (after the rename away from the stage path).
6981            setNativeLibraryPaths(pkg);
6982        }
6983
6984        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6985        final int[] userIds = sUserManager.getUserIds();
6986        synchronized (mInstallLock) {
6987            // Make sure all user data directories are ready to roll; we're okay
6988            // if they already exist
6989            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
6990                for (int userId : userIds) {
6991                    if (userId != UserHandle.USER_SYSTEM) {
6992                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
6993                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
6994                                pkg.applicationInfo.seinfo);
6995                    }
6996                }
6997            }
6998
6999            // Create a native library symlink only if we have native libraries
7000            // and if the native libraries are 32 bit libraries. We do not provide
7001            // this symlink for 64 bit libraries.
7002            if (pkg.applicationInfo.primaryCpuAbi != null &&
7003                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
7004                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib");
7005                try {
7006                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
7007                    for (int userId : userIds) {
7008                        if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
7009                                nativeLibPath, userId) < 0) {
7010                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7011                                    "Failed linking native library dir (user=" + userId + ")");
7012                        }
7013                    }
7014                } finally {
7015                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7016                }
7017            }
7018        }
7019
7020        // This is a special case for the "system" package, where the ABI is
7021        // dictated by the zygote configuration (and init.rc). We should keep track
7022        // of this ABI so that we can deal with "normal" applications that run under
7023        // the same UID correctly.
7024        if (mPlatformPackage == pkg) {
7025            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7026                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7027        }
7028
7029        // If there's a mismatch between the abi-override in the package setting
7030        // and the abiOverride specified for the install. Warn about this because we
7031        // would've already compiled the app without taking the package setting into
7032        // account.
7033        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7034            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7035                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7036                        " for package: " + pkg.packageName);
7037            }
7038        }
7039
7040        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7041        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7042        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7043
7044        // Copy the derived override back to the parsed package, so that we can
7045        // update the package settings accordingly.
7046        pkg.cpuAbiOverride = cpuAbiOverride;
7047
7048        if (DEBUG_ABI_SELECTION) {
7049            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7050                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7051                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7052        }
7053
7054        // Push the derived path down into PackageSettings so we know what to
7055        // clean up at uninstall time.
7056        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7057
7058        if (DEBUG_ABI_SELECTION) {
7059            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7060                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7061                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7062        }
7063
7064        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7065            // We don't do this here during boot because we can do it all
7066            // at once after scanning all existing packages.
7067            //
7068            // We also do this *before* we perform dexopt on this package, so that
7069            // we can avoid redundant dexopts, and also to make sure we've got the
7070            // code and package path correct.
7071            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7072                    pkg, true /* boot complete */);
7073        }
7074
7075        if (mFactoryTest && pkg.requestedPermissions.contains(
7076                android.Manifest.permission.FACTORY_TEST)) {
7077            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7078        }
7079
7080        ArrayList<PackageParser.Package> clientLibPkgs = null;
7081
7082        // writer
7083        synchronized (mPackages) {
7084            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7085                // Only system apps can add new shared libraries.
7086                if (pkg.libraryNames != null) {
7087                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7088                        String name = pkg.libraryNames.get(i);
7089                        boolean allowed = false;
7090                        if (pkg.isUpdatedSystemApp()) {
7091                            // New library entries can only be added through the
7092                            // system image.  This is important to get rid of a lot
7093                            // of nasty edge cases: for example if we allowed a non-
7094                            // system update of the app to add a library, then uninstalling
7095                            // the update would make the library go away, and assumptions
7096                            // we made such as through app install filtering would now
7097                            // have allowed apps on the device which aren't compatible
7098                            // with it.  Better to just have the restriction here, be
7099                            // conservative, and create many fewer cases that can negatively
7100                            // impact the user experience.
7101                            final PackageSetting sysPs = mSettings
7102                                    .getDisabledSystemPkgLPr(pkg.packageName);
7103                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7104                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7105                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7106                                        allowed = true;
7107                                        break;
7108                                    }
7109                                }
7110                            }
7111                        } else {
7112                            allowed = true;
7113                        }
7114                        if (allowed) {
7115                            if (!mSharedLibraries.containsKey(name)) {
7116                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7117                            } else if (!name.equals(pkg.packageName)) {
7118                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7119                                        + name + " already exists; skipping");
7120                            }
7121                        } else {
7122                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7123                                    + name + " that is not declared on system image; skipping");
7124                        }
7125                    }
7126                    if ((scanFlags & SCAN_BOOTING) == 0) {
7127                        // If we are not booting, we need to update any applications
7128                        // that are clients of our shared library.  If we are booting,
7129                        // this will all be done once the scan is complete.
7130                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7131                    }
7132                }
7133            }
7134        }
7135
7136        // Request the ActivityManager to kill the process(only for existing packages)
7137        // so that we do not end up in a confused state while the user is still using the older
7138        // version of the application while the new one gets installed.
7139        if ((scanFlags & SCAN_REPLACING) != 0) {
7140            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
7141
7142            killApplication(pkg.applicationInfo.packageName,
7143                        pkg.applicationInfo.uid, "replace pkg");
7144
7145            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7146        }
7147
7148        // Also need to kill any apps that are dependent on the library.
7149        if (clientLibPkgs != null) {
7150            for (int i=0; i<clientLibPkgs.size(); i++) {
7151                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7152                killApplication(clientPkg.applicationInfo.packageName,
7153                        clientPkg.applicationInfo.uid, "update lib");
7154            }
7155        }
7156
7157        // Make sure we're not adding any bogus keyset info
7158        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7159        ksms.assertScannedPackageValid(pkg);
7160
7161        // writer
7162        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
7163
7164        boolean createIdmapFailed = false;
7165        synchronized (mPackages) {
7166            // We don't expect installation to fail beyond this point
7167
7168            // Add the new setting to mSettings
7169            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7170            // Add the new setting to mPackages
7171            mPackages.put(pkg.applicationInfo.packageName, pkg);
7172            // Make sure we don't accidentally delete its data.
7173            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7174            while (iter.hasNext()) {
7175                PackageCleanItem item = iter.next();
7176                if (pkgName.equals(item.packageName)) {
7177                    iter.remove();
7178                }
7179            }
7180
7181            // Take care of first install / last update times.
7182            if (currentTime != 0) {
7183                if (pkgSetting.firstInstallTime == 0) {
7184                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7185                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7186                    pkgSetting.lastUpdateTime = currentTime;
7187                }
7188            } else if (pkgSetting.firstInstallTime == 0) {
7189                // We need *something*.  Take time time stamp of the file.
7190                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7191            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7192                if (scanFileTime != pkgSetting.timeStamp) {
7193                    // A package on the system image has changed; consider this
7194                    // to be an update.
7195                    pkgSetting.lastUpdateTime = scanFileTime;
7196                }
7197            }
7198
7199            // Add the package's KeySets to the global KeySetManagerService
7200            ksms.addScannedPackageLPw(pkg);
7201
7202            int N = pkg.providers.size();
7203            StringBuilder r = null;
7204            int i;
7205            for (i=0; i<N; i++) {
7206                PackageParser.Provider p = pkg.providers.get(i);
7207                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7208                        p.info.processName, pkg.applicationInfo.uid);
7209                mProviders.addProvider(p);
7210                p.syncable = p.info.isSyncable;
7211                if (p.info.authority != null) {
7212                    String names[] = p.info.authority.split(";");
7213                    p.info.authority = null;
7214                    for (int j = 0; j < names.length; j++) {
7215                        if (j == 1 && p.syncable) {
7216                            // We only want the first authority for a provider to possibly be
7217                            // syncable, so if we already added this provider using a different
7218                            // authority clear the syncable flag. We copy the provider before
7219                            // changing it because the mProviders object contains a reference
7220                            // to a provider that we don't want to change.
7221                            // Only do this for the second authority since the resulting provider
7222                            // object can be the same for all future authorities for this provider.
7223                            p = new PackageParser.Provider(p);
7224                            p.syncable = false;
7225                        }
7226                        if (!mProvidersByAuthority.containsKey(names[j])) {
7227                            mProvidersByAuthority.put(names[j], p);
7228                            if (p.info.authority == null) {
7229                                p.info.authority = names[j];
7230                            } else {
7231                                p.info.authority = p.info.authority + ";" + names[j];
7232                            }
7233                            if (DEBUG_PACKAGE_SCANNING) {
7234                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7235                                    Log.d(TAG, "Registered content provider: " + names[j]
7236                                            + ", className = " + p.info.name + ", isSyncable = "
7237                                            + p.info.isSyncable);
7238                            }
7239                        } else {
7240                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7241                            Slog.w(TAG, "Skipping provider name " + names[j] +
7242                                    " (in package " + pkg.applicationInfo.packageName +
7243                                    "): name already used by "
7244                                    + ((other != null && other.getComponentName() != null)
7245                                            ? other.getComponentName().getPackageName() : "?"));
7246                        }
7247                    }
7248                }
7249                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7250                    if (r == null) {
7251                        r = new StringBuilder(256);
7252                    } else {
7253                        r.append(' ');
7254                    }
7255                    r.append(p.info.name);
7256                }
7257            }
7258            if (r != null) {
7259                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7260            }
7261
7262            N = pkg.services.size();
7263            r = null;
7264            for (i=0; i<N; i++) {
7265                PackageParser.Service s = pkg.services.get(i);
7266                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7267                        s.info.processName, pkg.applicationInfo.uid);
7268                mServices.addService(s);
7269                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7270                    if (r == null) {
7271                        r = new StringBuilder(256);
7272                    } else {
7273                        r.append(' ');
7274                    }
7275                    r.append(s.info.name);
7276                }
7277            }
7278            if (r != null) {
7279                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7280            }
7281
7282            N = pkg.receivers.size();
7283            r = null;
7284            for (i=0; i<N; i++) {
7285                PackageParser.Activity a = pkg.receivers.get(i);
7286                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7287                        a.info.processName, pkg.applicationInfo.uid);
7288                mReceivers.addActivity(a, "receiver");
7289                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7290                    if (r == null) {
7291                        r = new StringBuilder(256);
7292                    } else {
7293                        r.append(' ');
7294                    }
7295                    r.append(a.info.name);
7296                }
7297            }
7298            if (r != null) {
7299                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7300            }
7301
7302            N = pkg.activities.size();
7303            r = null;
7304            for (i=0; i<N; i++) {
7305                PackageParser.Activity a = pkg.activities.get(i);
7306                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7307                        a.info.processName, pkg.applicationInfo.uid);
7308                mActivities.addActivity(a, "activity");
7309                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7310                    if (r == null) {
7311                        r = new StringBuilder(256);
7312                    } else {
7313                        r.append(' ');
7314                    }
7315                    r.append(a.info.name);
7316                }
7317            }
7318            if (r != null) {
7319                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7320            }
7321
7322            N = pkg.permissionGroups.size();
7323            r = null;
7324            for (i=0; i<N; i++) {
7325                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7326                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7327                if (cur == null) {
7328                    mPermissionGroups.put(pg.info.name, pg);
7329                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7330                        if (r == null) {
7331                            r = new StringBuilder(256);
7332                        } else {
7333                            r.append(' ');
7334                        }
7335                        r.append(pg.info.name);
7336                    }
7337                } else {
7338                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7339                            + pg.info.packageName + " ignored: original from "
7340                            + cur.info.packageName);
7341                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7342                        if (r == null) {
7343                            r = new StringBuilder(256);
7344                        } else {
7345                            r.append(' ');
7346                        }
7347                        r.append("DUP:");
7348                        r.append(pg.info.name);
7349                    }
7350                }
7351            }
7352            if (r != null) {
7353                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7354            }
7355
7356            N = pkg.permissions.size();
7357            r = null;
7358            for (i=0; i<N; i++) {
7359                PackageParser.Permission p = pkg.permissions.get(i);
7360
7361                // Assume by default that we did not install this permission into the system.
7362                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7363
7364                // Now that permission groups have a special meaning, we ignore permission
7365                // groups for legacy apps to prevent unexpected behavior. In particular,
7366                // permissions for one app being granted to someone just becuase they happen
7367                // to be in a group defined by another app (before this had no implications).
7368                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7369                    p.group = mPermissionGroups.get(p.info.group);
7370                    // Warn for a permission in an unknown group.
7371                    if (p.info.group != null && p.group == null) {
7372                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7373                                + p.info.packageName + " in an unknown group " + p.info.group);
7374                    }
7375                }
7376
7377                ArrayMap<String, BasePermission> permissionMap =
7378                        p.tree ? mSettings.mPermissionTrees
7379                                : mSettings.mPermissions;
7380                BasePermission bp = permissionMap.get(p.info.name);
7381
7382                // Allow system apps to redefine non-system permissions
7383                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7384                    final boolean currentOwnerIsSystem = (bp.perm != null
7385                            && isSystemApp(bp.perm.owner));
7386                    if (isSystemApp(p.owner)) {
7387                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7388                            // It's a built-in permission and no owner, take ownership now
7389                            bp.packageSetting = pkgSetting;
7390                            bp.perm = p;
7391                            bp.uid = pkg.applicationInfo.uid;
7392                            bp.sourcePackage = p.info.packageName;
7393                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7394                        } else if (!currentOwnerIsSystem) {
7395                            String msg = "New decl " + p.owner + " of permission  "
7396                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7397                            reportSettingsProblem(Log.WARN, msg);
7398                            bp = null;
7399                        }
7400                    }
7401                }
7402
7403                if (bp == null) {
7404                    bp = new BasePermission(p.info.name, p.info.packageName,
7405                            BasePermission.TYPE_NORMAL);
7406                    permissionMap.put(p.info.name, bp);
7407                }
7408
7409                if (bp.perm == null) {
7410                    if (bp.sourcePackage == null
7411                            || bp.sourcePackage.equals(p.info.packageName)) {
7412                        BasePermission tree = findPermissionTreeLP(p.info.name);
7413                        if (tree == null
7414                                || tree.sourcePackage.equals(p.info.packageName)) {
7415                            bp.packageSetting = pkgSetting;
7416                            bp.perm = p;
7417                            bp.uid = pkg.applicationInfo.uid;
7418                            bp.sourcePackage = p.info.packageName;
7419                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7420                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7421                                if (r == null) {
7422                                    r = new StringBuilder(256);
7423                                } else {
7424                                    r.append(' ');
7425                                }
7426                                r.append(p.info.name);
7427                            }
7428                        } else {
7429                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7430                                    + p.info.packageName + " ignored: base tree "
7431                                    + tree.name + " is from package "
7432                                    + tree.sourcePackage);
7433                        }
7434                    } else {
7435                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7436                                + p.info.packageName + " ignored: original from "
7437                                + bp.sourcePackage);
7438                    }
7439                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7440                    if (r == null) {
7441                        r = new StringBuilder(256);
7442                    } else {
7443                        r.append(' ');
7444                    }
7445                    r.append("DUP:");
7446                    r.append(p.info.name);
7447                }
7448                if (bp.perm == p) {
7449                    bp.protectionLevel = p.info.protectionLevel;
7450                }
7451            }
7452
7453            if (r != null) {
7454                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7455            }
7456
7457            N = pkg.instrumentation.size();
7458            r = null;
7459            for (i=0; i<N; i++) {
7460                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7461                a.info.packageName = pkg.applicationInfo.packageName;
7462                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7463                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7464                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7465                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7466                a.info.dataDir = pkg.applicationInfo.dataDir;
7467                a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir;
7468                a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir;
7469
7470                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7471                // need other information about the application, like the ABI and what not ?
7472                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7473                mInstrumentation.put(a.getComponentName(), a);
7474                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7475                    if (r == null) {
7476                        r = new StringBuilder(256);
7477                    } else {
7478                        r.append(' ');
7479                    }
7480                    r.append(a.info.name);
7481                }
7482            }
7483            if (r != null) {
7484                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7485            }
7486
7487            if (pkg.protectedBroadcasts != null) {
7488                N = pkg.protectedBroadcasts.size();
7489                for (i=0; i<N; i++) {
7490                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7491                }
7492            }
7493
7494            pkgSetting.setTimeStamp(scanFileTime);
7495
7496            // Create idmap files for pairs of (packages, overlay packages).
7497            // Note: "android", ie framework-res.apk, is handled by native layers.
7498            if (pkg.mOverlayTarget != null) {
7499                // This is an overlay package.
7500                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7501                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7502                        mOverlays.put(pkg.mOverlayTarget,
7503                                new ArrayMap<String, PackageParser.Package>());
7504                    }
7505                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7506                    map.put(pkg.packageName, pkg);
7507                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7508                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7509                        createIdmapFailed = true;
7510                    }
7511                }
7512            } else if (mOverlays.containsKey(pkg.packageName) &&
7513                    !pkg.packageName.equals("android")) {
7514                // This is a regular package, with one or more known overlay packages.
7515                createIdmapsForPackageLI(pkg);
7516            }
7517        }
7518
7519        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7520
7521        if (createIdmapFailed) {
7522            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7523                    "scanPackageLI failed to createIdmap");
7524        }
7525        return pkg;
7526    }
7527
7528    /**
7529     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7530     * is derived purely on the basis of the contents of {@code scanFile} and
7531     * {@code cpuAbiOverride}.
7532     *
7533     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7534     */
7535    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7536                                 String cpuAbiOverride, boolean extractLibs)
7537            throws PackageManagerException {
7538        // TODO: We can probably be smarter about this stuff. For installed apps,
7539        // we can calculate this information at install time once and for all. For
7540        // system apps, we can probably assume that this information doesn't change
7541        // after the first boot scan. As things stand, we do lots of unnecessary work.
7542
7543        // Give ourselves some initial paths; we'll come back for another
7544        // pass once we've determined ABI below.
7545        setNativeLibraryPaths(pkg);
7546
7547        // We would never need to extract libs for forward-locked and external packages,
7548        // since the container service will do it for us. We shouldn't attempt to
7549        // extract libs from system app when it was not updated.
7550        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
7551                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
7552            extractLibs = false;
7553        }
7554
7555        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7556        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7557
7558        NativeLibraryHelper.Handle handle = null;
7559        try {
7560            handle = NativeLibraryHelper.Handle.create(pkg);
7561            // TODO(multiArch): This can be null for apps that didn't go through the
7562            // usual installation process. We can calculate it again, like we
7563            // do during install time.
7564            //
7565            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7566            // unnecessary.
7567            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7568
7569            // Null out the abis so that they can be recalculated.
7570            pkg.applicationInfo.primaryCpuAbi = null;
7571            pkg.applicationInfo.secondaryCpuAbi = null;
7572            if (isMultiArch(pkg.applicationInfo)) {
7573                // Warn if we've set an abiOverride for multi-lib packages..
7574                // By definition, we need to copy both 32 and 64 bit libraries for
7575                // such packages.
7576                if (pkg.cpuAbiOverride != null
7577                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7578                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7579                }
7580
7581                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7582                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7583                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7584                    if (extractLibs) {
7585                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7586                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7587                                useIsaSpecificSubdirs);
7588                    } else {
7589                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7590                    }
7591                }
7592
7593                maybeThrowExceptionForMultiArchCopy(
7594                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7595
7596                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7597                    if (extractLibs) {
7598                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7599                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7600                                useIsaSpecificSubdirs);
7601                    } else {
7602                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7603                    }
7604                }
7605
7606                maybeThrowExceptionForMultiArchCopy(
7607                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7608
7609                if (abi64 >= 0) {
7610                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7611                }
7612
7613                if (abi32 >= 0) {
7614                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7615                    if (abi64 >= 0) {
7616                        pkg.applicationInfo.secondaryCpuAbi = abi;
7617                    } else {
7618                        pkg.applicationInfo.primaryCpuAbi = abi;
7619                    }
7620                }
7621            } else {
7622                String[] abiList = (cpuAbiOverride != null) ?
7623                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7624
7625                // Enable gross and lame hacks for apps that are built with old
7626                // SDK tools. We must scan their APKs for renderscript bitcode and
7627                // not launch them if it's present. Don't bother checking on devices
7628                // that don't have 64 bit support.
7629                boolean needsRenderScriptOverride = false;
7630                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7631                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7632                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7633                    needsRenderScriptOverride = true;
7634                }
7635
7636                final int copyRet;
7637                if (extractLibs) {
7638                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7639                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7640                } else {
7641                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7642                }
7643
7644                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7645                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7646                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7647                }
7648
7649                if (copyRet >= 0) {
7650                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7651                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7652                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7653                } else if (needsRenderScriptOverride) {
7654                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7655                }
7656            }
7657        } catch (IOException ioe) {
7658            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7659        } finally {
7660            IoUtils.closeQuietly(handle);
7661        }
7662
7663        // Now that we've calculated the ABIs and determined if it's an internal app,
7664        // we will go ahead and populate the nativeLibraryPath.
7665        setNativeLibraryPaths(pkg);
7666    }
7667
7668    /**
7669     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7670     * i.e, so that all packages can be run inside a single process if required.
7671     *
7672     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7673     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7674     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7675     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7676     * updating a package that belongs to a shared user.
7677     *
7678     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7679     * adds unnecessary complexity.
7680     */
7681    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7682            PackageParser.Package scannedPackage, boolean bootComplete) {
7683        String requiredInstructionSet = null;
7684        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7685            requiredInstructionSet = VMRuntime.getInstructionSet(
7686                     scannedPackage.applicationInfo.primaryCpuAbi);
7687        }
7688
7689        PackageSetting requirer = null;
7690        for (PackageSetting ps : packagesForUser) {
7691            // If packagesForUser contains scannedPackage, we skip it. This will happen
7692            // when scannedPackage is an update of an existing package. Without this check,
7693            // we will never be able to change the ABI of any package belonging to a shared
7694            // user, even if it's compatible with other packages.
7695            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7696                if (ps.primaryCpuAbiString == null) {
7697                    continue;
7698                }
7699
7700                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7701                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7702                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7703                    // this but there's not much we can do.
7704                    String errorMessage = "Instruction set mismatch, "
7705                            + ((requirer == null) ? "[caller]" : requirer)
7706                            + " requires " + requiredInstructionSet + " whereas " + ps
7707                            + " requires " + instructionSet;
7708                    Slog.w(TAG, errorMessage);
7709                }
7710
7711                if (requiredInstructionSet == null) {
7712                    requiredInstructionSet = instructionSet;
7713                    requirer = ps;
7714                }
7715            }
7716        }
7717
7718        if (requiredInstructionSet != null) {
7719            String adjustedAbi;
7720            if (requirer != null) {
7721                // requirer != null implies that either scannedPackage was null or that scannedPackage
7722                // did not require an ABI, in which case we have to adjust scannedPackage to match
7723                // the ABI of the set (which is the same as requirer's ABI)
7724                adjustedAbi = requirer.primaryCpuAbiString;
7725                if (scannedPackage != null) {
7726                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7727                }
7728            } else {
7729                // requirer == null implies that we're updating all ABIs in the set to
7730                // match scannedPackage.
7731                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7732            }
7733
7734            for (PackageSetting ps : packagesForUser) {
7735                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7736                    if (ps.primaryCpuAbiString != null) {
7737                        continue;
7738                    }
7739
7740                    ps.primaryCpuAbiString = adjustedAbi;
7741                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7742                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7743                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7744                        mInstaller.rmdex(ps.codePathString,
7745                                getDexCodeInstructionSet(getPreferredInstructionSet()));
7746                    }
7747                }
7748            }
7749        }
7750    }
7751
7752    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7753        synchronized (mPackages) {
7754            mResolverReplaced = true;
7755            // Set up information for custom user intent resolution activity.
7756            mResolveActivity.applicationInfo = pkg.applicationInfo;
7757            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7758            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7759            mResolveActivity.processName = pkg.applicationInfo.packageName;
7760            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7761            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7762                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7763            mResolveActivity.theme = 0;
7764            mResolveActivity.exported = true;
7765            mResolveActivity.enabled = true;
7766            mResolveInfo.activityInfo = mResolveActivity;
7767            mResolveInfo.priority = 0;
7768            mResolveInfo.preferredOrder = 0;
7769            mResolveInfo.match = 0;
7770            mResolveComponentName = mCustomResolverComponentName;
7771            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7772                    mResolveComponentName);
7773        }
7774    }
7775
7776    private static String calculateBundledApkRoot(final String codePathString) {
7777        final File codePath = new File(codePathString);
7778        final File codeRoot;
7779        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7780            codeRoot = Environment.getRootDirectory();
7781        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7782            codeRoot = Environment.getOemDirectory();
7783        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7784            codeRoot = Environment.getVendorDirectory();
7785        } else {
7786            // Unrecognized code path; take its top real segment as the apk root:
7787            // e.g. /something/app/blah.apk => /something
7788            try {
7789                File f = codePath.getCanonicalFile();
7790                File parent = f.getParentFile();    // non-null because codePath is a file
7791                File tmp;
7792                while ((tmp = parent.getParentFile()) != null) {
7793                    f = parent;
7794                    parent = tmp;
7795                }
7796                codeRoot = f;
7797                Slog.w(TAG, "Unrecognized code path "
7798                        + codePath + " - using " + codeRoot);
7799            } catch (IOException e) {
7800                // Can't canonicalize the code path -- shenanigans?
7801                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7802                return Environment.getRootDirectory().getPath();
7803            }
7804        }
7805        return codeRoot.getPath();
7806    }
7807
7808    /**
7809     * Derive and set the location of native libraries for the given package,
7810     * which varies depending on where and how the package was installed.
7811     */
7812    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7813        final ApplicationInfo info = pkg.applicationInfo;
7814        final String codePath = pkg.codePath;
7815        final File codeFile = new File(codePath);
7816        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7817        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
7818
7819        info.nativeLibraryRootDir = null;
7820        info.nativeLibraryRootRequiresIsa = false;
7821        info.nativeLibraryDir = null;
7822        info.secondaryNativeLibraryDir = null;
7823
7824        if (isApkFile(codeFile)) {
7825            // Monolithic install
7826            if (bundledApp) {
7827                // If "/system/lib64/apkname" exists, assume that is the per-package
7828                // native library directory to use; otherwise use "/system/lib/apkname".
7829                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7830                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7831                        getPrimaryInstructionSet(info));
7832
7833                // This is a bundled system app so choose the path based on the ABI.
7834                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7835                // is just the default path.
7836                final String apkName = deriveCodePathName(codePath);
7837                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7838                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7839                        apkName).getAbsolutePath();
7840
7841                if (info.secondaryCpuAbi != null) {
7842                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7843                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7844                            secondaryLibDir, apkName).getAbsolutePath();
7845                }
7846            } else if (asecApp) {
7847                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7848                        .getAbsolutePath();
7849            } else {
7850                final String apkName = deriveCodePathName(codePath);
7851                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7852                        .getAbsolutePath();
7853            }
7854
7855            info.nativeLibraryRootRequiresIsa = false;
7856            info.nativeLibraryDir = info.nativeLibraryRootDir;
7857        } else {
7858            // Cluster install
7859            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7860            info.nativeLibraryRootRequiresIsa = true;
7861
7862            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7863                    getPrimaryInstructionSet(info)).getAbsolutePath();
7864
7865            if (info.secondaryCpuAbi != null) {
7866                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7867                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7868            }
7869        }
7870    }
7871
7872    /**
7873     * Calculate the abis and roots for a bundled app. These can uniquely
7874     * be determined from the contents of the system partition, i.e whether
7875     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7876     * of this information, and instead assume that the system was built
7877     * sensibly.
7878     */
7879    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7880                                           PackageSetting pkgSetting) {
7881        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7882
7883        // If "/system/lib64/apkname" exists, assume that is the per-package
7884        // native library directory to use; otherwise use "/system/lib/apkname".
7885        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7886        setBundledAppAbi(pkg, apkRoot, apkName);
7887        // pkgSetting might be null during rescan following uninstall of updates
7888        // to a bundled app, so accommodate that possibility.  The settings in
7889        // that case will be established later from the parsed package.
7890        //
7891        // If the settings aren't null, sync them up with what we've just derived.
7892        // note that apkRoot isn't stored in the package settings.
7893        if (pkgSetting != null) {
7894            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7895            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7896        }
7897    }
7898
7899    /**
7900     * Deduces the ABI of a bundled app and sets the relevant fields on the
7901     * parsed pkg object.
7902     *
7903     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7904     *        under which system libraries are installed.
7905     * @param apkName the name of the installed package.
7906     */
7907    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7908        final File codeFile = new File(pkg.codePath);
7909
7910        final boolean has64BitLibs;
7911        final boolean has32BitLibs;
7912        if (isApkFile(codeFile)) {
7913            // Monolithic install
7914            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7915            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7916        } else {
7917            // Cluster install
7918            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7919            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7920                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7921                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7922                has64BitLibs = (new File(rootDir, isa)).exists();
7923            } else {
7924                has64BitLibs = false;
7925            }
7926            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7927                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7928                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7929                has32BitLibs = (new File(rootDir, isa)).exists();
7930            } else {
7931                has32BitLibs = false;
7932            }
7933        }
7934
7935        if (has64BitLibs && !has32BitLibs) {
7936            // The package has 64 bit libs, but not 32 bit libs. Its primary
7937            // ABI should be 64 bit. We can safely assume here that the bundled
7938            // native libraries correspond to the most preferred ABI in the list.
7939
7940            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7941            pkg.applicationInfo.secondaryCpuAbi = null;
7942        } else if (has32BitLibs && !has64BitLibs) {
7943            // The package has 32 bit libs but not 64 bit libs. Its primary
7944            // ABI should be 32 bit.
7945
7946            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7947            pkg.applicationInfo.secondaryCpuAbi = null;
7948        } else if (has32BitLibs && has64BitLibs) {
7949            // The application has both 64 and 32 bit bundled libraries. We check
7950            // here that the app declares multiArch support, and warn if it doesn't.
7951            //
7952            // We will be lenient here and record both ABIs. The primary will be the
7953            // ABI that's higher on the list, i.e, a device that's configured to prefer
7954            // 64 bit apps will see a 64 bit primary ABI,
7955
7956            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7957                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7958            }
7959
7960            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7961                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7962                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7963            } else {
7964                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7965                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7966            }
7967        } else {
7968            pkg.applicationInfo.primaryCpuAbi = null;
7969            pkg.applicationInfo.secondaryCpuAbi = null;
7970        }
7971    }
7972
7973    private void killApplication(String pkgName, int appId, String reason) {
7974        // Request the ActivityManager to kill the process(only for existing packages)
7975        // so that we do not end up in a confused state while the user is still using the older
7976        // version of the application while the new one gets installed.
7977        IActivityManager am = ActivityManagerNative.getDefault();
7978        if (am != null) {
7979            try {
7980                am.killApplicationWithAppId(pkgName, appId, reason);
7981            } catch (RemoteException e) {
7982            }
7983        }
7984    }
7985
7986    void removePackageLI(PackageSetting ps, boolean chatty) {
7987        if (DEBUG_INSTALL) {
7988            if (chatty)
7989                Log.d(TAG, "Removing package " + ps.name);
7990        }
7991
7992        // writer
7993        synchronized (mPackages) {
7994            mPackages.remove(ps.name);
7995            final PackageParser.Package pkg = ps.pkg;
7996            if (pkg != null) {
7997                cleanPackageDataStructuresLILPw(pkg, chatty);
7998            }
7999        }
8000    }
8001
8002    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8003        if (DEBUG_INSTALL) {
8004            if (chatty)
8005                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8006        }
8007
8008        // writer
8009        synchronized (mPackages) {
8010            mPackages.remove(pkg.applicationInfo.packageName);
8011            cleanPackageDataStructuresLILPw(pkg, chatty);
8012        }
8013    }
8014
8015    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8016        int N = pkg.providers.size();
8017        StringBuilder r = null;
8018        int i;
8019        for (i=0; i<N; i++) {
8020            PackageParser.Provider p = pkg.providers.get(i);
8021            mProviders.removeProvider(p);
8022            if (p.info.authority == null) {
8023
8024                /* There was another ContentProvider with this authority when
8025                 * this app was installed so this authority is null,
8026                 * Ignore it as we don't have to unregister the provider.
8027                 */
8028                continue;
8029            }
8030            String names[] = p.info.authority.split(";");
8031            for (int j = 0; j < names.length; j++) {
8032                if (mProvidersByAuthority.get(names[j]) == p) {
8033                    mProvidersByAuthority.remove(names[j]);
8034                    if (DEBUG_REMOVE) {
8035                        if (chatty)
8036                            Log.d(TAG, "Unregistered content provider: " + names[j]
8037                                    + ", className = " + p.info.name + ", isSyncable = "
8038                                    + p.info.isSyncable);
8039                    }
8040                }
8041            }
8042            if (DEBUG_REMOVE && chatty) {
8043                if (r == null) {
8044                    r = new StringBuilder(256);
8045                } else {
8046                    r.append(' ');
8047                }
8048                r.append(p.info.name);
8049            }
8050        }
8051        if (r != null) {
8052            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8053        }
8054
8055        N = pkg.services.size();
8056        r = null;
8057        for (i=0; i<N; i++) {
8058            PackageParser.Service s = pkg.services.get(i);
8059            mServices.removeService(s);
8060            if (chatty) {
8061                if (r == null) {
8062                    r = new StringBuilder(256);
8063                } else {
8064                    r.append(' ');
8065                }
8066                r.append(s.info.name);
8067            }
8068        }
8069        if (r != null) {
8070            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8071        }
8072
8073        N = pkg.receivers.size();
8074        r = null;
8075        for (i=0; i<N; i++) {
8076            PackageParser.Activity a = pkg.receivers.get(i);
8077            mReceivers.removeActivity(a, "receiver");
8078            if (DEBUG_REMOVE && chatty) {
8079                if (r == null) {
8080                    r = new StringBuilder(256);
8081                } else {
8082                    r.append(' ');
8083                }
8084                r.append(a.info.name);
8085            }
8086        }
8087        if (r != null) {
8088            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8089        }
8090
8091        N = pkg.activities.size();
8092        r = null;
8093        for (i=0; i<N; i++) {
8094            PackageParser.Activity a = pkg.activities.get(i);
8095            mActivities.removeActivity(a, "activity");
8096            if (DEBUG_REMOVE && chatty) {
8097                if (r == null) {
8098                    r = new StringBuilder(256);
8099                } else {
8100                    r.append(' ');
8101                }
8102                r.append(a.info.name);
8103            }
8104        }
8105        if (r != null) {
8106            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8107        }
8108
8109        N = pkg.permissions.size();
8110        r = null;
8111        for (i=0; i<N; i++) {
8112            PackageParser.Permission p = pkg.permissions.get(i);
8113            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8114            if (bp == null) {
8115                bp = mSettings.mPermissionTrees.get(p.info.name);
8116            }
8117            if (bp != null && bp.perm == p) {
8118                bp.perm = null;
8119                if (DEBUG_REMOVE && chatty) {
8120                    if (r == null) {
8121                        r = new StringBuilder(256);
8122                    } else {
8123                        r.append(' ');
8124                    }
8125                    r.append(p.info.name);
8126                }
8127            }
8128            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8129                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8130                if (appOpPerms != null) {
8131                    appOpPerms.remove(pkg.packageName);
8132                }
8133            }
8134        }
8135        if (r != null) {
8136            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8137        }
8138
8139        N = pkg.requestedPermissions.size();
8140        r = null;
8141        for (i=0; i<N; i++) {
8142            String perm = pkg.requestedPermissions.get(i);
8143            BasePermission bp = mSettings.mPermissions.get(perm);
8144            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8145                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8146                if (appOpPerms != null) {
8147                    appOpPerms.remove(pkg.packageName);
8148                    if (appOpPerms.isEmpty()) {
8149                        mAppOpPermissionPackages.remove(perm);
8150                    }
8151                }
8152            }
8153        }
8154        if (r != null) {
8155            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8156        }
8157
8158        N = pkg.instrumentation.size();
8159        r = null;
8160        for (i=0; i<N; i++) {
8161            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8162            mInstrumentation.remove(a.getComponentName());
8163            if (DEBUG_REMOVE && chatty) {
8164                if (r == null) {
8165                    r = new StringBuilder(256);
8166                } else {
8167                    r.append(' ');
8168                }
8169                r.append(a.info.name);
8170            }
8171        }
8172        if (r != null) {
8173            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8174        }
8175
8176        r = null;
8177        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8178            // Only system apps can hold shared libraries.
8179            if (pkg.libraryNames != null) {
8180                for (i=0; i<pkg.libraryNames.size(); i++) {
8181                    String name = pkg.libraryNames.get(i);
8182                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8183                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8184                        mSharedLibraries.remove(name);
8185                        if (DEBUG_REMOVE && chatty) {
8186                            if (r == null) {
8187                                r = new StringBuilder(256);
8188                            } else {
8189                                r.append(' ');
8190                            }
8191                            r.append(name);
8192                        }
8193                    }
8194                }
8195            }
8196        }
8197        if (r != null) {
8198            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8199        }
8200    }
8201
8202    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8203        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8204            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8205                return true;
8206            }
8207        }
8208        return false;
8209    }
8210
8211    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8212    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8213    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8214
8215    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
8216            int flags) {
8217        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
8218        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
8219    }
8220
8221    private void updatePermissionsLPw(String changingPkg,
8222            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
8223        // Make sure there are no dangling permission trees.
8224        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8225        while (it.hasNext()) {
8226            final BasePermission bp = it.next();
8227            if (bp.packageSetting == null) {
8228                // We may not yet have parsed the package, so just see if
8229                // we still know about its settings.
8230                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8231            }
8232            if (bp.packageSetting == null) {
8233                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8234                        + " from package " + bp.sourcePackage);
8235                it.remove();
8236            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8237                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8238                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8239                            + " from package " + bp.sourcePackage);
8240                    flags |= UPDATE_PERMISSIONS_ALL;
8241                    it.remove();
8242                }
8243            }
8244        }
8245
8246        // Make sure all dynamic permissions have been assigned to a package,
8247        // and make sure there are no dangling permissions.
8248        it = mSettings.mPermissions.values().iterator();
8249        while (it.hasNext()) {
8250            final BasePermission bp = it.next();
8251            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8252                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8253                        + bp.name + " pkg=" + bp.sourcePackage
8254                        + " info=" + bp.pendingInfo);
8255                if (bp.packageSetting == null && bp.pendingInfo != null) {
8256                    final BasePermission tree = findPermissionTreeLP(bp.name);
8257                    if (tree != null && tree.perm != null) {
8258                        bp.packageSetting = tree.packageSetting;
8259                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8260                                new PermissionInfo(bp.pendingInfo));
8261                        bp.perm.info.packageName = tree.perm.info.packageName;
8262                        bp.perm.info.name = bp.name;
8263                        bp.uid = tree.uid;
8264                    }
8265                }
8266            }
8267            if (bp.packageSetting == null) {
8268                // We may not yet have parsed the package, so just see if
8269                // we still know about its settings.
8270                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8271            }
8272            if (bp.packageSetting == null) {
8273                Slog.w(TAG, "Removing dangling permission: " + bp.name
8274                        + " from package " + bp.sourcePackage);
8275                it.remove();
8276            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8277                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8278                    Slog.i(TAG, "Removing old permission: " + bp.name
8279                            + " from package " + bp.sourcePackage);
8280                    flags |= UPDATE_PERMISSIONS_ALL;
8281                    it.remove();
8282                }
8283            }
8284        }
8285
8286        // Now update the permissions for all packages, in particular
8287        // replace the granted permissions of the system packages.
8288        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8289            for (PackageParser.Package pkg : mPackages.values()) {
8290                if (pkg != pkgInfo) {
8291                    // Only replace for packages on requested volume
8292                    final String volumeUuid = getVolumeUuidForPackage(pkg);
8293                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
8294                            && Objects.equals(replaceVolumeUuid, volumeUuid);
8295                    grantPermissionsLPw(pkg, replace, changingPkg);
8296                }
8297            }
8298        }
8299
8300        if (pkgInfo != null) {
8301            // Only replace for packages on requested volume
8302            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
8303            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
8304                    && Objects.equals(replaceVolumeUuid, volumeUuid);
8305            grantPermissionsLPw(pkgInfo, replace, changingPkg);
8306        }
8307    }
8308
8309    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8310            String packageOfInterest) {
8311        // IMPORTANT: There are two types of permissions: install and runtime.
8312        // Install time permissions are granted when the app is installed to
8313        // all device users and users added in the future. Runtime permissions
8314        // are granted at runtime explicitly to specific users. Normal and signature
8315        // protected permissions are install time permissions. Dangerous permissions
8316        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8317        // otherwise they are runtime permissions. This function does not manage
8318        // runtime permissions except for the case an app targeting Lollipop MR1
8319        // being upgraded to target a newer SDK, in which case dangerous permissions
8320        // are transformed from install time to runtime ones.
8321
8322        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8323        if (ps == null) {
8324            return;
8325        }
8326
8327        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
8328
8329        PermissionsState permissionsState = ps.getPermissionsState();
8330        PermissionsState origPermissions = permissionsState;
8331
8332        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8333
8334        boolean runtimePermissionsRevoked = false;
8335        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8336
8337        boolean changedInstallPermission = false;
8338
8339        if (replace) {
8340            ps.installPermissionsFixed = false;
8341            if (!ps.isSharedUser()) {
8342                origPermissions = new PermissionsState(permissionsState);
8343                permissionsState.reset();
8344            } else {
8345                // We need to know only about runtime permission changes since the
8346                // calling code always writes the install permissions state but
8347                // the runtime ones are written only if changed. The only cases of
8348                // changed runtime permissions here are promotion of an install to
8349                // runtime and revocation of a runtime from a shared user.
8350                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
8351                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
8352                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
8353                    runtimePermissionsRevoked = true;
8354                }
8355            }
8356        }
8357
8358        permissionsState.setGlobalGids(mGlobalGids);
8359
8360        final int N = pkg.requestedPermissions.size();
8361        for (int i=0; i<N; i++) {
8362            final String name = pkg.requestedPermissions.get(i);
8363            final BasePermission bp = mSettings.mPermissions.get(name);
8364
8365            if (DEBUG_INSTALL) {
8366                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8367            }
8368
8369            if (bp == null || bp.packageSetting == null) {
8370                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8371                    Slog.w(TAG, "Unknown permission " + name
8372                            + " in package " + pkg.packageName);
8373                }
8374                continue;
8375            }
8376
8377            final String perm = bp.name;
8378            boolean allowedSig = false;
8379            int grant = GRANT_DENIED;
8380
8381            // Keep track of app op permissions.
8382            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8383                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8384                if (pkgs == null) {
8385                    pkgs = new ArraySet<>();
8386                    mAppOpPermissionPackages.put(bp.name, pkgs);
8387                }
8388                pkgs.add(pkg.packageName);
8389            }
8390
8391            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8392            switch (level) {
8393                case PermissionInfo.PROTECTION_NORMAL: {
8394                    // For all apps normal permissions are install time ones.
8395                    grant = GRANT_INSTALL;
8396                } break;
8397
8398                case PermissionInfo.PROTECTION_DANGEROUS: {
8399                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8400                        // For legacy apps dangerous permissions are install time ones.
8401                        grant = GRANT_INSTALL_LEGACY;
8402                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8403                        // For legacy apps that became modern, install becomes runtime.
8404                        grant = GRANT_UPGRADE;
8405                    } else if (mPromoteSystemApps
8406                            && isSystemApp(ps)
8407                            && mExistingSystemPackages.contains(ps.name)) {
8408                        // For legacy system apps, install becomes runtime.
8409                        // We cannot check hasInstallPermission() for system apps since those
8410                        // permissions were granted implicitly and not persisted pre-M.
8411                        grant = GRANT_UPGRADE;
8412                    } else {
8413                        // For modern apps keep runtime permissions unchanged.
8414                        grant = GRANT_RUNTIME;
8415                    }
8416                } break;
8417
8418                case PermissionInfo.PROTECTION_SIGNATURE: {
8419                    // For all apps signature permissions are install time ones.
8420                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8421                    if (allowedSig) {
8422                        grant = GRANT_INSTALL;
8423                    }
8424                } break;
8425            }
8426
8427            if (DEBUG_INSTALL) {
8428                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8429            }
8430
8431            if (grant != GRANT_DENIED) {
8432                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8433                    // If this is an existing, non-system package, then
8434                    // we can't add any new permissions to it.
8435                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8436                        // Except...  if this is a permission that was added
8437                        // to the platform (note: need to only do this when
8438                        // updating the platform).
8439                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8440                            grant = GRANT_DENIED;
8441                        }
8442                    }
8443                }
8444
8445                switch (grant) {
8446                    case GRANT_INSTALL: {
8447                        // Revoke this as runtime permission to handle the case of
8448                        // a runtime permission being downgraded to an install one.
8449                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8450                            if (origPermissions.getRuntimePermissionState(
8451                                    bp.name, userId) != null) {
8452                                // Revoke the runtime permission and clear the flags.
8453                                origPermissions.revokeRuntimePermission(bp, userId);
8454                                origPermissions.updatePermissionFlags(bp, userId,
8455                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8456                                // If we revoked a permission permission, we have to write.
8457                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8458                                        changedRuntimePermissionUserIds, userId);
8459                            }
8460                        }
8461                        // Grant an install permission.
8462                        if (permissionsState.grantInstallPermission(bp) !=
8463                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8464                            changedInstallPermission = true;
8465                        }
8466                    } break;
8467
8468                    case GRANT_INSTALL_LEGACY: {
8469                        // Grant an install permission.
8470                        if (permissionsState.grantInstallPermission(bp) !=
8471                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8472                            changedInstallPermission = true;
8473                        }
8474                    } break;
8475
8476                    case GRANT_RUNTIME: {
8477                        // Grant previously granted runtime permissions.
8478                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8479                            PermissionState permissionState = origPermissions
8480                                    .getRuntimePermissionState(bp.name, userId);
8481                            final int flags = permissionState != null
8482                                    ? permissionState.getFlags() : 0;
8483                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8484                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8485                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8486                                    // If we cannot put the permission as it was, we have to write.
8487                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8488                                            changedRuntimePermissionUserIds, userId);
8489                                }
8490                            }
8491                            // Propagate the permission flags.
8492                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8493                        }
8494                    } break;
8495
8496                    case GRANT_UPGRADE: {
8497                        // Grant runtime permissions for a previously held install permission.
8498                        PermissionState permissionState = origPermissions
8499                                .getInstallPermissionState(bp.name);
8500                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8501
8502                        if (origPermissions.revokeInstallPermission(bp)
8503                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8504                            // We will be transferring the permission flags, so clear them.
8505                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8506                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8507                            changedInstallPermission = true;
8508                        }
8509
8510                        // If the permission is not to be promoted to runtime we ignore it and
8511                        // also its other flags as they are not applicable to install permissions.
8512                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8513                            for (int userId : currentUserIds) {
8514                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8515                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8516                                    // Transfer the permission flags.
8517                                    permissionsState.updatePermissionFlags(bp, userId,
8518                                            flags, flags);
8519                                    // If we granted the permission, we have to write.
8520                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8521                                            changedRuntimePermissionUserIds, userId);
8522                                }
8523                            }
8524                        }
8525                    } break;
8526
8527                    default: {
8528                        if (packageOfInterest == null
8529                                || packageOfInterest.equals(pkg.packageName)) {
8530                            Slog.w(TAG, "Not granting permission " + perm
8531                                    + " to package " + pkg.packageName
8532                                    + " because it was previously installed without");
8533                        }
8534                    } break;
8535                }
8536            } else {
8537                if (permissionsState.revokeInstallPermission(bp) !=
8538                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8539                    // Also drop the permission flags.
8540                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8541                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8542                    changedInstallPermission = true;
8543                    Slog.i(TAG, "Un-granting permission " + perm
8544                            + " from package " + pkg.packageName
8545                            + " (protectionLevel=" + bp.protectionLevel
8546                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8547                            + ")");
8548                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8549                    // Don't print warning for app op permissions, since it is fine for them
8550                    // not to be granted, there is a UI for the user to decide.
8551                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8552                        Slog.w(TAG, "Not granting permission " + perm
8553                                + " to package " + pkg.packageName
8554                                + " (protectionLevel=" + bp.protectionLevel
8555                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8556                                + ")");
8557                    }
8558                }
8559            }
8560        }
8561
8562        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8563                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8564            // This is the first that we have heard about this package, so the
8565            // permissions we have now selected are fixed until explicitly
8566            // changed.
8567            ps.installPermissionsFixed = true;
8568        }
8569
8570        // Persist the runtime permissions state for users with changes. If permissions
8571        // were revoked because no app in the shared user declares them we have to
8572        // write synchronously to avoid losing runtime permissions state.
8573        for (int userId : changedRuntimePermissionUserIds) {
8574            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
8575        }
8576
8577        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8578    }
8579
8580    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8581        boolean allowed = false;
8582        final int NP = PackageParser.NEW_PERMISSIONS.length;
8583        for (int ip=0; ip<NP; ip++) {
8584            final PackageParser.NewPermissionInfo npi
8585                    = PackageParser.NEW_PERMISSIONS[ip];
8586            if (npi.name.equals(perm)
8587                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8588                allowed = true;
8589                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8590                        + pkg.packageName);
8591                break;
8592            }
8593        }
8594        return allowed;
8595    }
8596
8597    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8598            BasePermission bp, PermissionsState origPermissions) {
8599        boolean allowed;
8600        allowed = (compareSignatures(
8601                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8602                        == PackageManager.SIGNATURE_MATCH)
8603                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8604                        == PackageManager.SIGNATURE_MATCH);
8605        if (!allowed && (bp.protectionLevel
8606                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8607            if (isSystemApp(pkg)) {
8608                // For updated system applications, a system permission
8609                // is granted only if it had been defined by the original application.
8610                if (pkg.isUpdatedSystemApp()) {
8611                    final PackageSetting sysPs = mSettings
8612                            .getDisabledSystemPkgLPr(pkg.packageName);
8613                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8614                        // If the original was granted this permission, we take
8615                        // that grant decision as read and propagate it to the
8616                        // update.
8617                        if (sysPs.isPrivileged()) {
8618                            allowed = true;
8619                        }
8620                    } else {
8621                        // The system apk may have been updated with an older
8622                        // version of the one on the data partition, but which
8623                        // granted a new system permission that it didn't have
8624                        // before.  In this case we do want to allow the app to
8625                        // now get the new permission if the ancestral apk is
8626                        // privileged to get it.
8627                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8628                            for (int j=0;
8629                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8630                                if (perm.equals(
8631                                        sysPs.pkg.requestedPermissions.get(j))) {
8632                                    allowed = true;
8633                                    break;
8634                                }
8635                            }
8636                        }
8637                    }
8638                } else {
8639                    allowed = isPrivilegedApp(pkg);
8640                }
8641            }
8642        }
8643        if (!allowed) {
8644            if (!allowed && (bp.protectionLevel
8645                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8646                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
8647                // If this was a previously normal/dangerous permission that got moved
8648                // to a system permission as part of the runtime permission redesign, then
8649                // we still want to blindly grant it to old apps.
8650                allowed = true;
8651            }
8652            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8653                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8654                // If this permission is to be granted to the system installer and
8655                // this app is an installer, then it gets the permission.
8656                allowed = true;
8657            }
8658            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8659                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8660                // If this permission is to be granted to the system verifier and
8661                // this app is a verifier, then it gets the permission.
8662                allowed = true;
8663            }
8664            if (!allowed && (bp.protectionLevel
8665                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8666                    && isSystemApp(pkg)) {
8667                // Any pre-installed system app is allowed to get this permission.
8668                allowed = true;
8669            }
8670            if (!allowed && (bp.protectionLevel
8671                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8672                // For development permissions, a development permission
8673                // is granted only if it was already granted.
8674                allowed = origPermissions.hasInstallPermission(perm);
8675            }
8676        }
8677        return allowed;
8678    }
8679
8680    final class ActivityIntentResolver
8681            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8682        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8683                boolean defaultOnly, int userId) {
8684            if (!sUserManager.exists(userId)) return null;
8685            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8686            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8687        }
8688
8689        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8690                int userId) {
8691            if (!sUserManager.exists(userId)) return null;
8692            mFlags = flags;
8693            return super.queryIntent(intent, resolvedType,
8694                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8695        }
8696
8697        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8698                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8699            if (!sUserManager.exists(userId)) return null;
8700            if (packageActivities == null) {
8701                return null;
8702            }
8703            mFlags = flags;
8704            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8705            final int N = packageActivities.size();
8706            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8707                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8708
8709            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8710            for (int i = 0; i < N; ++i) {
8711                intentFilters = packageActivities.get(i).intents;
8712                if (intentFilters != null && intentFilters.size() > 0) {
8713                    PackageParser.ActivityIntentInfo[] array =
8714                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8715                    intentFilters.toArray(array);
8716                    listCut.add(array);
8717                }
8718            }
8719            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8720        }
8721
8722        public final void addActivity(PackageParser.Activity a, String type) {
8723            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8724            mActivities.put(a.getComponentName(), a);
8725            if (DEBUG_SHOW_INFO)
8726                Log.v(
8727                TAG, "  " + type + " " +
8728                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8729            if (DEBUG_SHOW_INFO)
8730                Log.v(TAG, "    Class=" + a.info.name);
8731            final int NI = a.intents.size();
8732            for (int j=0; j<NI; j++) {
8733                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8734                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8735                    intent.setPriority(0);
8736                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8737                            + a.className + " with priority > 0, forcing to 0");
8738                }
8739                if (DEBUG_SHOW_INFO) {
8740                    Log.v(TAG, "    IntentFilter:");
8741                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8742                }
8743                if (!intent.debugCheck()) {
8744                    Log.w(TAG, "==> For Activity " + a.info.name);
8745                }
8746                addFilter(intent);
8747            }
8748        }
8749
8750        public final void removeActivity(PackageParser.Activity a, String type) {
8751            mActivities.remove(a.getComponentName());
8752            if (DEBUG_SHOW_INFO) {
8753                Log.v(TAG, "  " + type + " "
8754                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8755                                : a.info.name) + ":");
8756                Log.v(TAG, "    Class=" + a.info.name);
8757            }
8758            final int NI = a.intents.size();
8759            for (int j=0; j<NI; j++) {
8760                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8761                if (DEBUG_SHOW_INFO) {
8762                    Log.v(TAG, "    IntentFilter:");
8763                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8764                }
8765                removeFilter(intent);
8766            }
8767        }
8768
8769        @Override
8770        protected boolean allowFilterResult(
8771                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8772            ActivityInfo filterAi = filter.activity.info;
8773            for (int i=dest.size()-1; i>=0; i--) {
8774                ActivityInfo destAi = dest.get(i).activityInfo;
8775                if (destAi.name == filterAi.name
8776                        && destAi.packageName == filterAi.packageName) {
8777                    return false;
8778                }
8779            }
8780            return true;
8781        }
8782
8783        @Override
8784        protected ActivityIntentInfo[] newArray(int size) {
8785            return new ActivityIntentInfo[size];
8786        }
8787
8788        @Override
8789        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8790            if (!sUserManager.exists(userId)) return true;
8791            PackageParser.Package p = filter.activity.owner;
8792            if (p != null) {
8793                PackageSetting ps = (PackageSetting)p.mExtras;
8794                if (ps != null) {
8795                    // System apps are never considered stopped for purposes of
8796                    // filtering, because there may be no way for the user to
8797                    // actually re-launch them.
8798                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8799                            && ps.getStopped(userId);
8800                }
8801            }
8802            return false;
8803        }
8804
8805        @Override
8806        protected boolean isPackageForFilter(String packageName,
8807                PackageParser.ActivityIntentInfo info) {
8808            return packageName.equals(info.activity.owner.packageName);
8809        }
8810
8811        @Override
8812        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8813                int match, int userId) {
8814            if (!sUserManager.exists(userId)) return null;
8815            if (!mSettings.isEnabledAndVisibleLPr(info.activity.info, mFlags, userId)) {
8816                return null;
8817            }
8818            final PackageParser.Activity activity = info.activity;
8819            if (mSafeMode && (activity.info.applicationInfo.flags
8820                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8821                return null;
8822            }
8823            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8824            if (ps == null) {
8825                return null;
8826            }
8827            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8828                    ps.readUserState(userId), userId);
8829            if (ai == null) {
8830                return null;
8831            }
8832            final ResolveInfo res = new ResolveInfo();
8833            res.activityInfo = ai;
8834            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8835                res.filter = info;
8836            }
8837            if (info != null) {
8838                res.handleAllWebDataURI = info.handleAllWebDataURI();
8839            }
8840            res.priority = info.getPriority();
8841            res.preferredOrder = activity.owner.mPreferredOrder;
8842            //System.out.println("Result: " + res.activityInfo.className +
8843            //                   " = " + res.priority);
8844            res.match = match;
8845            res.isDefault = info.hasDefault;
8846            res.labelRes = info.labelRes;
8847            res.nonLocalizedLabel = info.nonLocalizedLabel;
8848            if (userNeedsBadging(userId)) {
8849                res.noResourceId = true;
8850            } else {
8851                res.icon = info.icon;
8852            }
8853            res.iconResourceId = info.icon;
8854            res.system = res.activityInfo.applicationInfo.isSystemApp();
8855            return res;
8856        }
8857
8858        @Override
8859        protected void sortResults(List<ResolveInfo> results) {
8860            Collections.sort(results, mResolvePrioritySorter);
8861        }
8862
8863        @Override
8864        protected void dumpFilter(PrintWriter out, String prefix,
8865                PackageParser.ActivityIntentInfo filter) {
8866            out.print(prefix); out.print(
8867                    Integer.toHexString(System.identityHashCode(filter.activity)));
8868                    out.print(' ');
8869                    filter.activity.printComponentShortName(out);
8870                    out.print(" filter ");
8871                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8872        }
8873
8874        @Override
8875        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8876            return filter.activity;
8877        }
8878
8879        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8880            PackageParser.Activity activity = (PackageParser.Activity)label;
8881            out.print(prefix); out.print(
8882                    Integer.toHexString(System.identityHashCode(activity)));
8883                    out.print(' ');
8884                    activity.printComponentShortName(out);
8885            if (count > 1) {
8886                out.print(" ("); out.print(count); out.print(" filters)");
8887            }
8888            out.println();
8889        }
8890
8891//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8892//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8893//            final List<ResolveInfo> retList = Lists.newArrayList();
8894//            while (i.hasNext()) {
8895//                final ResolveInfo resolveInfo = i.next();
8896//                if (isEnabledLP(resolveInfo.activityInfo)) {
8897//                    retList.add(resolveInfo);
8898//                }
8899//            }
8900//            return retList;
8901//        }
8902
8903        // Keys are String (activity class name), values are Activity.
8904        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8905                = new ArrayMap<ComponentName, PackageParser.Activity>();
8906        private int mFlags;
8907    }
8908
8909    private final class ServiceIntentResolver
8910            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8911        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8912                boolean defaultOnly, int userId) {
8913            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8914            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8915        }
8916
8917        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8918                int userId) {
8919            if (!sUserManager.exists(userId)) return null;
8920            mFlags = flags;
8921            return super.queryIntent(intent, resolvedType,
8922                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8923        }
8924
8925        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8926                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8927            if (!sUserManager.exists(userId)) return null;
8928            if (packageServices == null) {
8929                return null;
8930            }
8931            mFlags = flags;
8932            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8933            final int N = packageServices.size();
8934            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8935                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8936
8937            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8938            for (int i = 0; i < N; ++i) {
8939                intentFilters = packageServices.get(i).intents;
8940                if (intentFilters != null && intentFilters.size() > 0) {
8941                    PackageParser.ServiceIntentInfo[] array =
8942                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8943                    intentFilters.toArray(array);
8944                    listCut.add(array);
8945                }
8946            }
8947            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8948        }
8949
8950        public final void addService(PackageParser.Service s) {
8951            mServices.put(s.getComponentName(), s);
8952            if (DEBUG_SHOW_INFO) {
8953                Log.v(TAG, "  "
8954                        + (s.info.nonLocalizedLabel != null
8955                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8956                Log.v(TAG, "    Class=" + s.info.name);
8957            }
8958            final int NI = s.intents.size();
8959            int j;
8960            for (j=0; j<NI; j++) {
8961                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8962                if (DEBUG_SHOW_INFO) {
8963                    Log.v(TAG, "    IntentFilter:");
8964                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8965                }
8966                if (!intent.debugCheck()) {
8967                    Log.w(TAG, "==> For Service " + s.info.name);
8968                }
8969                addFilter(intent);
8970            }
8971        }
8972
8973        public final void removeService(PackageParser.Service s) {
8974            mServices.remove(s.getComponentName());
8975            if (DEBUG_SHOW_INFO) {
8976                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8977                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8978                Log.v(TAG, "    Class=" + s.info.name);
8979            }
8980            final int NI = s.intents.size();
8981            int j;
8982            for (j=0; j<NI; j++) {
8983                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8984                if (DEBUG_SHOW_INFO) {
8985                    Log.v(TAG, "    IntentFilter:");
8986                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8987                }
8988                removeFilter(intent);
8989            }
8990        }
8991
8992        @Override
8993        protected boolean allowFilterResult(
8994                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8995            ServiceInfo filterSi = filter.service.info;
8996            for (int i=dest.size()-1; i>=0; i--) {
8997                ServiceInfo destAi = dest.get(i).serviceInfo;
8998                if (destAi.name == filterSi.name
8999                        && destAi.packageName == filterSi.packageName) {
9000                    return false;
9001                }
9002            }
9003            return true;
9004        }
9005
9006        @Override
9007        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9008            return new PackageParser.ServiceIntentInfo[size];
9009        }
9010
9011        @Override
9012        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9013            if (!sUserManager.exists(userId)) return true;
9014            PackageParser.Package p = filter.service.owner;
9015            if (p != null) {
9016                PackageSetting ps = (PackageSetting)p.mExtras;
9017                if (ps != null) {
9018                    // System apps are never considered stopped for purposes of
9019                    // filtering, because there may be no way for the user to
9020                    // actually re-launch them.
9021                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9022                            && ps.getStopped(userId);
9023                }
9024            }
9025            return false;
9026        }
9027
9028        @Override
9029        protected boolean isPackageForFilter(String packageName,
9030                PackageParser.ServiceIntentInfo info) {
9031            return packageName.equals(info.service.owner.packageName);
9032        }
9033
9034        @Override
9035        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9036                int match, int userId) {
9037            if (!sUserManager.exists(userId)) return null;
9038            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9039            if (!mSettings.isEnabledAndVisibleLPr(info.service.info, mFlags, userId)) {
9040                return null;
9041            }
9042            final PackageParser.Service service = info.service;
9043            if (mSafeMode && (service.info.applicationInfo.flags
9044                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9045                return null;
9046            }
9047            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9048            if (ps == null) {
9049                return null;
9050            }
9051            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9052                    ps.readUserState(userId), userId);
9053            if (si == null) {
9054                return null;
9055            }
9056            final ResolveInfo res = new ResolveInfo();
9057            res.serviceInfo = si;
9058            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9059                res.filter = filter;
9060            }
9061            res.priority = info.getPriority();
9062            res.preferredOrder = service.owner.mPreferredOrder;
9063            res.match = match;
9064            res.isDefault = info.hasDefault;
9065            res.labelRes = info.labelRes;
9066            res.nonLocalizedLabel = info.nonLocalizedLabel;
9067            res.icon = info.icon;
9068            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9069            return res;
9070        }
9071
9072        @Override
9073        protected void sortResults(List<ResolveInfo> results) {
9074            Collections.sort(results, mResolvePrioritySorter);
9075        }
9076
9077        @Override
9078        protected void dumpFilter(PrintWriter out, String prefix,
9079                PackageParser.ServiceIntentInfo filter) {
9080            out.print(prefix); out.print(
9081                    Integer.toHexString(System.identityHashCode(filter.service)));
9082                    out.print(' ');
9083                    filter.service.printComponentShortName(out);
9084                    out.print(" filter ");
9085                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9086        }
9087
9088        @Override
9089        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9090            return filter.service;
9091        }
9092
9093        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9094            PackageParser.Service service = (PackageParser.Service)label;
9095            out.print(prefix); out.print(
9096                    Integer.toHexString(System.identityHashCode(service)));
9097                    out.print(' ');
9098                    service.printComponentShortName(out);
9099            if (count > 1) {
9100                out.print(" ("); out.print(count); out.print(" filters)");
9101            }
9102            out.println();
9103        }
9104
9105//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9106//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9107//            final List<ResolveInfo> retList = Lists.newArrayList();
9108//            while (i.hasNext()) {
9109//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9110//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9111//                    retList.add(resolveInfo);
9112//                }
9113//            }
9114//            return retList;
9115//        }
9116
9117        // Keys are String (activity class name), values are Activity.
9118        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9119                = new ArrayMap<ComponentName, PackageParser.Service>();
9120        private int mFlags;
9121    };
9122
9123    private final class ProviderIntentResolver
9124            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9125        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9126                boolean defaultOnly, int userId) {
9127            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9128            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9129        }
9130
9131        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9132                int userId) {
9133            if (!sUserManager.exists(userId))
9134                return null;
9135            mFlags = flags;
9136            return super.queryIntent(intent, resolvedType,
9137                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9138        }
9139
9140        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9141                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9142            if (!sUserManager.exists(userId))
9143                return null;
9144            if (packageProviders == null) {
9145                return null;
9146            }
9147            mFlags = flags;
9148            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9149            final int N = packageProviders.size();
9150            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9151                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9152
9153            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9154            for (int i = 0; i < N; ++i) {
9155                intentFilters = packageProviders.get(i).intents;
9156                if (intentFilters != null && intentFilters.size() > 0) {
9157                    PackageParser.ProviderIntentInfo[] array =
9158                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9159                    intentFilters.toArray(array);
9160                    listCut.add(array);
9161                }
9162            }
9163            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9164        }
9165
9166        public final void addProvider(PackageParser.Provider p) {
9167            if (mProviders.containsKey(p.getComponentName())) {
9168                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9169                return;
9170            }
9171
9172            mProviders.put(p.getComponentName(), p);
9173            if (DEBUG_SHOW_INFO) {
9174                Log.v(TAG, "  "
9175                        + (p.info.nonLocalizedLabel != null
9176                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9177                Log.v(TAG, "    Class=" + p.info.name);
9178            }
9179            final int NI = p.intents.size();
9180            int j;
9181            for (j = 0; j < NI; j++) {
9182                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9183                if (DEBUG_SHOW_INFO) {
9184                    Log.v(TAG, "    IntentFilter:");
9185                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9186                }
9187                if (!intent.debugCheck()) {
9188                    Log.w(TAG, "==> For Provider " + p.info.name);
9189                }
9190                addFilter(intent);
9191            }
9192        }
9193
9194        public final void removeProvider(PackageParser.Provider p) {
9195            mProviders.remove(p.getComponentName());
9196            if (DEBUG_SHOW_INFO) {
9197                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9198                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9199                Log.v(TAG, "    Class=" + p.info.name);
9200            }
9201            final int NI = p.intents.size();
9202            int j;
9203            for (j = 0; j < NI; j++) {
9204                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9205                if (DEBUG_SHOW_INFO) {
9206                    Log.v(TAG, "    IntentFilter:");
9207                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9208                }
9209                removeFilter(intent);
9210            }
9211        }
9212
9213        @Override
9214        protected boolean allowFilterResult(
9215                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9216            ProviderInfo filterPi = filter.provider.info;
9217            for (int i = dest.size() - 1; i >= 0; i--) {
9218                ProviderInfo destPi = dest.get(i).providerInfo;
9219                if (destPi.name == filterPi.name
9220                        && destPi.packageName == filterPi.packageName) {
9221                    return false;
9222                }
9223            }
9224            return true;
9225        }
9226
9227        @Override
9228        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9229            return new PackageParser.ProviderIntentInfo[size];
9230        }
9231
9232        @Override
9233        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9234            if (!sUserManager.exists(userId))
9235                return true;
9236            PackageParser.Package p = filter.provider.owner;
9237            if (p != null) {
9238                PackageSetting ps = (PackageSetting) p.mExtras;
9239                if (ps != null) {
9240                    // System apps are never considered stopped for purposes of
9241                    // filtering, because there may be no way for the user to
9242                    // actually re-launch them.
9243                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9244                            && ps.getStopped(userId);
9245                }
9246            }
9247            return false;
9248        }
9249
9250        @Override
9251        protected boolean isPackageForFilter(String packageName,
9252                PackageParser.ProviderIntentInfo info) {
9253            return packageName.equals(info.provider.owner.packageName);
9254        }
9255
9256        @Override
9257        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9258                int match, int userId) {
9259            if (!sUserManager.exists(userId))
9260                return null;
9261            final PackageParser.ProviderIntentInfo info = filter;
9262            if (!mSettings.isEnabledAndVisibleLPr(info.provider.info, mFlags, userId)) {
9263                return null;
9264            }
9265            final PackageParser.Provider provider = info.provider;
9266            if (mSafeMode && (provider.info.applicationInfo.flags
9267                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9268                return null;
9269            }
9270            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9271            if (ps == null) {
9272                return null;
9273            }
9274            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9275                    ps.readUserState(userId), userId);
9276            if (pi == null) {
9277                return null;
9278            }
9279            final ResolveInfo res = new ResolveInfo();
9280            res.providerInfo = pi;
9281            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9282                res.filter = filter;
9283            }
9284            res.priority = info.getPriority();
9285            res.preferredOrder = provider.owner.mPreferredOrder;
9286            res.match = match;
9287            res.isDefault = info.hasDefault;
9288            res.labelRes = info.labelRes;
9289            res.nonLocalizedLabel = info.nonLocalizedLabel;
9290            res.icon = info.icon;
9291            res.system = res.providerInfo.applicationInfo.isSystemApp();
9292            return res;
9293        }
9294
9295        @Override
9296        protected void sortResults(List<ResolveInfo> results) {
9297            Collections.sort(results, mResolvePrioritySorter);
9298        }
9299
9300        @Override
9301        protected void dumpFilter(PrintWriter out, String prefix,
9302                PackageParser.ProviderIntentInfo filter) {
9303            out.print(prefix);
9304            out.print(
9305                    Integer.toHexString(System.identityHashCode(filter.provider)));
9306            out.print(' ');
9307            filter.provider.printComponentShortName(out);
9308            out.print(" filter ");
9309            out.println(Integer.toHexString(System.identityHashCode(filter)));
9310        }
9311
9312        @Override
9313        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9314            return filter.provider;
9315        }
9316
9317        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9318            PackageParser.Provider provider = (PackageParser.Provider)label;
9319            out.print(prefix); out.print(
9320                    Integer.toHexString(System.identityHashCode(provider)));
9321                    out.print(' ');
9322                    provider.printComponentShortName(out);
9323            if (count > 1) {
9324                out.print(" ("); out.print(count); out.print(" filters)");
9325            }
9326            out.println();
9327        }
9328
9329        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9330                = new ArrayMap<ComponentName, PackageParser.Provider>();
9331        private int mFlags;
9332    };
9333
9334    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9335            new Comparator<ResolveInfo>() {
9336        public int compare(ResolveInfo r1, ResolveInfo r2) {
9337            int v1 = r1.priority;
9338            int v2 = r2.priority;
9339            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9340            if (v1 != v2) {
9341                return (v1 > v2) ? -1 : 1;
9342            }
9343            v1 = r1.preferredOrder;
9344            v2 = r2.preferredOrder;
9345            if (v1 != v2) {
9346                return (v1 > v2) ? -1 : 1;
9347            }
9348            if (r1.isDefault != r2.isDefault) {
9349                return r1.isDefault ? -1 : 1;
9350            }
9351            v1 = r1.match;
9352            v2 = r2.match;
9353            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9354            if (v1 != v2) {
9355                return (v1 > v2) ? -1 : 1;
9356            }
9357            if (r1.system != r2.system) {
9358                return r1.system ? -1 : 1;
9359            }
9360            return 0;
9361        }
9362    };
9363
9364    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9365            new Comparator<ProviderInfo>() {
9366        public int compare(ProviderInfo p1, ProviderInfo p2) {
9367            final int v1 = p1.initOrder;
9368            final int v2 = p2.initOrder;
9369            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9370        }
9371    };
9372
9373    final void sendPackageBroadcast(final String action, final String pkg,
9374            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9375            final int[] userIds) {
9376        mHandler.post(new Runnable() {
9377            @Override
9378            public void run() {
9379                try {
9380                    final IActivityManager am = ActivityManagerNative.getDefault();
9381                    if (am == null) return;
9382                    final int[] resolvedUserIds;
9383                    if (userIds == null) {
9384                        resolvedUserIds = am.getRunningUserIds();
9385                    } else {
9386                        resolvedUserIds = userIds;
9387                    }
9388                    for (int id : resolvedUserIds) {
9389                        final Intent intent = new Intent(action,
9390                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9391                        if (extras != null) {
9392                            intent.putExtras(extras);
9393                        }
9394                        if (targetPkg != null) {
9395                            intent.setPackage(targetPkg);
9396                        }
9397                        // Modify the UID when posting to other users
9398                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9399                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9400                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9401                            intent.putExtra(Intent.EXTRA_UID, uid);
9402                        }
9403                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9404                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9405                        if (DEBUG_BROADCASTS) {
9406                            RuntimeException here = new RuntimeException("here");
9407                            here.fillInStackTrace();
9408                            Slog.d(TAG, "Sending to user " + id + ": "
9409                                    + intent.toShortString(false, true, false, false)
9410                                    + " " + intent.getExtras(), here);
9411                        }
9412                        am.broadcastIntent(null, intent, null, finishedReceiver,
9413                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9414                                null, finishedReceiver != null, false, id);
9415                    }
9416                } catch (RemoteException ex) {
9417                }
9418            }
9419        });
9420    }
9421
9422    /**
9423     * Check if the external storage media is available. This is true if there
9424     * is a mounted external storage medium or if the external storage is
9425     * emulated.
9426     */
9427    private boolean isExternalMediaAvailable() {
9428        return mMediaMounted || Environment.isExternalStorageEmulated();
9429    }
9430
9431    @Override
9432    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9433        // writer
9434        synchronized (mPackages) {
9435            if (!isExternalMediaAvailable()) {
9436                // If the external storage is no longer mounted at this point,
9437                // the caller may not have been able to delete all of this
9438                // packages files and can not delete any more.  Bail.
9439                return null;
9440            }
9441            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9442            if (lastPackage != null) {
9443                pkgs.remove(lastPackage);
9444            }
9445            if (pkgs.size() > 0) {
9446                return pkgs.get(0);
9447            }
9448        }
9449        return null;
9450    }
9451
9452    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9453        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9454                userId, andCode ? 1 : 0, packageName);
9455        if (mSystemReady) {
9456            msg.sendToTarget();
9457        } else {
9458            if (mPostSystemReadyMessages == null) {
9459                mPostSystemReadyMessages = new ArrayList<>();
9460            }
9461            mPostSystemReadyMessages.add(msg);
9462        }
9463    }
9464
9465    void startCleaningPackages() {
9466        // reader
9467        synchronized (mPackages) {
9468            if (!isExternalMediaAvailable()) {
9469                return;
9470            }
9471            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9472                return;
9473            }
9474        }
9475        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9476        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9477        IActivityManager am = ActivityManagerNative.getDefault();
9478        if (am != null) {
9479            try {
9480                am.startService(null, intent, null, mContext.getOpPackageName(),
9481                        UserHandle.USER_SYSTEM);
9482            } catch (RemoteException e) {
9483            }
9484        }
9485    }
9486
9487    @Override
9488    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9489            int installFlags, String installerPackageName, VerificationParams verificationParams,
9490            String packageAbiOverride) {
9491        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9492                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9493    }
9494
9495    @Override
9496    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9497            int installFlags, String installerPackageName, VerificationParams verificationParams,
9498            String packageAbiOverride, int userId) {
9499        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9500
9501        final int callingUid = Binder.getCallingUid();
9502        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9503
9504        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9505            try {
9506                if (observer != null) {
9507                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9508                }
9509            } catch (RemoteException re) {
9510            }
9511            return;
9512        }
9513
9514        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9515            installFlags |= PackageManager.INSTALL_FROM_ADB;
9516
9517        } else {
9518            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9519            // about installerPackageName.
9520
9521            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9522            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9523        }
9524
9525        UserHandle user;
9526        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9527            user = UserHandle.ALL;
9528        } else {
9529            user = new UserHandle(userId);
9530        }
9531
9532        // Only system components can circumvent runtime permissions when installing.
9533        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9534                && mContext.checkCallingOrSelfPermission(Manifest.permission
9535                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9536            throw new SecurityException("You need the "
9537                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9538                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9539        }
9540
9541        verificationParams.setInstallerUid(callingUid);
9542
9543        final File originFile = new File(originPath);
9544        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9545
9546        final Message msg = mHandler.obtainMessage(INIT_COPY);
9547        final InstallParams params = new InstallParams(origin, null, observer, installFlags,
9548                installerPackageName, null, verificationParams, user, packageAbiOverride, null);
9549        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
9550        msg.obj = params;
9551
9552        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
9553                System.identityHashCode(msg.obj));
9554        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
9555                System.identityHashCode(msg.obj));
9556
9557        mHandler.sendMessage(msg);
9558    }
9559
9560    void installStage(String packageName, File stagedDir, String stagedCid,
9561            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
9562            String installerPackageName, int installerUid, UserHandle user) {
9563        final VerificationParams verifParams = new VerificationParams(
9564                null, sessionParams.originatingUri, sessionParams.referrerUri,
9565                sessionParams.originatingUid, null);
9566        verifParams.setInstallerUid(installerUid);
9567
9568        final OriginInfo origin;
9569        if (stagedDir != null) {
9570            origin = OriginInfo.fromStagedFile(stagedDir);
9571        } else {
9572            origin = OriginInfo.fromStagedContainer(stagedCid);
9573        }
9574
9575        final Message msg = mHandler.obtainMessage(INIT_COPY);
9576        final InstallParams params = new InstallParams(origin, null, observer,
9577                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
9578                verifParams, user, sessionParams.abiOverride,
9579                sessionParams.grantedRuntimePermissions);
9580        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
9581        msg.obj = params;
9582
9583        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
9584                System.identityHashCode(msg.obj));
9585        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
9586                System.identityHashCode(msg.obj));
9587
9588        mHandler.sendMessage(msg);
9589    }
9590
9591    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9592        Bundle extras = new Bundle(1);
9593        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9594
9595        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9596                packageName, extras, null, null, new int[] {userId});
9597        try {
9598            IActivityManager am = ActivityManagerNative.getDefault();
9599            final boolean isSystem =
9600                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9601            if (isSystem && am.isUserRunning(userId, 0)) {
9602                // The just-installed/enabled app is bundled on the system, so presumed
9603                // to be able to run automatically without needing an explicit launch.
9604                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9605                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9606                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9607                        .setPackage(packageName);
9608                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9609                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9610            }
9611        } catch (RemoteException e) {
9612            // shouldn't happen
9613            Slog.w(TAG, "Unable to bootstrap installed package", e);
9614        }
9615    }
9616
9617    @Override
9618    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9619            int userId) {
9620        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9621        PackageSetting pkgSetting;
9622        final int uid = Binder.getCallingUid();
9623        enforceCrossUserPermission(uid, userId, true, true,
9624                "setApplicationHiddenSetting for user " + userId);
9625
9626        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9627            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9628            return false;
9629        }
9630
9631        long callingId = Binder.clearCallingIdentity();
9632        try {
9633            boolean sendAdded = false;
9634            boolean sendRemoved = false;
9635            // writer
9636            synchronized (mPackages) {
9637                pkgSetting = mSettings.mPackages.get(packageName);
9638                if (pkgSetting == null) {
9639                    return false;
9640                }
9641                if (pkgSetting.getHidden(userId) != hidden) {
9642                    pkgSetting.setHidden(hidden, userId);
9643                    mSettings.writePackageRestrictionsLPr(userId);
9644                    if (hidden) {
9645                        sendRemoved = true;
9646                    } else {
9647                        sendAdded = true;
9648                    }
9649                }
9650            }
9651            if (sendAdded) {
9652                sendPackageAddedForUser(packageName, pkgSetting, userId);
9653                return true;
9654            }
9655            if (sendRemoved) {
9656                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9657                        "hiding pkg");
9658                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9659                return true;
9660            }
9661        } finally {
9662            Binder.restoreCallingIdentity(callingId);
9663        }
9664        return false;
9665    }
9666
9667    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9668            int userId) {
9669        final PackageRemovedInfo info = new PackageRemovedInfo();
9670        info.removedPackage = packageName;
9671        info.removedUsers = new int[] {userId};
9672        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9673        info.sendBroadcast(false, false, false);
9674    }
9675
9676    /**
9677     * Returns true if application is not found or there was an error. Otherwise it returns
9678     * the hidden state of the package for the given user.
9679     */
9680    @Override
9681    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9682        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9683        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9684                false, "getApplicationHidden for user " + userId);
9685        PackageSetting pkgSetting;
9686        long callingId = Binder.clearCallingIdentity();
9687        try {
9688            // writer
9689            synchronized (mPackages) {
9690                pkgSetting = mSettings.mPackages.get(packageName);
9691                if (pkgSetting == null) {
9692                    return true;
9693                }
9694                return pkgSetting.getHidden(userId);
9695            }
9696        } finally {
9697            Binder.restoreCallingIdentity(callingId);
9698        }
9699    }
9700
9701    /**
9702     * @hide
9703     */
9704    @Override
9705    public int installExistingPackageAsUser(String packageName, int userId) {
9706        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9707                null);
9708        PackageSetting pkgSetting;
9709        final int uid = Binder.getCallingUid();
9710        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9711                + userId);
9712        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9713            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9714        }
9715
9716        long callingId = Binder.clearCallingIdentity();
9717        try {
9718            boolean sendAdded = false;
9719
9720            // writer
9721            synchronized (mPackages) {
9722                pkgSetting = mSettings.mPackages.get(packageName);
9723                if (pkgSetting == null) {
9724                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9725                }
9726                if (!pkgSetting.getInstalled(userId)) {
9727                    pkgSetting.setInstalled(true, userId);
9728                    pkgSetting.setHidden(false, userId);
9729                    mSettings.writePackageRestrictionsLPr(userId);
9730                    sendAdded = true;
9731                }
9732            }
9733
9734            if (sendAdded) {
9735                sendPackageAddedForUser(packageName, pkgSetting, userId);
9736            }
9737        } finally {
9738            Binder.restoreCallingIdentity(callingId);
9739        }
9740
9741        return PackageManager.INSTALL_SUCCEEDED;
9742    }
9743
9744    boolean isUserRestricted(int userId, String restrictionKey) {
9745        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9746        if (restrictions.getBoolean(restrictionKey, false)) {
9747            Log.w(TAG, "User is restricted: " + restrictionKey);
9748            return true;
9749        }
9750        return false;
9751    }
9752
9753    @Override
9754    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9755        mContext.enforceCallingOrSelfPermission(
9756                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9757                "Only package verification agents can verify applications");
9758
9759        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9760        final PackageVerificationResponse response = new PackageVerificationResponse(
9761                verificationCode, Binder.getCallingUid());
9762        msg.arg1 = id;
9763        msg.obj = response;
9764        mHandler.sendMessage(msg);
9765    }
9766
9767    @Override
9768    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9769            long millisecondsToDelay) {
9770        mContext.enforceCallingOrSelfPermission(
9771                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9772                "Only package verification agents can extend verification timeouts");
9773
9774        final PackageVerificationState state = mPendingVerification.get(id);
9775        final PackageVerificationResponse response = new PackageVerificationResponse(
9776                verificationCodeAtTimeout, Binder.getCallingUid());
9777
9778        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9779            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9780        }
9781        if (millisecondsToDelay < 0) {
9782            millisecondsToDelay = 0;
9783        }
9784        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9785                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9786            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9787        }
9788
9789        if ((state != null) && !state.timeoutExtended()) {
9790            state.extendTimeout();
9791
9792            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9793            msg.arg1 = id;
9794            msg.obj = response;
9795            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9796        }
9797    }
9798
9799    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9800            int verificationCode, UserHandle user) {
9801        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9802        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9803        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9804        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9805        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9806
9807        mContext.sendBroadcastAsUser(intent, user,
9808                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9809    }
9810
9811    private ComponentName matchComponentForVerifier(String packageName,
9812            List<ResolveInfo> receivers) {
9813        ActivityInfo targetReceiver = null;
9814
9815        final int NR = receivers.size();
9816        for (int i = 0; i < NR; i++) {
9817            final ResolveInfo info = receivers.get(i);
9818            if (info.activityInfo == null) {
9819                continue;
9820            }
9821
9822            if (packageName.equals(info.activityInfo.packageName)) {
9823                targetReceiver = info.activityInfo;
9824                break;
9825            }
9826        }
9827
9828        if (targetReceiver == null) {
9829            return null;
9830        }
9831
9832        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9833    }
9834
9835    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9836            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9837        if (pkgInfo.verifiers.length == 0) {
9838            return null;
9839        }
9840
9841        final int N = pkgInfo.verifiers.length;
9842        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9843        for (int i = 0; i < N; i++) {
9844            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9845
9846            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9847                    receivers);
9848            if (comp == null) {
9849                continue;
9850            }
9851
9852            final int verifierUid = getUidForVerifier(verifierInfo);
9853            if (verifierUid == -1) {
9854                continue;
9855            }
9856
9857            if (DEBUG_VERIFY) {
9858                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9859                        + " with the correct signature");
9860            }
9861            sufficientVerifiers.add(comp);
9862            verificationState.addSufficientVerifier(verifierUid);
9863        }
9864
9865        return sufficientVerifiers;
9866    }
9867
9868    private int getUidForVerifier(VerifierInfo verifierInfo) {
9869        synchronized (mPackages) {
9870            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9871            if (pkg == null) {
9872                return -1;
9873            } else if (pkg.mSignatures.length != 1) {
9874                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9875                        + " has more than one signature; ignoring");
9876                return -1;
9877            }
9878
9879            /*
9880             * If the public key of the package's signature does not match
9881             * our expected public key, then this is a different package and
9882             * we should skip.
9883             */
9884
9885            final byte[] expectedPublicKey;
9886            try {
9887                final Signature verifierSig = pkg.mSignatures[0];
9888                final PublicKey publicKey = verifierSig.getPublicKey();
9889                expectedPublicKey = publicKey.getEncoded();
9890            } catch (CertificateException e) {
9891                return -1;
9892            }
9893
9894            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9895
9896            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9897                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9898                        + " does not have the expected public key; ignoring");
9899                return -1;
9900            }
9901
9902            return pkg.applicationInfo.uid;
9903        }
9904    }
9905
9906    @Override
9907    public void finishPackageInstall(int token) {
9908        enforceSystemOrRoot("Only the system is allowed to finish installs");
9909
9910        if (DEBUG_INSTALL) {
9911            Slog.v(TAG, "BM finishing package install for " + token);
9912        }
9913        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
9914
9915        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9916        mHandler.sendMessage(msg);
9917    }
9918
9919    /**
9920     * Get the verification agent timeout.
9921     *
9922     * @return verification timeout in milliseconds
9923     */
9924    private long getVerificationTimeout() {
9925        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9926                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9927                DEFAULT_VERIFICATION_TIMEOUT);
9928    }
9929
9930    /**
9931     * Get the default verification agent response code.
9932     *
9933     * @return default verification response code
9934     */
9935    private int getDefaultVerificationResponse() {
9936        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9937                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9938                DEFAULT_VERIFICATION_RESPONSE);
9939    }
9940
9941    /**
9942     * Check whether or not package verification has been enabled.
9943     *
9944     * @return true if verification should be performed
9945     */
9946    private boolean isVerificationEnabled(int userId, int installFlags) {
9947        if (!DEFAULT_VERIFY_ENABLE) {
9948            return false;
9949        }
9950        // TODO: fix b/25118622; don't bypass verification
9951        if (Build.IS_DEBUGGABLE && (installFlags & PackageManager.INSTALL_QUICK) != 0) {
9952            return false;
9953        }
9954
9955        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9956
9957        // Check if installing from ADB
9958        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9959            // Do not run verification in a test harness environment
9960            if (ActivityManager.isRunningInTestHarness()) {
9961                return false;
9962            }
9963            if (ensureVerifyAppsEnabled) {
9964                return true;
9965            }
9966            // Check if the developer does not want package verification for ADB installs
9967            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9968                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9969                return false;
9970            }
9971        }
9972
9973        if (ensureVerifyAppsEnabled) {
9974            return true;
9975        }
9976
9977        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9978                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9979    }
9980
9981    @Override
9982    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9983            throws RemoteException {
9984        mContext.enforceCallingOrSelfPermission(
9985                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9986                "Only intentfilter verification agents can verify applications");
9987
9988        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9989        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9990                Binder.getCallingUid(), verificationCode, failedDomains);
9991        msg.arg1 = id;
9992        msg.obj = response;
9993        mHandler.sendMessage(msg);
9994    }
9995
9996    @Override
9997    public int getIntentVerificationStatus(String packageName, int userId) {
9998        synchronized (mPackages) {
9999            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
10000        }
10001    }
10002
10003    @Override
10004    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
10005        mContext.enforceCallingOrSelfPermission(
10006                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10007
10008        boolean result = false;
10009        synchronized (mPackages) {
10010            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10011        }
10012        if (result) {
10013            scheduleWritePackageRestrictionsLocked(userId);
10014        }
10015        return result;
10016    }
10017
10018    @Override
10019    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10020        synchronized (mPackages) {
10021            return mSettings.getIntentFilterVerificationsLPr(packageName);
10022        }
10023    }
10024
10025    @Override
10026    public List<IntentFilter> getAllIntentFilters(String packageName) {
10027        if (TextUtils.isEmpty(packageName)) {
10028            return Collections.<IntentFilter>emptyList();
10029        }
10030        synchronized (mPackages) {
10031            PackageParser.Package pkg = mPackages.get(packageName);
10032            if (pkg == null || pkg.activities == null) {
10033                return Collections.<IntentFilter>emptyList();
10034            }
10035            final int count = pkg.activities.size();
10036            ArrayList<IntentFilter> result = new ArrayList<>();
10037            for (int n=0; n<count; n++) {
10038                PackageParser.Activity activity = pkg.activities.get(n);
10039                if (activity.intents != null || activity.intents.size() > 0) {
10040                    result.addAll(activity.intents);
10041                }
10042            }
10043            return result;
10044        }
10045    }
10046
10047    @Override
10048    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10049        mContext.enforceCallingOrSelfPermission(
10050                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10051
10052        synchronized (mPackages) {
10053            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10054            if (packageName != null) {
10055                result |= updateIntentVerificationStatus(packageName,
10056                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10057                        userId);
10058                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10059                        packageName, userId);
10060            }
10061            return result;
10062        }
10063    }
10064
10065    @Override
10066    public String getDefaultBrowserPackageName(int userId) {
10067        synchronized (mPackages) {
10068            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10069        }
10070    }
10071
10072    /**
10073     * Get the "allow unknown sources" setting.
10074     *
10075     * @return the current "allow unknown sources" setting
10076     */
10077    private int getUnknownSourcesSettings() {
10078        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10079                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10080                -1);
10081    }
10082
10083    @Override
10084    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10085        final int uid = Binder.getCallingUid();
10086        // writer
10087        synchronized (mPackages) {
10088            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10089            if (targetPackageSetting == null) {
10090                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10091            }
10092
10093            PackageSetting installerPackageSetting;
10094            if (installerPackageName != null) {
10095                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10096                if (installerPackageSetting == null) {
10097                    throw new IllegalArgumentException("Unknown installer package: "
10098                            + installerPackageName);
10099                }
10100            } else {
10101                installerPackageSetting = null;
10102            }
10103
10104            Signature[] callerSignature;
10105            Object obj = mSettings.getUserIdLPr(uid);
10106            if (obj != null) {
10107                if (obj instanceof SharedUserSetting) {
10108                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10109                } else if (obj instanceof PackageSetting) {
10110                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10111                } else {
10112                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10113                }
10114            } else {
10115                throw new SecurityException("Unknown calling uid " + uid);
10116            }
10117
10118            // Verify: can't set installerPackageName to a package that is
10119            // not signed with the same cert as the caller.
10120            if (installerPackageSetting != null) {
10121                if (compareSignatures(callerSignature,
10122                        installerPackageSetting.signatures.mSignatures)
10123                        != PackageManager.SIGNATURE_MATCH) {
10124                    throw new SecurityException(
10125                            "Caller does not have same cert as new installer package "
10126                            + installerPackageName);
10127                }
10128            }
10129
10130            // Verify: if target already has an installer package, it must
10131            // be signed with the same cert as the caller.
10132            if (targetPackageSetting.installerPackageName != null) {
10133                PackageSetting setting = mSettings.mPackages.get(
10134                        targetPackageSetting.installerPackageName);
10135                // If the currently set package isn't valid, then it's always
10136                // okay to change it.
10137                if (setting != null) {
10138                    if (compareSignatures(callerSignature,
10139                            setting.signatures.mSignatures)
10140                            != PackageManager.SIGNATURE_MATCH) {
10141                        throw new SecurityException(
10142                                "Caller does not have same cert as old installer package "
10143                                + targetPackageSetting.installerPackageName);
10144                    }
10145                }
10146            }
10147
10148            // Okay!
10149            targetPackageSetting.installerPackageName = installerPackageName;
10150            scheduleWriteSettingsLocked();
10151        }
10152    }
10153
10154    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10155        // Queue up an async operation since the package installation may take a little while.
10156        mHandler.post(new Runnable() {
10157            public void run() {
10158                mHandler.removeCallbacks(this);
10159                 // Result object to be returned
10160                PackageInstalledInfo res = new PackageInstalledInfo();
10161                res.returnCode = currentStatus;
10162                res.uid = -1;
10163                res.pkg = null;
10164                res.removedInfo = new PackageRemovedInfo();
10165                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10166                    args.doPreInstall(res.returnCode);
10167                    synchronized (mInstallLock) {
10168                        installPackageTracedLI(args, res);
10169                    }
10170                    args.doPostInstall(res.returnCode, res.uid);
10171                }
10172
10173                // A restore should be performed at this point if (a) the install
10174                // succeeded, (b) the operation is not an update, and (c) the new
10175                // package has not opted out of backup participation.
10176                final boolean update = res.removedInfo.removedPackage != null;
10177                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10178                boolean doRestore = !update
10179                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10180
10181                // Set up the post-install work request bookkeeping.  This will be used
10182                // and cleaned up by the post-install event handling regardless of whether
10183                // there's a restore pass performed.  Token values are >= 1.
10184                int token;
10185                if (mNextInstallToken < 0) mNextInstallToken = 1;
10186                token = mNextInstallToken++;
10187
10188                PostInstallData data = new PostInstallData(args, res);
10189                mRunningInstalls.put(token, data);
10190                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10191
10192                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10193                    // Pass responsibility to the Backup Manager.  It will perform a
10194                    // restore if appropriate, then pass responsibility back to the
10195                    // Package Manager to run the post-install observer callbacks
10196                    // and broadcasts.
10197                    IBackupManager bm = IBackupManager.Stub.asInterface(
10198                            ServiceManager.getService(Context.BACKUP_SERVICE));
10199                    if (bm != null) {
10200                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10201                                + " to BM for possible restore");
10202                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10203                        try {
10204                            // TODO: http://b/22388012
10205                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
10206                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10207                            } else {
10208                                doRestore = false;
10209                            }
10210                        } catch (RemoteException e) {
10211                            // can't happen; the backup manager is local
10212                        } catch (Exception e) {
10213                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10214                            doRestore = false;
10215                        }
10216                    } else {
10217                        Slog.e(TAG, "Backup Manager not found!");
10218                        doRestore = false;
10219                    }
10220                }
10221
10222                if (!doRestore) {
10223                    // No restore possible, or the Backup Manager was mysteriously not
10224                    // available -- just fire the post-install work request directly.
10225                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10226
10227                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
10228
10229                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10230                    mHandler.sendMessage(msg);
10231                }
10232            }
10233        });
10234    }
10235
10236    private abstract class HandlerParams {
10237        private static final int MAX_RETRIES = 4;
10238
10239        /**
10240         * Number of times startCopy() has been attempted and had a non-fatal
10241         * error.
10242         */
10243        private int mRetries = 0;
10244
10245        /** User handle for the user requesting the information or installation. */
10246        private final UserHandle mUser;
10247        String traceMethod;
10248        int traceCookie;
10249
10250        HandlerParams(UserHandle user) {
10251            mUser = user;
10252        }
10253
10254        UserHandle getUser() {
10255            return mUser;
10256        }
10257
10258        HandlerParams setTraceMethod(String traceMethod) {
10259            this.traceMethod = traceMethod;
10260            return this;
10261        }
10262
10263        HandlerParams setTraceCookie(int traceCookie) {
10264            this.traceCookie = traceCookie;
10265            return this;
10266        }
10267
10268        final boolean startCopy() {
10269            boolean res;
10270            try {
10271                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10272
10273                if (++mRetries > MAX_RETRIES) {
10274                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10275                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10276                    handleServiceError();
10277                    return false;
10278                } else {
10279                    handleStartCopy();
10280                    res = true;
10281                }
10282            } catch (RemoteException e) {
10283                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10284                mHandler.sendEmptyMessage(MCS_RECONNECT);
10285                res = false;
10286            }
10287            handleReturnCode();
10288            return res;
10289        }
10290
10291        final void serviceError() {
10292            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10293            handleServiceError();
10294            handleReturnCode();
10295        }
10296
10297        abstract void handleStartCopy() throws RemoteException;
10298        abstract void handleServiceError();
10299        abstract void handleReturnCode();
10300    }
10301
10302    class MeasureParams extends HandlerParams {
10303        private final PackageStats mStats;
10304        private boolean mSuccess;
10305
10306        private final IPackageStatsObserver mObserver;
10307
10308        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10309            super(new UserHandle(stats.userHandle));
10310            mObserver = observer;
10311            mStats = stats;
10312        }
10313
10314        @Override
10315        public String toString() {
10316            return "MeasureParams{"
10317                + Integer.toHexString(System.identityHashCode(this))
10318                + " " + mStats.packageName + "}";
10319        }
10320
10321        @Override
10322        void handleStartCopy() throws RemoteException {
10323            synchronized (mInstallLock) {
10324                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10325            }
10326
10327            if (mSuccess) {
10328                final boolean mounted;
10329                if (Environment.isExternalStorageEmulated()) {
10330                    mounted = true;
10331                } else {
10332                    final String status = Environment.getExternalStorageState();
10333                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10334                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10335                }
10336
10337                if (mounted) {
10338                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10339
10340                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10341                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10342
10343                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10344                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10345
10346                    // Always subtract cache size, since it's a subdirectory
10347                    mStats.externalDataSize -= mStats.externalCacheSize;
10348
10349                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10350                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10351
10352                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10353                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10354                }
10355            }
10356        }
10357
10358        @Override
10359        void handleReturnCode() {
10360            if (mObserver != null) {
10361                try {
10362                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10363                } catch (RemoteException e) {
10364                    Slog.i(TAG, "Observer no longer exists.");
10365                }
10366            }
10367        }
10368
10369        @Override
10370        void handleServiceError() {
10371            Slog.e(TAG, "Could not measure application " + mStats.packageName
10372                            + " external storage");
10373        }
10374    }
10375
10376    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10377            throws RemoteException {
10378        long result = 0;
10379        for (File path : paths) {
10380            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10381        }
10382        return result;
10383    }
10384
10385    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10386        for (File path : paths) {
10387            try {
10388                mcs.clearDirectory(path.getAbsolutePath());
10389            } catch (RemoteException e) {
10390            }
10391        }
10392    }
10393
10394    static class OriginInfo {
10395        /**
10396         * Location where install is coming from, before it has been
10397         * copied/renamed into place. This could be a single monolithic APK
10398         * file, or a cluster directory. This location may be untrusted.
10399         */
10400        final File file;
10401        final String cid;
10402
10403        /**
10404         * Flag indicating that {@link #file} or {@link #cid} has already been
10405         * staged, meaning downstream users don't need to defensively copy the
10406         * contents.
10407         */
10408        final boolean staged;
10409
10410        /**
10411         * Flag indicating that {@link #file} or {@link #cid} is an already
10412         * installed app that is being moved.
10413         */
10414        final boolean existing;
10415
10416        final String resolvedPath;
10417        final File resolvedFile;
10418
10419        static OriginInfo fromNothing() {
10420            return new OriginInfo(null, null, false, false);
10421        }
10422
10423        static OriginInfo fromUntrustedFile(File file) {
10424            return new OriginInfo(file, null, false, false);
10425        }
10426
10427        static OriginInfo fromExistingFile(File file) {
10428            return new OriginInfo(file, null, false, true);
10429        }
10430
10431        static OriginInfo fromStagedFile(File file) {
10432            return new OriginInfo(file, null, true, false);
10433        }
10434
10435        static OriginInfo fromStagedContainer(String cid) {
10436            return new OriginInfo(null, cid, true, false);
10437        }
10438
10439        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10440            this.file = file;
10441            this.cid = cid;
10442            this.staged = staged;
10443            this.existing = existing;
10444
10445            if (cid != null) {
10446                resolvedPath = PackageHelper.getSdDir(cid);
10447                resolvedFile = new File(resolvedPath);
10448            } else if (file != null) {
10449                resolvedPath = file.getAbsolutePath();
10450                resolvedFile = file;
10451            } else {
10452                resolvedPath = null;
10453                resolvedFile = null;
10454            }
10455        }
10456    }
10457
10458    class MoveInfo {
10459        final int moveId;
10460        final String fromUuid;
10461        final String toUuid;
10462        final String packageName;
10463        final String dataAppName;
10464        final int appId;
10465        final String seinfo;
10466
10467        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10468                String dataAppName, int appId, String seinfo) {
10469            this.moveId = moveId;
10470            this.fromUuid = fromUuid;
10471            this.toUuid = toUuid;
10472            this.packageName = packageName;
10473            this.dataAppName = dataAppName;
10474            this.appId = appId;
10475            this.seinfo = seinfo;
10476        }
10477    }
10478
10479    class InstallParams extends HandlerParams {
10480        final OriginInfo origin;
10481        final MoveInfo move;
10482        final IPackageInstallObserver2 observer;
10483        int installFlags;
10484        final String installerPackageName;
10485        final String volumeUuid;
10486        final VerificationParams verificationParams;
10487        private InstallArgs mArgs;
10488        private int mRet;
10489        final String packageAbiOverride;
10490        final String[] grantedRuntimePermissions;
10491
10492        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10493                int installFlags, String installerPackageName, String volumeUuid,
10494                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10495                String[] grantedPermissions) {
10496            super(user);
10497            this.origin = origin;
10498            this.move = move;
10499            this.observer = observer;
10500            this.installFlags = installFlags;
10501            this.installerPackageName = installerPackageName;
10502            this.volumeUuid = volumeUuid;
10503            this.verificationParams = verificationParams;
10504            this.packageAbiOverride = packageAbiOverride;
10505            this.grantedRuntimePermissions = grantedPermissions;
10506        }
10507
10508        @Override
10509        public String toString() {
10510            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10511                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10512        }
10513
10514        public ManifestDigest getManifestDigest() {
10515            if (verificationParams == null) {
10516                return null;
10517            }
10518            return verificationParams.getManifestDigest();
10519        }
10520
10521        private int installLocationPolicy(PackageInfoLite pkgLite) {
10522            String packageName = pkgLite.packageName;
10523            int installLocation = pkgLite.installLocation;
10524            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10525            // reader
10526            synchronized (mPackages) {
10527                PackageParser.Package pkg = mPackages.get(packageName);
10528                if (pkg != null) {
10529                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10530                        // Check for downgrading.
10531                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10532                            try {
10533                                checkDowngrade(pkg, pkgLite);
10534                            } catch (PackageManagerException e) {
10535                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10536                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10537                            }
10538                        }
10539                        // Check for updated system application.
10540                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10541                            if (onSd) {
10542                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10543                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10544                            }
10545                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10546                        } else {
10547                            if (onSd) {
10548                                // Install flag overrides everything.
10549                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10550                            }
10551                            // If current upgrade specifies particular preference
10552                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10553                                // Application explicitly specified internal.
10554                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10555                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10556                                // App explictly prefers external. Let policy decide
10557                            } else {
10558                                // Prefer previous location
10559                                if (isExternal(pkg)) {
10560                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10561                                }
10562                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10563                            }
10564                        }
10565                    } else {
10566                        // Invalid install. Return error code
10567                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10568                    }
10569                }
10570            }
10571            // All the special cases have been taken care of.
10572            // Return result based on recommended install location.
10573            if (onSd) {
10574                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10575            }
10576            return pkgLite.recommendedInstallLocation;
10577        }
10578
10579        /*
10580         * Invoke remote method to get package information and install
10581         * location values. Override install location based on default
10582         * policy if needed and then create install arguments based
10583         * on the install location.
10584         */
10585        public void handleStartCopy() throws RemoteException {
10586            int ret = PackageManager.INSTALL_SUCCEEDED;
10587
10588            // If we're already staged, we've firmly committed to an install location
10589            if (origin.staged) {
10590                if (origin.file != null) {
10591                    installFlags |= PackageManager.INSTALL_INTERNAL;
10592                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10593                } else if (origin.cid != null) {
10594                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10595                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10596                } else {
10597                    throw new IllegalStateException("Invalid stage location");
10598                }
10599            }
10600
10601            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10602            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10603            PackageInfoLite pkgLite = null;
10604
10605            if (onInt && onSd) {
10606                // Check if both bits are set.
10607                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10608                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10609            } else {
10610                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10611                        packageAbiOverride);
10612
10613                /*
10614                 * If we have too little free space, try to free cache
10615                 * before giving up.
10616                 */
10617                if (!origin.staged && pkgLite.recommendedInstallLocation
10618                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10619                    // TODO: focus freeing disk space on the target device
10620                    final StorageManager storage = StorageManager.from(mContext);
10621                    final long lowThreshold = storage.getStorageLowBytes(
10622                            Environment.getDataDirectory());
10623
10624                    final long sizeBytes = mContainerService.calculateInstalledSize(
10625                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10626
10627                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10628                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10629                                installFlags, packageAbiOverride);
10630                    }
10631
10632                    /*
10633                     * The cache free must have deleted the file we
10634                     * downloaded to install.
10635                     *
10636                     * TODO: fix the "freeCache" call to not delete
10637                     *       the file we care about.
10638                     */
10639                    if (pkgLite.recommendedInstallLocation
10640                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10641                        pkgLite.recommendedInstallLocation
10642                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10643                    }
10644                }
10645            }
10646
10647            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10648                int loc = pkgLite.recommendedInstallLocation;
10649                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10650                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10651                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10652                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10653                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10654                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10655                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10656                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10657                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10658                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10659                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10660                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10661                } else {
10662                    // Override with defaults if needed.
10663                    loc = installLocationPolicy(pkgLite);
10664                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10665                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10666                    } else if (!onSd && !onInt) {
10667                        // Override install location with flags
10668                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10669                            // Set the flag to install on external media.
10670                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10671                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10672                        } else {
10673                            // Make sure the flag for installing on external
10674                            // media is unset
10675                            installFlags |= PackageManager.INSTALL_INTERNAL;
10676                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10677                        }
10678                    }
10679                }
10680            }
10681
10682            final InstallArgs args = createInstallArgs(this);
10683            mArgs = args;
10684
10685            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10686                // TODO: http://b/22976637
10687                // Apps installed for "all" users use the device owner to verify the app
10688                UserHandle verifierUser = getUser();
10689                if (verifierUser == UserHandle.ALL) {
10690                    verifierUser = UserHandle.SYSTEM;
10691                }
10692
10693                /*
10694                 * Determine if we have any installed package verifiers. If we
10695                 * do, then we'll defer to them to verify the packages.
10696                 */
10697                final int requiredUid = mRequiredVerifierPackage == null ? -1
10698                        : getPackageUid(mRequiredVerifierPackage, verifierUser.getIdentifier());
10699                if (!origin.existing && requiredUid != -1
10700                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
10701                    final Intent verification = new Intent(
10702                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10703                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10704                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10705                            PACKAGE_MIME_TYPE);
10706                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10707
10708                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10709                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10710                            verifierUser.getIdentifier());
10711
10712                    if (DEBUG_VERIFY) {
10713                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10714                                + verification.toString() + " with " + pkgLite.verifiers.length
10715                                + " optional verifiers");
10716                    }
10717
10718                    final int verificationId = mPendingVerificationToken++;
10719
10720                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10721
10722                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10723                            installerPackageName);
10724
10725                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10726                            installFlags);
10727
10728                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10729                            pkgLite.packageName);
10730
10731                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10732                            pkgLite.versionCode);
10733
10734                    if (verificationParams != null) {
10735                        if (verificationParams.getVerificationURI() != null) {
10736                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10737                                 verificationParams.getVerificationURI());
10738                        }
10739                        if (verificationParams.getOriginatingURI() != null) {
10740                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10741                                  verificationParams.getOriginatingURI());
10742                        }
10743                        if (verificationParams.getReferrer() != null) {
10744                            verification.putExtra(Intent.EXTRA_REFERRER,
10745                                  verificationParams.getReferrer());
10746                        }
10747                        if (verificationParams.getOriginatingUid() >= 0) {
10748                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10749                                  verificationParams.getOriginatingUid());
10750                        }
10751                        if (verificationParams.getInstallerUid() >= 0) {
10752                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10753                                  verificationParams.getInstallerUid());
10754                        }
10755                    }
10756
10757                    final PackageVerificationState verificationState = new PackageVerificationState(
10758                            requiredUid, args);
10759
10760                    mPendingVerification.append(verificationId, verificationState);
10761
10762                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10763                            receivers, verificationState);
10764
10765                    /*
10766                     * If any sufficient verifiers were listed in the package
10767                     * manifest, attempt to ask them.
10768                     */
10769                    if (sufficientVerifiers != null) {
10770                        final int N = sufficientVerifiers.size();
10771                        if (N == 0) {
10772                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10773                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10774                        } else {
10775                            for (int i = 0; i < N; i++) {
10776                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10777
10778                                final Intent sufficientIntent = new Intent(verification);
10779                                sufficientIntent.setComponent(verifierComponent);
10780                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
10781                            }
10782                        }
10783                    }
10784
10785                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10786                            mRequiredVerifierPackage, receivers);
10787                    if (ret == PackageManager.INSTALL_SUCCEEDED
10788                            && mRequiredVerifierPackage != null) {
10789                        Trace.asyncTraceBegin(
10790                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
10791                        /*
10792                         * Send the intent to the required verification agent,
10793                         * but only start the verification timeout after the
10794                         * target BroadcastReceivers have run.
10795                         */
10796                        verification.setComponent(requiredVerifierComponent);
10797                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
10798                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10799                                new BroadcastReceiver() {
10800                                    @Override
10801                                    public void onReceive(Context context, Intent intent) {
10802                                        final Message msg = mHandler
10803                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10804                                        msg.arg1 = verificationId;
10805                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10806                                    }
10807                                }, null, 0, null, null);
10808
10809                        /*
10810                         * We don't want the copy to proceed until verification
10811                         * succeeds, so null out this field.
10812                         */
10813                        mArgs = null;
10814                    }
10815                } else {
10816                    /*
10817                     * No package verification is enabled, so immediately start
10818                     * the remote call to initiate copy using temporary file.
10819                     */
10820                    ret = args.copyApk(mContainerService, true);
10821                }
10822            }
10823
10824            mRet = ret;
10825        }
10826
10827        @Override
10828        void handleReturnCode() {
10829            // If mArgs is null, then MCS couldn't be reached. When it
10830            // reconnects, it will try again to install. At that point, this
10831            // will succeed.
10832            if (mArgs != null) {
10833                processPendingInstall(mArgs, mRet);
10834            }
10835        }
10836
10837        @Override
10838        void handleServiceError() {
10839            mArgs = createInstallArgs(this);
10840            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10841        }
10842
10843        public boolean isForwardLocked() {
10844            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10845        }
10846    }
10847
10848    /**
10849     * Used during creation of InstallArgs
10850     *
10851     * @param installFlags package installation flags
10852     * @return true if should be installed on external storage
10853     */
10854    private static boolean installOnExternalAsec(int installFlags) {
10855        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10856            return false;
10857        }
10858        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10859            return true;
10860        }
10861        return false;
10862    }
10863
10864    /**
10865     * Used during creation of InstallArgs
10866     *
10867     * @param installFlags package installation flags
10868     * @return true if should be installed as forward locked
10869     */
10870    private static boolean installForwardLocked(int installFlags) {
10871        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10872    }
10873
10874    private InstallArgs createInstallArgs(InstallParams params) {
10875        if (params.move != null) {
10876            return new MoveInstallArgs(params);
10877        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10878            return new AsecInstallArgs(params);
10879        } else {
10880            return new FileInstallArgs(params);
10881        }
10882    }
10883
10884    /**
10885     * Create args that describe an existing installed package. Typically used
10886     * when cleaning up old installs, or used as a move source.
10887     */
10888    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10889            String resourcePath, String[] instructionSets) {
10890        final boolean isInAsec;
10891        if (installOnExternalAsec(installFlags)) {
10892            /* Apps on SD card are always in ASEC containers. */
10893            isInAsec = true;
10894        } else if (installForwardLocked(installFlags)
10895                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10896            /*
10897             * Forward-locked apps are only in ASEC containers if they're the
10898             * new style
10899             */
10900            isInAsec = true;
10901        } else {
10902            isInAsec = false;
10903        }
10904
10905        if (isInAsec) {
10906            return new AsecInstallArgs(codePath, instructionSets,
10907                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10908        } else {
10909            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10910        }
10911    }
10912
10913    static abstract class InstallArgs {
10914        /** @see InstallParams#origin */
10915        final OriginInfo origin;
10916        /** @see InstallParams#move */
10917        final MoveInfo move;
10918
10919        final IPackageInstallObserver2 observer;
10920        // Always refers to PackageManager flags only
10921        final int installFlags;
10922        final String installerPackageName;
10923        final String volumeUuid;
10924        final ManifestDigest manifestDigest;
10925        final UserHandle user;
10926        final String abiOverride;
10927        final String[] installGrantPermissions;
10928        /** If non-null, drop an async trace when the install completes */
10929        final String traceMethod;
10930        final int traceCookie;
10931
10932        // The list of instruction sets supported by this app. This is currently
10933        // only used during the rmdex() phase to clean up resources. We can get rid of this
10934        // if we move dex files under the common app path.
10935        /* nullable */ String[] instructionSets;
10936
10937        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10938                int installFlags, String installerPackageName, String volumeUuid,
10939                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10940                String abiOverride, String[] installGrantPermissions,
10941                String traceMethod, int traceCookie) {
10942            this.origin = origin;
10943            this.move = move;
10944            this.installFlags = installFlags;
10945            this.observer = observer;
10946            this.installerPackageName = installerPackageName;
10947            this.volumeUuid = volumeUuid;
10948            this.manifestDigest = manifestDigest;
10949            this.user = user;
10950            this.instructionSets = instructionSets;
10951            this.abiOverride = abiOverride;
10952            this.installGrantPermissions = installGrantPermissions;
10953            this.traceMethod = traceMethod;
10954            this.traceCookie = traceCookie;
10955        }
10956
10957        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10958        abstract int doPreInstall(int status);
10959
10960        /**
10961         * Rename package into final resting place. All paths on the given
10962         * scanned package should be updated to reflect the rename.
10963         */
10964        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10965        abstract int doPostInstall(int status, int uid);
10966
10967        /** @see PackageSettingBase#codePathString */
10968        abstract String getCodePath();
10969        /** @see PackageSettingBase#resourcePathString */
10970        abstract String getResourcePath();
10971
10972        // Need installer lock especially for dex file removal.
10973        abstract void cleanUpResourcesLI();
10974        abstract boolean doPostDeleteLI(boolean delete);
10975
10976        /**
10977         * Called before the source arguments are copied. This is used mostly
10978         * for MoveParams when it needs to read the source file to put it in the
10979         * destination.
10980         */
10981        int doPreCopy() {
10982            return PackageManager.INSTALL_SUCCEEDED;
10983        }
10984
10985        /**
10986         * Called after the source arguments are copied. This is used mostly for
10987         * MoveParams when it needs to read the source file to put it in the
10988         * destination.
10989         *
10990         * @return
10991         */
10992        int doPostCopy(int uid) {
10993            return PackageManager.INSTALL_SUCCEEDED;
10994        }
10995
10996        protected boolean isFwdLocked() {
10997            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10998        }
10999
11000        protected boolean isExternalAsec() {
11001            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11002        }
11003
11004        UserHandle getUser() {
11005            return user;
11006        }
11007    }
11008
11009    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
11010        if (!allCodePaths.isEmpty()) {
11011            if (instructionSets == null) {
11012                throw new IllegalStateException("instructionSet == null");
11013            }
11014            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
11015            for (String codePath : allCodePaths) {
11016                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
11017                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
11018                    if (retCode < 0) {
11019                        Slog.w(TAG, "Couldn't remove dex file for package: "
11020                                + " at location " + codePath + ", retcode=" + retCode);
11021                        // we don't consider this to be a failure of the core package deletion
11022                    }
11023                }
11024            }
11025        }
11026    }
11027
11028    /**
11029     * Logic to handle installation of non-ASEC applications, including copying
11030     * and renaming logic.
11031     */
11032    class FileInstallArgs extends InstallArgs {
11033        private File codeFile;
11034        private File resourceFile;
11035
11036        // Example topology:
11037        // /data/app/com.example/base.apk
11038        // /data/app/com.example/split_foo.apk
11039        // /data/app/com.example/lib/arm/libfoo.so
11040        // /data/app/com.example/lib/arm64/libfoo.so
11041        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11042
11043        /** New install */
11044        FileInstallArgs(InstallParams params) {
11045            super(params.origin, params.move, params.observer, params.installFlags,
11046                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11047                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11048                    params.grantedRuntimePermissions,
11049                    params.traceMethod, params.traceCookie);
11050            if (isFwdLocked()) {
11051                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11052            }
11053        }
11054
11055        /** Existing install */
11056        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11057            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
11058                    null, null, null, 0);
11059            this.codeFile = (codePath != null) ? new File(codePath) : null;
11060            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11061        }
11062
11063        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11064            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
11065            try {
11066                return doCopyApk(imcs, temp);
11067            } finally {
11068                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11069            }
11070        }
11071
11072        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11073            if (origin.staged) {
11074                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11075                codeFile = origin.file;
11076                resourceFile = origin.file;
11077                return PackageManager.INSTALL_SUCCEEDED;
11078            }
11079
11080            try {
11081                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
11082                codeFile = tempDir;
11083                resourceFile = tempDir;
11084            } catch (IOException e) {
11085                Slog.w(TAG, "Failed to create copy file: " + e);
11086                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11087            }
11088
11089            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11090                @Override
11091                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11092                    if (!FileUtils.isValidExtFilename(name)) {
11093                        throw new IllegalArgumentException("Invalid filename: " + name);
11094                    }
11095                    try {
11096                        final File file = new File(codeFile, name);
11097                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11098                                O_RDWR | O_CREAT, 0644);
11099                        Os.chmod(file.getAbsolutePath(), 0644);
11100                        return new ParcelFileDescriptor(fd);
11101                    } catch (ErrnoException e) {
11102                        throw new RemoteException("Failed to open: " + e.getMessage());
11103                    }
11104                }
11105            };
11106
11107            int ret = PackageManager.INSTALL_SUCCEEDED;
11108            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11109            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11110                Slog.e(TAG, "Failed to copy package");
11111                return ret;
11112            }
11113
11114            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11115            NativeLibraryHelper.Handle handle = null;
11116            try {
11117                handle = NativeLibraryHelper.Handle.create(codeFile);
11118                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11119                        abiOverride);
11120            } catch (IOException e) {
11121                Slog.e(TAG, "Copying native libraries failed", e);
11122                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11123            } finally {
11124                IoUtils.closeQuietly(handle);
11125            }
11126
11127            return ret;
11128        }
11129
11130        int doPreInstall(int status) {
11131            if (status != PackageManager.INSTALL_SUCCEEDED) {
11132                cleanUp();
11133            }
11134            return status;
11135        }
11136
11137        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11138            if (status != PackageManager.INSTALL_SUCCEEDED) {
11139                cleanUp();
11140                return false;
11141            }
11142
11143            final File targetDir = codeFile.getParentFile();
11144            final File beforeCodeFile = codeFile;
11145            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11146
11147            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11148            try {
11149                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11150            } catch (ErrnoException e) {
11151                Slog.w(TAG, "Failed to rename", e);
11152                return false;
11153            }
11154
11155            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11156                Slog.w(TAG, "Failed to restorecon");
11157                return false;
11158            }
11159
11160            // Reflect the rename internally
11161            codeFile = afterCodeFile;
11162            resourceFile = afterCodeFile;
11163
11164            // Reflect the rename in scanned details
11165            pkg.codePath = afterCodeFile.getAbsolutePath();
11166            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11167                    pkg.baseCodePath);
11168            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11169                    pkg.splitCodePaths);
11170
11171            // Reflect the rename in app info
11172            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11173            pkg.applicationInfo.setCodePath(pkg.codePath);
11174            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11175            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11176            pkg.applicationInfo.setResourcePath(pkg.codePath);
11177            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11178            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11179
11180            return true;
11181        }
11182
11183        int doPostInstall(int status, int uid) {
11184            if (status != PackageManager.INSTALL_SUCCEEDED) {
11185                cleanUp();
11186            }
11187            return status;
11188        }
11189
11190        @Override
11191        String getCodePath() {
11192            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11193        }
11194
11195        @Override
11196        String getResourcePath() {
11197            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11198        }
11199
11200        private boolean cleanUp() {
11201            if (codeFile == null || !codeFile.exists()) {
11202                return false;
11203            }
11204
11205            if (codeFile.isDirectory()) {
11206                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11207            } else {
11208                codeFile.delete();
11209            }
11210
11211            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11212                resourceFile.delete();
11213            }
11214
11215            return true;
11216        }
11217
11218        void cleanUpResourcesLI() {
11219            // Try enumerating all code paths before deleting
11220            List<String> allCodePaths = Collections.EMPTY_LIST;
11221            if (codeFile != null && codeFile.exists()) {
11222                try {
11223                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11224                    allCodePaths = pkg.getAllCodePaths();
11225                } catch (PackageParserException e) {
11226                    // Ignored; we tried our best
11227                }
11228            }
11229
11230            cleanUp();
11231            removeDexFiles(allCodePaths, instructionSets);
11232        }
11233
11234        boolean doPostDeleteLI(boolean delete) {
11235            // XXX err, shouldn't we respect the delete flag?
11236            cleanUpResourcesLI();
11237            return true;
11238        }
11239    }
11240
11241    private boolean isAsecExternal(String cid) {
11242        final String asecPath = PackageHelper.getSdFilesystem(cid);
11243        return !asecPath.startsWith(mAsecInternalPath);
11244    }
11245
11246    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11247            PackageManagerException {
11248        if (copyRet < 0) {
11249            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11250                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11251                throw new PackageManagerException(copyRet, message);
11252            }
11253        }
11254    }
11255
11256    /**
11257     * Extract the MountService "container ID" from the full code path of an
11258     * .apk.
11259     */
11260    static String cidFromCodePath(String fullCodePath) {
11261        int eidx = fullCodePath.lastIndexOf("/");
11262        String subStr1 = fullCodePath.substring(0, eidx);
11263        int sidx = subStr1.lastIndexOf("/");
11264        return subStr1.substring(sidx+1, eidx);
11265    }
11266
11267    /**
11268     * Logic to handle installation of ASEC applications, including copying and
11269     * renaming logic.
11270     */
11271    class AsecInstallArgs extends InstallArgs {
11272        static final String RES_FILE_NAME = "pkg.apk";
11273        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11274
11275        String cid;
11276        String packagePath;
11277        String resourcePath;
11278
11279        /** New install */
11280        AsecInstallArgs(InstallParams params) {
11281            super(params.origin, params.move, params.observer, params.installFlags,
11282                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11283                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11284                    params.grantedRuntimePermissions,
11285                    params.traceMethod, params.traceCookie);
11286        }
11287
11288        /** Existing install */
11289        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11290                        boolean isExternal, boolean isForwardLocked) {
11291            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11292                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11293                    instructionSets, null, null, null, 0);
11294            // Hackily pretend we're still looking at a full code path
11295            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11296                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11297            }
11298
11299            // Extract cid from fullCodePath
11300            int eidx = fullCodePath.lastIndexOf("/");
11301            String subStr1 = fullCodePath.substring(0, eidx);
11302            int sidx = subStr1.lastIndexOf("/");
11303            cid = subStr1.substring(sidx+1, eidx);
11304            setMountPath(subStr1);
11305        }
11306
11307        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11308            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11309                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11310                    instructionSets, null, null, null, 0);
11311            this.cid = cid;
11312            setMountPath(PackageHelper.getSdDir(cid));
11313        }
11314
11315        void createCopyFile() {
11316            cid = mInstallerService.allocateExternalStageCidLegacy();
11317        }
11318
11319        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11320            if (origin.staged) {
11321                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11322                cid = origin.cid;
11323                setMountPath(PackageHelper.getSdDir(cid));
11324                return PackageManager.INSTALL_SUCCEEDED;
11325            }
11326
11327            if (temp) {
11328                createCopyFile();
11329            } else {
11330                /*
11331                 * Pre-emptively destroy the container since it's destroyed if
11332                 * copying fails due to it existing anyway.
11333                 */
11334                PackageHelper.destroySdDir(cid);
11335            }
11336
11337            final String newMountPath = imcs.copyPackageToContainer(
11338                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11339                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11340
11341            if (newMountPath != null) {
11342                setMountPath(newMountPath);
11343                return PackageManager.INSTALL_SUCCEEDED;
11344            } else {
11345                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11346            }
11347        }
11348
11349        @Override
11350        String getCodePath() {
11351            return packagePath;
11352        }
11353
11354        @Override
11355        String getResourcePath() {
11356            return resourcePath;
11357        }
11358
11359        int doPreInstall(int status) {
11360            if (status != PackageManager.INSTALL_SUCCEEDED) {
11361                // Destroy container
11362                PackageHelper.destroySdDir(cid);
11363            } else {
11364                boolean mounted = PackageHelper.isContainerMounted(cid);
11365                if (!mounted) {
11366                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11367                            Process.SYSTEM_UID);
11368                    if (newMountPath != null) {
11369                        setMountPath(newMountPath);
11370                    } else {
11371                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11372                    }
11373                }
11374            }
11375            return status;
11376        }
11377
11378        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11379            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11380            String newMountPath = null;
11381            if (PackageHelper.isContainerMounted(cid)) {
11382                // Unmount the container
11383                if (!PackageHelper.unMountSdDir(cid)) {
11384                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11385                    return false;
11386                }
11387            }
11388            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11389                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11390                        " which might be stale. Will try to clean up.");
11391                // Clean up the stale container and proceed to recreate.
11392                if (!PackageHelper.destroySdDir(newCacheId)) {
11393                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11394                    return false;
11395                }
11396                // Successfully cleaned up stale container. Try to rename again.
11397                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11398                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11399                            + " inspite of cleaning it up.");
11400                    return false;
11401                }
11402            }
11403            if (!PackageHelper.isContainerMounted(newCacheId)) {
11404                Slog.w(TAG, "Mounting container " + newCacheId);
11405                newMountPath = PackageHelper.mountSdDir(newCacheId,
11406                        getEncryptKey(), Process.SYSTEM_UID);
11407            } else {
11408                newMountPath = PackageHelper.getSdDir(newCacheId);
11409            }
11410            if (newMountPath == null) {
11411                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11412                return false;
11413            }
11414            Log.i(TAG, "Succesfully renamed " + cid +
11415                    " to " + newCacheId +
11416                    " at new path: " + newMountPath);
11417            cid = newCacheId;
11418
11419            final File beforeCodeFile = new File(packagePath);
11420            setMountPath(newMountPath);
11421            final File afterCodeFile = new File(packagePath);
11422
11423            // Reflect the rename in scanned details
11424            pkg.codePath = afterCodeFile.getAbsolutePath();
11425            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11426                    pkg.baseCodePath);
11427            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11428                    pkg.splitCodePaths);
11429
11430            // Reflect the rename in app info
11431            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11432            pkg.applicationInfo.setCodePath(pkg.codePath);
11433            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11434            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11435            pkg.applicationInfo.setResourcePath(pkg.codePath);
11436            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11437            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11438
11439            return true;
11440        }
11441
11442        private void setMountPath(String mountPath) {
11443            final File mountFile = new File(mountPath);
11444
11445            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11446            if (monolithicFile.exists()) {
11447                packagePath = monolithicFile.getAbsolutePath();
11448                if (isFwdLocked()) {
11449                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11450                } else {
11451                    resourcePath = packagePath;
11452                }
11453            } else {
11454                packagePath = mountFile.getAbsolutePath();
11455                resourcePath = packagePath;
11456            }
11457        }
11458
11459        int doPostInstall(int status, int uid) {
11460            if (status != PackageManager.INSTALL_SUCCEEDED) {
11461                cleanUp();
11462            } else {
11463                final int groupOwner;
11464                final String protectedFile;
11465                if (isFwdLocked()) {
11466                    groupOwner = UserHandle.getSharedAppGid(uid);
11467                    protectedFile = RES_FILE_NAME;
11468                } else {
11469                    groupOwner = -1;
11470                    protectedFile = null;
11471                }
11472
11473                if (uid < Process.FIRST_APPLICATION_UID
11474                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11475                    Slog.e(TAG, "Failed to finalize " + cid);
11476                    PackageHelper.destroySdDir(cid);
11477                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11478                }
11479
11480                boolean mounted = PackageHelper.isContainerMounted(cid);
11481                if (!mounted) {
11482                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11483                }
11484            }
11485            return status;
11486        }
11487
11488        private void cleanUp() {
11489            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11490
11491            // Destroy secure container
11492            PackageHelper.destroySdDir(cid);
11493        }
11494
11495        private List<String> getAllCodePaths() {
11496            final File codeFile = new File(getCodePath());
11497            if (codeFile != null && codeFile.exists()) {
11498                try {
11499                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11500                    return pkg.getAllCodePaths();
11501                } catch (PackageParserException e) {
11502                    // Ignored; we tried our best
11503                }
11504            }
11505            return Collections.EMPTY_LIST;
11506        }
11507
11508        void cleanUpResourcesLI() {
11509            // Enumerate all code paths before deleting
11510            cleanUpResourcesLI(getAllCodePaths());
11511        }
11512
11513        private void cleanUpResourcesLI(List<String> allCodePaths) {
11514            cleanUp();
11515            removeDexFiles(allCodePaths, instructionSets);
11516        }
11517
11518        String getPackageName() {
11519            return getAsecPackageName(cid);
11520        }
11521
11522        boolean doPostDeleteLI(boolean delete) {
11523            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11524            final List<String> allCodePaths = getAllCodePaths();
11525            boolean mounted = PackageHelper.isContainerMounted(cid);
11526            if (mounted) {
11527                // Unmount first
11528                if (PackageHelper.unMountSdDir(cid)) {
11529                    mounted = false;
11530                }
11531            }
11532            if (!mounted && delete) {
11533                cleanUpResourcesLI(allCodePaths);
11534            }
11535            return !mounted;
11536        }
11537
11538        @Override
11539        int doPreCopy() {
11540            if (isFwdLocked()) {
11541                if (!PackageHelper.fixSdPermissions(cid,
11542                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11543                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11544                }
11545            }
11546
11547            return PackageManager.INSTALL_SUCCEEDED;
11548        }
11549
11550        @Override
11551        int doPostCopy(int uid) {
11552            if (isFwdLocked()) {
11553                if (uid < Process.FIRST_APPLICATION_UID
11554                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11555                                RES_FILE_NAME)) {
11556                    Slog.e(TAG, "Failed to finalize " + cid);
11557                    PackageHelper.destroySdDir(cid);
11558                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11559                }
11560            }
11561
11562            return PackageManager.INSTALL_SUCCEEDED;
11563        }
11564    }
11565
11566    /**
11567     * Logic to handle movement of existing installed applications.
11568     */
11569    class MoveInstallArgs extends InstallArgs {
11570        private File codeFile;
11571        private File resourceFile;
11572
11573        /** New install */
11574        MoveInstallArgs(InstallParams params) {
11575            super(params.origin, params.move, params.observer, params.installFlags,
11576                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11577                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11578                    params.grantedRuntimePermissions,
11579                    params.traceMethod, params.traceCookie);
11580        }
11581
11582        int copyApk(IMediaContainerService imcs, boolean temp) {
11583            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11584                    + move.fromUuid + " to " + move.toUuid);
11585            synchronized (mInstaller) {
11586                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11587                        move.dataAppName, move.appId, move.seinfo) != 0) {
11588                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11589                }
11590            }
11591
11592            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11593            resourceFile = codeFile;
11594            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11595
11596            return PackageManager.INSTALL_SUCCEEDED;
11597        }
11598
11599        int doPreInstall(int status) {
11600            if (status != PackageManager.INSTALL_SUCCEEDED) {
11601                cleanUp(move.toUuid);
11602            }
11603            return status;
11604        }
11605
11606        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11607            if (status != PackageManager.INSTALL_SUCCEEDED) {
11608                cleanUp(move.toUuid);
11609                return false;
11610            }
11611
11612            // Reflect the move in app info
11613            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11614            pkg.applicationInfo.setCodePath(pkg.codePath);
11615            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11616            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11617            pkg.applicationInfo.setResourcePath(pkg.codePath);
11618            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11619            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11620
11621            return true;
11622        }
11623
11624        int doPostInstall(int status, int uid) {
11625            if (status == PackageManager.INSTALL_SUCCEEDED) {
11626                cleanUp(move.fromUuid);
11627            } else {
11628                cleanUp(move.toUuid);
11629            }
11630            return status;
11631        }
11632
11633        @Override
11634        String getCodePath() {
11635            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11636        }
11637
11638        @Override
11639        String getResourcePath() {
11640            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11641        }
11642
11643        private boolean cleanUp(String volumeUuid) {
11644            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11645                    move.dataAppName);
11646            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11647            synchronized (mInstallLock) {
11648                // Clean up both app data and code
11649                removeDataDirsLI(volumeUuid, move.packageName);
11650                if (codeFile.isDirectory()) {
11651                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11652                } else {
11653                    codeFile.delete();
11654                }
11655            }
11656            return true;
11657        }
11658
11659        void cleanUpResourcesLI() {
11660            throw new UnsupportedOperationException();
11661        }
11662
11663        boolean doPostDeleteLI(boolean delete) {
11664            throw new UnsupportedOperationException();
11665        }
11666    }
11667
11668    static String getAsecPackageName(String packageCid) {
11669        int idx = packageCid.lastIndexOf("-");
11670        if (idx == -1) {
11671            return packageCid;
11672        }
11673        return packageCid.substring(0, idx);
11674    }
11675
11676    // Utility method used to create code paths based on package name and available index.
11677    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11678        String idxStr = "";
11679        int idx = 1;
11680        // Fall back to default value of idx=1 if prefix is not
11681        // part of oldCodePath
11682        if (oldCodePath != null) {
11683            String subStr = oldCodePath;
11684            // Drop the suffix right away
11685            if (suffix != null && subStr.endsWith(suffix)) {
11686                subStr = subStr.substring(0, subStr.length() - suffix.length());
11687            }
11688            // If oldCodePath already contains prefix find out the
11689            // ending index to either increment or decrement.
11690            int sidx = subStr.lastIndexOf(prefix);
11691            if (sidx != -1) {
11692                subStr = subStr.substring(sidx + prefix.length());
11693                if (subStr != null) {
11694                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11695                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11696                    }
11697                    try {
11698                        idx = Integer.parseInt(subStr);
11699                        if (idx <= 1) {
11700                            idx++;
11701                        } else {
11702                            idx--;
11703                        }
11704                    } catch(NumberFormatException e) {
11705                    }
11706                }
11707            }
11708        }
11709        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11710        return prefix + idxStr;
11711    }
11712
11713    private File getNextCodePath(File targetDir, String packageName) {
11714        int suffix = 1;
11715        File result;
11716        do {
11717            result = new File(targetDir, packageName + "-" + suffix);
11718            suffix++;
11719        } while (result.exists());
11720        return result;
11721    }
11722
11723    // Utility method that returns the relative package path with respect
11724    // to the installation directory. Like say for /data/data/com.test-1.apk
11725    // string com.test-1 is returned.
11726    static String deriveCodePathName(String codePath) {
11727        if (codePath == null) {
11728            return null;
11729        }
11730        final File codeFile = new File(codePath);
11731        final String name = codeFile.getName();
11732        if (codeFile.isDirectory()) {
11733            return name;
11734        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11735            final int lastDot = name.lastIndexOf('.');
11736            return name.substring(0, lastDot);
11737        } else {
11738            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11739            return null;
11740        }
11741    }
11742
11743    class PackageInstalledInfo {
11744        String name;
11745        int uid;
11746        // The set of users that originally had this package installed.
11747        int[] origUsers;
11748        // The set of users that now have this package installed.
11749        int[] newUsers;
11750        PackageParser.Package pkg;
11751        int returnCode;
11752        String returnMsg;
11753        PackageRemovedInfo removedInfo;
11754
11755        public void setError(int code, String msg) {
11756            returnCode = code;
11757            returnMsg = msg;
11758            Slog.w(TAG, msg);
11759        }
11760
11761        public void setError(String msg, PackageParserException e) {
11762            returnCode = e.error;
11763            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11764            Slog.w(TAG, msg, e);
11765        }
11766
11767        public void setError(String msg, PackageManagerException e) {
11768            returnCode = e.error;
11769            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11770            Slog.w(TAG, msg, e);
11771        }
11772
11773        // In some error cases we want to convey more info back to the observer
11774        String origPackage;
11775        String origPermission;
11776    }
11777
11778    /*
11779     * Install a non-existing package.
11780     */
11781    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11782            UserHandle user, String installerPackageName, String volumeUuid,
11783            PackageInstalledInfo res) {
11784        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
11785
11786        // Remember this for later, in case we need to rollback this install
11787        String pkgName = pkg.packageName;
11788
11789        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11790        // TODO: b/23350563
11791        final boolean dataDirExists = Environment
11792                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists();
11793
11794        synchronized(mPackages) {
11795            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11796                // A package with the same name is already installed, though
11797                // it has been renamed to an older name.  The package we
11798                // are trying to install should be installed as an update to
11799                // the existing one, but that has not been requested, so bail.
11800                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11801                        + " without first uninstalling package running as "
11802                        + mSettings.mRenamedPackages.get(pkgName));
11803                return;
11804            }
11805            if (mPackages.containsKey(pkgName)) {
11806                // Don't allow installation over an existing package with the same name.
11807                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11808                        + " without first uninstalling.");
11809                return;
11810            }
11811        }
11812
11813        try {
11814            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
11815                    System.currentTimeMillis(), user);
11816
11817            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11818            // delete the partially installed application. the data directory will have to be
11819            // restored if it was already existing
11820            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11821                // remove package from internal structures.  Note that we want deletePackageX to
11822                // delete the package data and cache directories that it created in
11823                // scanPackageLocked, unless those directories existed before we even tried to
11824                // install.
11825                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11826                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11827                                res.removedInfo, true);
11828            }
11829
11830        } catch (PackageManagerException e) {
11831            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11832        }
11833
11834        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11835    }
11836
11837    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11838        // Can't rotate keys during boot or if sharedUser.
11839        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11840                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11841            return false;
11842        }
11843        // app is using upgradeKeySets; make sure all are valid
11844        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11845        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11846        for (int i = 0; i < upgradeKeySets.length; i++) {
11847            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11848                Slog.wtf(TAG, "Package "
11849                         + (oldPs.name != null ? oldPs.name : "<null>")
11850                         + " contains upgrade-key-set reference to unknown key-set: "
11851                         + upgradeKeySets[i]
11852                         + " reverting to signatures check.");
11853                return false;
11854            }
11855        }
11856        return true;
11857    }
11858
11859    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11860        // Upgrade keysets are being used.  Determine if new package has a superset of the
11861        // required keys.
11862        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11863        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11864        for (int i = 0; i < upgradeKeySets.length; i++) {
11865            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11866            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11867                return true;
11868            }
11869        }
11870        return false;
11871    }
11872
11873    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11874            UserHandle user, String installerPackageName, String volumeUuid,
11875            PackageInstalledInfo res) {
11876        final PackageParser.Package oldPackage;
11877        final String pkgName = pkg.packageName;
11878        final int[] allUsers;
11879        final boolean[] perUserInstalled;
11880
11881        // First find the old package info and check signatures
11882        synchronized(mPackages) {
11883            oldPackage = mPackages.get(pkgName);
11884            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11885            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11886            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11887                if(!checkUpgradeKeySetLP(ps, pkg)) {
11888                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11889                            "New package not signed by keys specified by upgrade-keysets: "
11890                            + pkgName);
11891                    return;
11892                }
11893            } else {
11894                // default to original signature matching
11895                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11896                    != PackageManager.SIGNATURE_MATCH) {
11897                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11898                            "New package has a different signature: " + pkgName);
11899                    return;
11900                }
11901            }
11902
11903            // In case of rollback, remember per-user/profile install state
11904            allUsers = sUserManager.getUserIds();
11905            perUserInstalled = new boolean[allUsers.length];
11906            for (int i = 0; i < allUsers.length; i++) {
11907                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11908            }
11909        }
11910
11911        boolean sysPkg = (isSystemApp(oldPackage));
11912        if (sysPkg) {
11913            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11914                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11915        } else {
11916            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11917                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11918        }
11919    }
11920
11921    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11922            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11923            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11924            String volumeUuid, PackageInstalledInfo res) {
11925        String pkgName = deletedPackage.packageName;
11926        boolean deletedPkg = true;
11927        boolean updatedSettings = false;
11928
11929        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11930                + deletedPackage);
11931        long origUpdateTime;
11932        if (pkg.mExtras != null) {
11933            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11934        } else {
11935            origUpdateTime = 0;
11936        }
11937
11938        // First delete the existing package while retaining the data directory
11939        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11940                res.removedInfo, true)) {
11941            // If the existing package wasn't successfully deleted
11942            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11943            deletedPkg = false;
11944        } else {
11945            // Successfully deleted the old package; proceed with replace.
11946
11947            // If deleted package lived in a container, give users a chance to
11948            // relinquish resources before killing.
11949            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11950                if (DEBUG_INSTALL) {
11951                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11952                }
11953                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11954                final ArrayList<String> pkgList = new ArrayList<String>(1);
11955                pkgList.add(deletedPackage.applicationInfo.packageName);
11956                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11957            }
11958
11959            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11960            try {
11961                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
11962                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11963                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11964                        perUserInstalled, res, user);
11965                updatedSettings = true;
11966            } catch (PackageManagerException e) {
11967                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11968            }
11969        }
11970
11971        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11972            // remove package from internal structures.  Note that we want deletePackageX to
11973            // delete the package data and cache directories that it created in
11974            // scanPackageLocked, unless those directories existed before we even tried to
11975            // install.
11976            if(updatedSettings) {
11977                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11978                deletePackageLI(
11979                        pkgName, null, true, allUsers, perUserInstalled,
11980                        PackageManager.DELETE_KEEP_DATA,
11981                                res.removedInfo, true);
11982            }
11983            // Since we failed to install the new package we need to restore the old
11984            // package that we deleted.
11985            if (deletedPkg) {
11986                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11987                File restoreFile = new File(deletedPackage.codePath);
11988                // Parse old package
11989                boolean oldExternal = isExternal(deletedPackage);
11990                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11991                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11992                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11993                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11994                try {
11995                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
11996                            null);
11997                } catch (PackageManagerException e) {
11998                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11999                            + e.getMessage());
12000                    return;
12001                }
12002                // Restore of old package succeeded. Update permissions.
12003                // writer
12004                synchronized (mPackages) {
12005                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
12006                            UPDATE_PERMISSIONS_ALL);
12007                    // can downgrade to reader
12008                    mSettings.writeLPr();
12009                }
12010                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
12011            }
12012        }
12013    }
12014
12015    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
12016            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12017            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12018            String volumeUuid, PackageInstalledInfo res) {
12019        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
12020                + ", old=" + deletedPackage);
12021        boolean disabledSystem = false;
12022        boolean updatedSettings = false;
12023        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
12024        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
12025                != 0) {
12026            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12027        }
12028        String packageName = deletedPackage.packageName;
12029        if (packageName == null) {
12030            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12031                    "Attempt to delete null packageName.");
12032            return;
12033        }
12034        PackageParser.Package oldPkg;
12035        PackageSetting oldPkgSetting;
12036        // reader
12037        synchronized (mPackages) {
12038            oldPkg = mPackages.get(packageName);
12039            oldPkgSetting = mSettings.mPackages.get(packageName);
12040            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
12041                    (oldPkgSetting == null)) {
12042                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12043                        "Couldn't find package:" + packageName + " information");
12044                return;
12045            }
12046        }
12047
12048        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12049
12050        res.removedInfo.uid = oldPkg.applicationInfo.uid;
12051        res.removedInfo.removedPackage = packageName;
12052        // Remove existing system package
12053        removePackageLI(oldPkgSetting, true);
12054        // writer
12055        synchronized (mPackages) {
12056            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12057            if (!disabledSystem && deletedPackage != null) {
12058                // We didn't need to disable the .apk as a current system package,
12059                // which means we are replacing another update that is already
12060                // installed.  We need to make sure to delete the older one's .apk.
12061                res.removedInfo.args = createInstallArgsForExisting(0,
12062                        deletedPackage.applicationInfo.getCodePath(),
12063                        deletedPackage.applicationInfo.getResourcePath(),
12064                        getAppDexInstructionSets(deletedPackage.applicationInfo));
12065            } else {
12066                res.removedInfo.args = null;
12067            }
12068        }
12069
12070        // Successfully disabled the old package. Now proceed with re-installation
12071        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12072
12073        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12074        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12075
12076        PackageParser.Package newPackage = null;
12077        try {
12078            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
12079            if (newPackage.mExtras != null) {
12080                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12081                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12082                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12083
12084                // is the update attempting to change shared user? that isn't going to work...
12085                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12086                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12087                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12088                            + " to " + newPkgSetting.sharedUser);
12089                    updatedSettings = true;
12090                }
12091            }
12092
12093            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12094                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12095                        perUserInstalled, res, user);
12096                updatedSettings = true;
12097            }
12098
12099        } catch (PackageManagerException e) {
12100            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12101        }
12102
12103        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12104            // Re installation failed. Restore old information
12105            // Remove new pkg information
12106            if (newPackage != null) {
12107                removeInstalledPackageLI(newPackage, true);
12108            }
12109            // Add back the old system package
12110            try {
12111                scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12112            } catch (PackageManagerException e) {
12113                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12114            }
12115            // Restore the old system information in Settings
12116            synchronized (mPackages) {
12117                if (disabledSystem) {
12118                    mSettings.enableSystemPackageLPw(packageName);
12119                }
12120                if (updatedSettings) {
12121                    mSettings.setInstallerPackageName(packageName,
12122                            oldPkgSetting.installerPackageName);
12123                }
12124                mSettings.writeLPr();
12125            }
12126        }
12127    }
12128
12129    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
12130        // Collect all used permissions in the UID
12131        ArraySet<String> usedPermissions = new ArraySet<>();
12132        final int packageCount = su.packages.size();
12133        for (int i = 0; i < packageCount; i++) {
12134            PackageSetting ps = su.packages.valueAt(i);
12135            if (ps.pkg == null) {
12136                continue;
12137            }
12138            final int requestedPermCount = ps.pkg.requestedPermissions.size();
12139            for (int j = 0; j < requestedPermCount; j++) {
12140                String permission = ps.pkg.requestedPermissions.get(j);
12141                BasePermission bp = mSettings.mPermissions.get(permission);
12142                if (bp != null) {
12143                    usedPermissions.add(permission);
12144                }
12145            }
12146        }
12147
12148        PermissionsState permissionsState = su.getPermissionsState();
12149        // Prune install permissions
12150        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
12151        final int installPermCount = installPermStates.size();
12152        for (int i = installPermCount - 1; i >= 0;  i--) {
12153            PermissionState permissionState = installPermStates.get(i);
12154            if (!usedPermissions.contains(permissionState.getName())) {
12155                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12156                if (bp != null) {
12157                    permissionsState.revokeInstallPermission(bp);
12158                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12159                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12160                }
12161            }
12162        }
12163
12164        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
12165
12166        // Prune runtime permissions
12167        for (int userId : allUserIds) {
12168            List<PermissionState> runtimePermStates = permissionsState
12169                    .getRuntimePermissionStates(userId);
12170            final int runtimePermCount = runtimePermStates.size();
12171            for (int i = runtimePermCount - 1; i >= 0; i--) {
12172                PermissionState permissionState = runtimePermStates.get(i);
12173                if (!usedPermissions.contains(permissionState.getName())) {
12174                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12175                    if (bp != null) {
12176                        permissionsState.revokeRuntimePermission(bp, userId);
12177                        permissionsState.updatePermissionFlags(bp, userId,
12178                                PackageManager.MASK_PERMISSION_FLAGS, 0);
12179                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
12180                                runtimePermissionChangedUserIds, userId);
12181                    }
12182                }
12183            }
12184        }
12185
12186        return runtimePermissionChangedUserIds;
12187    }
12188
12189    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12190            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12191            UserHandle user) {
12192        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
12193
12194        String pkgName = newPackage.packageName;
12195        synchronized (mPackages) {
12196            //write settings. the installStatus will be incomplete at this stage.
12197            //note that the new package setting would have already been
12198            //added to mPackages. It hasn't been persisted yet.
12199            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12200            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12201            mSettings.writeLPr();
12202            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12203        }
12204
12205        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12206        synchronized (mPackages) {
12207            updatePermissionsLPw(newPackage.packageName, newPackage,
12208                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12209                            ? UPDATE_PERMISSIONS_ALL : 0));
12210            // For system-bundled packages, we assume that installing an upgraded version
12211            // of the package implies that the user actually wants to run that new code,
12212            // so we enable the package.
12213            PackageSetting ps = mSettings.mPackages.get(pkgName);
12214            if (ps != null) {
12215                if (isSystemApp(newPackage)) {
12216                    // NB: implicit assumption that system package upgrades apply to all users
12217                    if (DEBUG_INSTALL) {
12218                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12219                    }
12220                    if (res.origUsers != null) {
12221                        for (int userHandle : res.origUsers) {
12222                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12223                                    userHandle, installerPackageName);
12224                        }
12225                    }
12226                    // Also convey the prior install/uninstall state
12227                    if (allUsers != null && perUserInstalled != null) {
12228                        for (int i = 0; i < allUsers.length; i++) {
12229                            if (DEBUG_INSTALL) {
12230                                Slog.d(TAG, "    user " + allUsers[i]
12231                                        + " => " + perUserInstalled[i]);
12232                            }
12233                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12234                        }
12235                        // these install state changes will be persisted in the
12236                        // upcoming call to mSettings.writeLPr().
12237                    }
12238                }
12239                // It's implied that when a user requests installation, they want the app to be
12240                // installed and enabled.
12241                int userId = user.getIdentifier();
12242                if (userId != UserHandle.USER_ALL) {
12243                    ps.setInstalled(true, userId);
12244                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12245                }
12246            }
12247            res.name = pkgName;
12248            res.uid = newPackage.applicationInfo.uid;
12249            res.pkg = newPackage;
12250            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12251            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12252            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12253            //to update install status
12254            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12255            mSettings.writeLPr();
12256            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12257        }
12258
12259        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12260    }
12261
12262    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
12263        try {
12264            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
12265            installPackageLI(args, res);
12266        } finally {
12267            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12268        }
12269    }
12270
12271    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12272        final int installFlags = args.installFlags;
12273        final String installerPackageName = args.installerPackageName;
12274        final String volumeUuid = args.volumeUuid;
12275        final File tmpPackageFile = new File(args.getCodePath());
12276        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12277        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12278                || (args.volumeUuid != null));
12279        final boolean quickInstall = ((installFlags & PackageManager.INSTALL_QUICK) != 0);
12280        boolean replace = false;
12281        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12282        if (args.move != null) {
12283            // moving a complete application; perfom an initial scan on the new install location
12284            scanFlags |= SCAN_INITIAL;
12285        }
12286        // Result object to be returned
12287        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12288
12289        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12290
12291        // Retrieve PackageSettings and parse package
12292        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12293                | PackageParser.PARSE_ENFORCE_CODE
12294                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12295                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
12296                | (quickInstall ? PackageParser.PARSE_SKIP_VERIFICATION : 0);
12297        PackageParser pp = new PackageParser();
12298        pp.setSeparateProcesses(mSeparateProcesses);
12299        pp.setDisplayMetrics(mMetrics);
12300
12301        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
12302        final PackageParser.Package pkg;
12303        try {
12304            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12305        } catch (PackageParserException e) {
12306            res.setError("Failed parse during installPackageLI", e);
12307            return;
12308        } finally {
12309            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12310        }
12311
12312        // Mark that we have an install time CPU ABI override.
12313        pkg.cpuAbiOverride = args.abiOverride;
12314
12315        String pkgName = res.name = pkg.packageName;
12316        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12317            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12318                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12319                return;
12320            }
12321        }
12322
12323        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
12324        try {
12325            pp.collectCertificates(pkg, parseFlags);
12326        } catch (PackageParserException e) {
12327            res.setError("Failed collect during installPackageLI", e);
12328            return;
12329        } finally {
12330            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12331        }
12332
12333        /* If the installer passed in a manifest digest, compare it now. */
12334        if (args.manifestDigest != null) {
12335            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectManifestDigest");
12336            try {
12337                pp.collectManifestDigest(pkg);
12338            } catch (PackageParserException e) {
12339                res.setError("Failed collect during installPackageLI", e);
12340                return;
12341            } finally {
12342                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12343            }
12344
12345            if (DEBUG_INSTALL) {
12346                final String parsedManifest = pkg.manifestDigest == null ? "null"
12347                        : pkg.manifestDigest.toString();
12348                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12349                        + parsedManifest);
12350            }
12351
12352            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12353                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12354                return;
12355            }
12356        } else if (DEBUG_INSTALL) {
12357            final String parsedManifest = pkg.manifestDigest == null
12358                    ? "null" : pkg.manifestDigest.toString();
12359            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12360        }
12361
12362        // Get rid of all references to package scan path via parser.
12363        pp = null;
12364        String oldCodePath = null;
12365        boolean systemApp = false;
12366        synchronized (mPackages) {
12367            // Check if installing already existing package
12368            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12369                String oldName = mSettings.mRenamedPackages.get(pkgName);
12370                if (pkg.mOriginalPackages != null
12371                        && pkg.mOriginalPackages.contains(oldName)
12372                        && mPackages.containsKey(oldName)) {
12373                    // This package is derived from an original package,
12374                    // and this device has been updating from that original
12375                    // name.  We must continue using the original name, so
12376                    // rename the new package here.
12377                    pkg.setPackageName(oldName);
12378                    pkgName = pkg.packageName;
12379                    replace = true;
12380                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12381                            + oldName + " pkgName=" + pkgName);
12382                } else if (mPackages.containsKey(pkgName)) {
12383                    // This package, under its official name, already exists
12384                    // on the device; we should replace it.
12385                    replace = true;
12386                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12387                }
12388
12389                // Prevent apps opting out from runtime permissions
12390                if (replace) {
12391                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12392                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12393                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12394                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12395                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12396                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12397                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12398                                        + " doesn't support runtime permissions but the old"
12399                                        + " target SDK " + oldTargetSdk + " does.");
12400                        return;
12401                    }
12402                }
12403            }
12404
12405            PackageSetting ps = mSettings.mPackages.get(pkgName);
12406            if (ps != null) {
12407                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12408
12409                // Quick sanity check that we're signed correctly if updating;
12410                // we'll check this again later when scanning, but we want to
12411                // bail early here before tripping over redefined permissions.
12412                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12413                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12414                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12415                                + pkg.packageName + " upgrade keys do not match the "
12416                                + "previously installed version");
12417                        return;
12418                    }
12419                } else {
12420                    try {
12421                        verifySignaturesLP(ps, pkg);
12422                    } catch (PackageManagerException e) {
12423                        res.setError(e.error, e.getMessage());
12424                        return;
12425                    }
12426                }
12427
12428                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12429                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12430                    systemApp = (ps.pkg.applicationInfo.flags &
12431                            ApplicationInfo.FLAG_SYSTEM) != 0;
12432                }
12433                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12434            }
12435
12436            // Check whether the newly-scanned package wants to define an already-defined perm
12437            int N = pkg.permissions.size();
12438            for (int i = N-1; i >= 0; i--) {
12439                PackageParser.Permission perm = pkg.permissions.get(i);
12440                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12441                if (bp != null) {
12442                    // If the defining package is signed with our cert, it's okay.  This
12443                    // also includes the "updating the same package" case, of course.
12444                    // "updating same package" could also involve key-rotation.
12445                    final boolean sigsOk;
12446                    if (bp.sourcePackage.equals(pkg.packageName)
12447                            && (bp.packageSetting instanceof PackageSetting)
12448                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12449                                    scanFlags))) {
12450                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12451                    } else {
12452                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12453                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12454                    }
12455                    if (!sigsOk) {
12456                        // If the owning package is the system itself, we log but allow
12457                        // install to proceed; we fail the install on all other permission
12458                        // redefinitions.
12459                        if (!bp.sourcePackage.equals("android")) {
12460                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12461                                    + pkg.packageName + " attempting to redeclare permission "
12462                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12463                            res.origPermission = perm.info.name;
12464                            res.origPackage = bp.sourcePackage;
12465                            return;
12466                        } else {
12467                            Slog.w(TAG, "Package " + pkg.packageName
12468                                    + " attempting to redeclare system permission "
12469                                    + perm.info.name + "; ignoring new declaration");
12470                            pkg.permissions.remove(i);
12471                        }
12472                    }
12473                }
12474            }
12475
12476        }
12477
12478        if (systemApp && onExternal) {
12479            // Disable updates to system apps on sdcard
12480            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12481                    "Cannot install updates to system apps on sdcard");
12482            return;
12483        }
12484
12485        if (args.move != null) {
12486            // We did an in-place move, so dex is ready to roll
12487            scanFlags |= SCAN_NO_DEX;
12488            scanFlags |= SCAN_MOVE;
12489
12490            synchronized (mPackages) {
12491                final PackageSetting ps = mSettings.mPackages.get(pkgName);
12492                if (ps == null) {
12493                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
12494                            "Missing settings for moved package " + pkgName);
12495                }
12496
12497                // We moved the entire application as-is, so bring over the
12498                // previously derived ABI information.
12499                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
12500                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
12501            }
12502
12503        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12504            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12505            scanFlags |= SCAN_NO_DEX;
12506
12507            try {
12508                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12509                        true /* extract libs */);
12510            } catch (PackageManagerException pme) {
12511                Slog.e(TAG, "Error deriving application ABI", pme);
12512                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12513                return;
12514            }
12515        }
12516
12517        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12518            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12519            return;
12520        }
12521
12522        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12523
12524        if (replace) {
12525            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
12526                    installerPackageName, volumeUuid, res);
12527        } else {
12528            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12529                    args.user, installerPackageName, volumeUuid, res);
12530        }
12531        synchronized (mPackages) {
12532            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12533            if (ps != null) {
12534                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12535            }
12536        }
12537    }
12538
12539    private void startIntentFilterVerifications(int userId, boolean replacing,
12540            PackageParser.Package pkg) {
12541        if (mIntentFilterVerifierComponent == null) {
12542            Slog.w(TAG, "No IntentFilter verification will not be done as "
12543                    + "there is no IntentFilterVerifier available!");
12544            return;
12545        }
12546
12547        final int verifierUid = getPackageUid(
12548                mIntentFilterVerifierComponent.getPackageName(),
12549                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
12550
12551        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12552        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12553        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12554        mHandler.sendMessage(msg);
12555    }
12556
12557    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12558            PackageParser.Package pkg) {
12559        int size = pkg.activities.size();
12560        if (size == 0) {
12561            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12562                    "No activity, so no need to verify any IntentFilter!");
12563            return;
12564        }
12565
12566        final boolean hasDomainURLs = hasDomainURLs(pkg);
12567        if (!hasDomainURLs) {
12568            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12569                    "No domain URLs, so no need to verify any IntentFilter!");
12570            return;
12571        }
12572
12573        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12574                + " if any IntentFilter from the " + size
12575                + " Activities needs verification ...");
12576
12577        int count = 0;
12578        final String packageName = pkg.packageName;
12579
12580        synchronized (mPackages) {
12581            // If this is a new install and we see that we've already run verification for this
12582            // package, we have nothing to do: it means the state was restored from backup.
12583            if (!replacing) {
12584                IntentFilterVerificationInfo ivi =
12585                        mSettings.getIntentFilterVerificationLPr(packageName);
12586                if (ivi != null) {
12587                    if (DEBUG_DOMAIN_VERIFICATION) {
12588                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12589                                + ivi.getStatusString());
12590                    }
12591                    return;
12592                }
12593            }
12594
12595            // If any filters need to be verified, then all need to be.
12596            boolean needToVerify = false;
12597            for (PackageParser.Activity a : pkg.activities) {
12598                for (ActivityIntentInfo filter : a.intents) {
12599                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12600                        if (DEBUG_DOMAIN_VERIFICATION) {
12601                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12602                        }
12603                        needToVerify = true;
12604                        break;
12605                    }
12606                }
12607            }
12608
12609            if (needToVerify) {
12610                final int verificationId = mIntentFilterVerificationToken++;
12611                for (PackageParser.Activity a : pkg.activities) {
12612                    for (ActivityIntentInfo filter : a.intents) {
12613                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12614                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12615                                    "Verification needed for IntentFilter:" + filter.toString());
12616                            mIntentFilterVerifier.addOneIntentFilterVerification(
12617                                    verifierUid, userId, verificationId, filter, packageName);
12618                            count++;
12619                        }
12620                    }
12621                }
12622            }
12623        }
12624
12625        if (count > 0) {
12626            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12627                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12628                    +  " for userId:" + userId);
12629            mIntentFilterVerifier.startVerifications(userId);
12630        } else {
12631            if (DEBUG_DOMAIN_VERIFICATION) {
12632                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12633            }
12634        }
12635    }
12636
12637    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12638        final ComponentName cn  = filter.activity.getComponentName();
12639        final String packageName = cn.getPackageName();
12640
12641        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12642                packageName);
12643        if (ivi == null) {
12644            return true;
12645        }
12646        int status = ivi.getStatus();
12647        switch (status) {
12648            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12649            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12650                return true;
12651
12652            default:
12653                // Nothing to do
12654                return false;
12655        }
12656    }
12657
12658    private static boolean isMultiArch(PackageSetting ps) {
12659        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12660    }
12661
12662    private static boolean isMultiArch(ApplicationInfo info) {
12663        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12664    }
12665
12666    private static boolean isExternal(PackageParser.Package pkg) {
12667        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12668    }
12669
12670    private static boolean isExternal(PackageSetting ps) {
12671        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12672    }
12673
12674    private static boolean isExternal(ApplicationInfo info) {
12675        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12676    }
12677
12678    private static boolean isSystemApp(PackageParser.Package pkg) {
12679        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12680    }
12681
12682    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12683        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12684    }
12685
12686    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12687        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12688    }
12689
12690    private static boolean isSystemApp(PackageSetting ps) {
12691        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12692    }
12693
12694    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12695        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12696    }
12697
12698    private int packageFlagsToInstallFlags(PackageSetting ps) {
12699        int installFlags = 0;
12700        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12701            // This existing package was an external ASEC install when we have
12702            // the external flag without a UUID
12703            installFlags |= PackageManager.INSTALL_EXTERNAL;
12704        }
12705        if (ps.isForwardLocked()) {
12706            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12707        }
12708        return installFlags;
12709    }
12710
12711    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
12712        if (isExternal(pkg)) {
12713            if (TextUtils.isEmpty(pkg.volumeUuid)) {
12714                return StorageManager.UUID_PRIMARY_PHYSICAL;
12715            } else {
12716                return pkg.volumeUuid;
12717            }
12718        } else {
12719            return StorageManager.UUID_PRIVATE_INTERNAL;
12720        }
12721    }
12722
12723    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
12724        if (isExternal(pkg)) {
12725            if (TextUtils.isEmpty(pkg.volumeUuid)) {
12726                return mSettings.getExternalVersion();
12727            } else {
12728                return mSettings.findOrCreateVersion(pkg.volumeUuid);
12729            }
12730        } else {
12731            return mSettings.getInternalVersion();
12732        }
12733    }
12734
12735    private void deleteTempPackageFiles() {
12736        final FilenameFilter filter = new FilenameFilter() {
12737            public boolean accept(File dir, String name) {
12738                return name.startsWith("vmdl") && name.endsWith(".tmp");
12739            }
12740        };
12741        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12742            file.delete();
12743        }
12744    }
12745
12746    @Override
12747    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12748            int flags) {
12749        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12750                flags);
12751    }
12752
12753    @Override
12754    public void deletePackage(final String packageName,
12755            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12756        mContext.enforceCallingOrSelfPermission(
12757                android.Manifest.permission.DELETE_PACKAGES, null);
12758        Preconditions.checkNotNull(packageName);
12759        Preconditions.checkNotNull(observer);
12760        final int uid = Binder.getCallingUid();
12761        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
12762        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
12763        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
12764            mContext.enforceCallingPermission(
12765                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12766                    "deletePackage for user " + userId);
12767        }
12768
12769        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12770            try {
12771                observer.onPackageDeleted(packageName,
12772                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12773            } catch (RemoteException re) {
12774            }
12775            return;
12776        }
12777
12778        for (int currentUserId : users) {
12779            if (getBlockUninstallForUser(packageName, currentUserId)) {
12780                try {
12781                    observer.onPackageDeleted(packageName,
12782                            PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
12783                } catch (RemoteException re) {
12784                }
12785                return;
12786            }
12787        }
12788
12789        if (DEBUG_REMOVE) {
12790            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12791        }
12792        // Queue up an async operation since the package deletion may take a little while.
12793        mHandler.post(new Runnable() {
12794            public void run() {
12795                mHandler.removeCallbacks(this);
12796                final int returnCode = deletePackageX(packageName, userId, flags);
12797                try {
12798                    observer.onPackageDeleted(packageName, returnCode, null);
12799                } catch (RemoteException e) {
12800                    Log.i(TAG, "Observer no longer exists.");
12801                } //end catch
12802            } //end run
12803        });
12804    }
12805
12806    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12807        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12808                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12809        try {
12810            if (dpm != null) {
12811                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwner();
12812                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
12813                        : deviceOwnerComponentName.getPackageName();
12814                // Does the package contains the device owner?
12815                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
12816                // this check is probably not needed, since DO should be registered as a device
12817                // admin on some user too. (Original bug for this: b/17657954)
12818                if (packageName.equals(deviceOwnerPackageName)) {
12819                    return true;
12820                }
12821                // Does it contain a device admin for any user?
12822                int[] users;
12823                if (userId == UserHandle.USER_ALL) {
12824                    users = sUserManager.getUserIds();
12825                } else {
12826                    users = new int[]{userId};
12827                }
12828                for (int i = 0; i < users.length; ++i) {
12829                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12830                        return true;
12831                    }
12832                }
12833            }
12834        } catch (RemoteException e) {
12835        }
12836        return false;
12837    }
12838
12839    /**
12840     *  This method is an internal method that could be get invoked either
12841     *  to delete an installed package or to clean up a failed installation.
12842     *  After deleting an installed package, a broadcast is sent to notify any
12843     *  listeners that the package has been installed. For cleaning up a failed
12844     *  installation, the broadcast is not necessary since the package's
12845     *  installation wouldn't have sent the initial broadcast either
12846     *  The key steps in deleting a package are
12847     *  deleting the package information in internal structures like mPackages,
12848     *  deleting the packages base directories through installd
12849     *  updating mSettings to reflect current status
12850     *  persisting settings for later use
12851     *  sending a broadcast if necessary
12852     */
12853    private int deletePackageX(String packageName, int userId, int flags) {
12854        final PackageRemovedInfo info = new PackageRemovedInfo();
12855        final boolean res;
12856
12857        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12858                ? UserHandle.ALL : new UserHandle(userId);
12859
12860        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12861            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12862            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12863        }
12864
12865        boolean removedForAllUsers = false;
12866        boolean systemUpdate = false;
12867
12868        // for the uninstall-updates case and restricted profiles, remember the per-
12869        // userhandle installed state
12870        int[] allUsers;
12871        boolean[] perUserInstalled;
12872        synchronized (mPackages) {
12873            PackageSetting ps = mSettings.mPackages.get(packageName);
12874            allUsers = sUserManager.getUserIds();
12875            perUserInstalled = new boolean[allUsers.length];
12876            for (int i = 0; i < allUsers.length; i++) {
12877                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12878            }
12879        }
12880
12881        synchronized (mInstallLock) {
12882            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12883            res = deletePackageLI(packageName, removeForUser,
12884                    true, allUsers, perUserInstalled,
12885                    flags | REMOVE_CHATTY, info, true);
12886            systemUpdate = info.isRemovedPackageSystemUpdate;
12887            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12888                removedForAllUsers = true;
12889            }
12890            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12891                    + " removedForAllUsers=" + removedForAllUsers);
12892        }
12893
12894        if (res) {
12895            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12896
12897            // If the removed package was a system update, the old system package
12898            // was re-enabled; we need to broadcast this information
12899            if (systemUpdate) {
12900                Bundle extras = new Bundle(1);
12901                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12902                        ? info.removedAppId : info.uid);
12903                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12904
12905                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12906                        extras, null, null, null);
12907                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12908                        extras, null, null, null);
12909                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12910                        null, packageName, null, null);
12911            }
12912        }
12913        // Force a gc here.
12914        Runtime.getRuntime().gc();
12915        // Delete the resources here after sending the broadcast to let
12916        // other processes clean up before deleting resources.
12917        if (info.args != null) {
12918            synchronized (mInstallLock) {
12919                info.args.doPostDeleteLI(true);
12920            }
12921        }
12922
12923        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12924    }
12925
12926    class PackageRemovedInfo {
12927        String removedPackage;
12928        int uid = -1;
12929        int removedAppId = -1;
12930        int[] removedUsers = null;
12931        boolean isRemovedPackageSystemUpdate = false;
12932        // Clean up resources deleted packages.
12933        InstallArgs args = null;
12934
12935        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12936            Bundle extras = new Bundle(1);
12937            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12938            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12939            if (replacing) {
12940                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12941            }
12942            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12943            if (removedPackage != null) {
12944                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12945                        extras, null, null, removedUsers);
12946                if (fullRemove && !replacing) {
12947                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12948                            extras, null, null, removedUsers);
12949                }
12950            }
12951            if (removedAppId >= 0) {
12952                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12953                        removedUsers);
12954            }
12955        }
12956    }
12957
12958    /*
12959     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12960     * flag is not set, the data directory is removed as well.
12961     * make sure this flag is set for partially installed apps. If not its meaningless to
12962     * delete a partially installed application.
12963     */
12964    private void removePackageDataLI(PackageSetting ps,
12965            int[] allUserHandles, boolean[] perUserInstalled,
12966            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12967        String packageName = ps.name;
12968        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12969        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12970        // Retrieve object to delete permissions for shared user later on
12971        final PackageSetting deletedPs;
12972        // reader
12973        synchronized (mPackages) {
12974            deletedPs = mSettings.mPackages.get(packageName);
12975            if (outInfo != null) {
12976                outInfo.removedPackage = packageName;
12977                outInfo.removedUsers = deletedPs != null
12978                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12979                        : null;
12980            }
12981        }
12982        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12983            removeDataDirsLI(ps.volumeUuid, packageName);
12984            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12985        }
12986        // writer
12987        synchronized (mPackages) {
12988            if (deletedPs != null) {
12989                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12990                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12991                    clearDefaultBrowserIfNeeded(packageName);
12992                    if (outInfo != null) {
12993                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12994                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12995                    }
12996                    updatePermissionsLPw(deletedPs.name, null, 0);
12997                    if (deletedPs.sharedUser != null) {
12998                        // Remove permissions associated with package. Since runtime
12999                        // permissions are per user we have to kill the removed package
13000                        // or packages running under the shared user of the removed
13001                        // package if revoking the permissions requested only by the removed
13002                        // package is successful and this causes a change in gids.
13003                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13004                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
13005                                    userId);
13006                            if (userIdToKill == UserHandle.USER_ALL
13007                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
13008                                // If gids changed for this user, kill all affected packages.
13009                                mHandler.post(new Runnable() {
13010                                    @Override
13011                                    public void run() {
13012                                        // This has to happen with no lock held.
13013                                        killApplication(deletedPs.name, deletedPs.appId,
13014                                                KILL_APP_REASON_GIDS_CHANGED);
13015                                    }
13016                                });
13017                                break;
13018                            }
13019                        }
13020                    }
13021                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
13022                }
13023                // make sure to preserve per-user disabled state if this removal was just
13024                // a downgrade of a system app to the factory package
13025                if (allUserHandles != null && perUserInstalled != null) {
13026                    if (DEBUG_REMOVE) {
13027                        Slog.d(TAG, "Propagating install state across downgrade");
13028                    }
13029                    for (int i = 0; i < allUserHandles.length; i++) {
13030                        if (DEBUG_REMOVE) {
13031                            Slog.d(TAG, "    user " + allUserHandles[i]
13032                                    + " => " + perUserInstalled[i]);
13033                        }
13034                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13035                    }
13036                }
13037            }
13038            // can downgrade to reader
13039            if (writeSettings) {
13040                // Save settings now
13041                mSettings.writeLPr();
13042            }
13043        }
13044        if (outInfo != null) {
13045            // A user ID was deleted here. Go through all users and remove it
13046            // from KeyStore.
13047            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
13048        }
13049    }
13050
13051    static boolean locationIsPrivileged(File path) {
13052        try {
13053            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
13054                    .getCanonicalPath();
13055            return path.getCanonicalPath().startsWith(privilegedAppDir);
13056        } catch (IOException e) {
13057            Slog.e(TAG, "Unable to access code path " + path);
13058        }
13059        return false;
13060    }
13061
13062    /*
13063     * Tries to delete system package.
13064     */
13065    private boolean deleteSystemPackageLI(PackageSetting newPs,
13066            int[] allUserHandles, boolean[] perUserInstalled,
13067            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
13068        final boolean applyUserRestrictions
13069                = (allUserHandles != null) && (perUserInstalled != null);
13070        PackageSetting disabledPs = null;
13071        // Confirm if the system package has been updated
13072        // An updated system app can be deleted. This will also have to restore
13073        // the system pkg from system partition
13074        // reader
13075        synchronized (mPackages) {
13076            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
13077        }
13078        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
13079                + " disabledPs=" + disabledPs);
13080        if (disabledPs == null) {
13081            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
13082            return false;
13083        } else if (DEBUG_REMOVE) {
13084            Slog.d(TAG, "Deleting system pkg from data partition");
13085        }
13086        if (DEBUG_REMOVE) {
13087            if (applyUserRestrictions) {
13088                Slog.d(TAG, "Remembering install states:");
13089                for (int i = 0; i < allUserHandles.length; i++) {
13090                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
13091                }
13092            }
13093        }
13094        // Delete the updated package
13095        outInfo.isRemovedPackageSystemUpdate = true;
13096        if (disabledPs.versionCode < newPs.versionCode) {
13097            // Delete data for downgrades
13098            flags &= ~PackageManager.DELETE_KEEP_DATA;
13099        } else {
13100            // Preserve data by setting flag
13101            flags |= PackageManager.DELETE_KEEP_DATA;
13102        }
13103        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
13104                allUserHandles, perUserInstalled, outInfo, writeSettings);
13105        if (!ret) {
13106            return false;
13107        }
13108        // writer
13109        synchronized (mPackages) {
13110            // Reinstate the old system package
13111            mSettings.enableSystemPackageLPw(newPs.name);
13112            // Remove any native libraries from the upgraded package.
13113            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
13114        }
13115        // Install the system package
13116        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
13117        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
13118        if (locationIsPrivileged(disabledPs.codePath)) {
13119            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13120        }
13121
13122        final PackageParser.Package newPkg;
13123        try {
13124            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
13125        } catch (PackageManagerException e) {
13126            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
13127            return false;
13128        }
13129
13130        // writer
13131        synchronized (mPackages) {
13132            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
13133
13134            // Propagate the permissions state as we do not want to drop on the floor
13135            // runtime permissions. The update permissions method below will take
13136            // care of removing obsolete permissions and grant install permissions.
13137            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
13138            updatePermissionsLPw(newPkg.packageName, newPkg,
13139                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
13140
13141            if (applyUserRestrictions) {
13142                if (DEBUG_REMOVE) {
13143                    Slog.d(TAG, "Propagating install state across reinstall");
13144                }
13145                for (int i = 0; i < allUserHandles.length; i++) {
13146                    if (DEBUG_REMOVE) {
13147                        Slog.d(TAG, "    user " + allUserHandles[i]
13148                                + " => " + perUserInstalled[i]);
13149                    }
13150                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13151
13152                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13153                }
13154                // Regardless of writeSettings we need to ensure that this restriction
13155                // state propagation is persisted
13156                mSettings.writeAllUsersPackageRestrictionsLPr();
13157            }
13158            // can downgrade to reader here
13159            if (writeSettings) {
13160                mSettings.writeLPr();
13161            }
13162        }
13163        return true;
13164    }
13165
13166    private boolean deleteInstalledPackageLI(PackageSetting ps,
13167            boolean deleteCodeAndResources, int flags,
13168            int[] allUserHandles, boolean[] perUserInstalled,
13169            PackageRemovedInfo outInfo, boolean writeSettings) {
13170        if (outInfo != null) {
13171            outInfo.uid = ps.appId;
13172        }
13173
13174        // Delete package data from internal structures and also remove data if flag is set
13175        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13176
13177        // Delete application code and resources
13178        if (deleteCodeAndResources && (outInfo != null)) {
13179            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13180                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13181            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13182        }
13183        return true;
13184    }
13185
13186    @Override
13187    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13188            int userId) {
13189        mContext.enforceCallingOrSelfPermission(
13190                android.Manifest.permission.DELETE_PACKAGES, null);
13191        synchronized (mPackages) {
13192            PackageSetting ps = mSettings.mPackages.get(packageName);
13193            if (ps == null) {
13194                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13195                return false;
13196            }
13197            if (!ps.getInstalled(userId)) {
13198                // Can't block uninstall for an app that is not installed or enabled.
13199                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13200                return false;
13201            }
13202            ps.setBlockUninstall(blockUninstall, userId);
13203            mSettings.writePackageRestrictionsLPr(userId);
13204        }
13205        return true;
13206    }
13207
13208    @Override
13209    public boolean getBlockUninstallForUser(String packageName, int userId) {
13210        synchronized (mPackages) {
13211            PackageSetting ps = mSettings.mPackages.get(packageName);
13212            if (ps == null) {
13213                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13214                return false;
13215            }
13216            return ps.getBlockUninstall(userId);
13217        }
13218    }
13219
13220    /*
13221     * This method handles package deletion in general
13222     */
13223    private boolean deletePackageLI(String packageName, UserHandle user,
13224            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13225            int flags, PackageRemovedInfo outInfo,
13226            boolean writeSettings) {
13227        if (packageName == null) {
13228            Slog.w(TAG, "Attempt to delete null packageName.");
13229            return false;
13230        }
13231        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13232        PackageSetting ps;
13233        boolean dataOnly = false;
13234        int removeUser = -1;
13235        int appId = -1;
13236        synchronized (mPackages) {
13237            ps = mSettings.mPackages.get(packageName);
13238            if (ps == null) {
13239                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13240                return false;
13241            }
13242            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13243                    && user.getIdentifier() != UserHandle.USER_ALL) {
13244                // The caller is asking that the package only be deleted for a single
13245                // user.  To do this, we just mark its uninstalled state and delete
13246                // its data.  If this is a system app, we only allow this to happen if
13247                // they have set the special DELETE_SYSTEM_APP which requests different
13248                // semantics than normal for uninstalling system apps.
13249                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13250                final int userId = user.getIdentifier();
13251                ps.setUserState(userId,
13252                        COMPONENT_ENABLED_STATE_DEFAULT,
13253                        false, //installed
13254                        true,  //stopped
13255                        true,  //notLaunched
13256                        false, //hidden
13257                        null, null, null,
13258                        false, // blockUninstall
13259                        ps.readUserState(userId).domainVerificationStatus, 0);
13260                if (!isSystemApp(ps)) {
13261                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
13262                        // Other user still have this package installed, so all
13263                        // we need to do is clear this user's data and save that
13264                        // it is uninstalled.
13265                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13266                        removeUser = user.getIdentifier();
13267                        appId = ps.appId;
13268                        scheduleWritePackageRestrictionsLocked(removeUser);
13269                    } else {
13270                        // We need to set it back to 'installed' so the uninstall
13271                        // broadcasts will be sent correctly.
13272                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13273                        ps.setInstalled(true, user.getIdentifier());
13274                    }
13275                } else {
13276                    // This is a system app, so we assume that the
13277                    // other users still have this package installed, so all
13278                    // we need to do is clear this user's data and save that
13279                    // it is uninstalled.
13280                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13281                    removeUser = user.getIdentifier();
13282                    appId = ps.appId;
13283                    scheduleWritePackageRestrictionsLocked(removeUser);
13284                }
13285            }
13286        }
13287
13288        if (removeUser >= 0) {
13289            // From above, we determined that we are deleting this only
13290            // for a single user.  Continue the work here.
13291            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13292            if (outInfo != null) {
13293                outInfo.removedPackage = packageName;
13294                outInfo.removedAppId = appId;
13295                outInfo.removedUsers = new int[] {removeUser};
13296            }
13297            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13298            removeKeystoreDataIfNeeded(removeUser, appId);
13299            schedulePackageCleaning(packageName, removeUser, false);
13300            synchronized (mPackages) {
13301                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13302                    scheduleWritePackageRestrictionsLocked(removeUser);
13303                }
13304                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13305            }
13306            return true;
13307        }
13308
13309        if (dataOnly) {
13310            // Delete application data first
13311            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13312            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13313            return true;
13314        }
13315
13316        boolean ret = false;
13317        if (isSystemApp(ps)) {
13318            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13319            // When an updated system application is deleted we delete the existing resources as well and
13320            // fall back to existing code in system partition
13321            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13322                    flags, outInfo, writeSettings);
13323        } else {
13324            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13325            // Kill application pre-emptively especially for apps on sd.
13326            killApplication(packageName, ps.appId, "uninstall pkg");
13327            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13328                    allUserHandles, perUserInstalled,
13329                    outInfo, writeSettings);
13330        }
13331
13332        return ret;
13333    }
13334
13335    private final class ClearStorageConnection implements ServiceConnection {
13336        IMediaContainerService mContainerService;
13337
13338        @Override
13339        public void onServiceConnected(ComponentName name, IBinder service) {
13340            synchronized (this) {
13341                mContainerService = IMediaContainerService.Stub.asInterface(service);
13342                notifyAll();
13343            }
13344        }
13345
13346        @Override
13347        public void onServiceDisconnected(ComponentName name) {
13348        }
13349    }
13350
13351    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13352        final boolean mounted;
13353        if (Environment.isExternalStorageEmulated()) {
13354            mounted = true;
13355        } else {
13356            final String status = Environment.getExternalStorageState();
13357
13358            mounted = status.equals(Environment.MEDIA_MOUNTED)
13359                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13360        }
13361
13362        if (!mounted) {
13363            return;
13364        }
13365
13366        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13367        int[] users;
13368        if (userId == UserHandle.USER_ALL) {
13369            users = sUserManager.getUserIds();
13370        } else {
13371            users = new int[] { userId };
13372        }
13373        final ClearStorageConnection conn = new ClearStorageConnection();
13374        if (mContext.bindServiceAsUser(
13375                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
13376            try {
13377                for (int curUser : users) {
13378                    long timeout = SystemClock.uptimeMillis() + 5000;
13379                    synchronized (conn) {
13380                        long now = SystemClock.uptimeMillis();
13381                        while (conn.mContainerService == null && now < timeout) {
13382                            try {
13383                                conn.wait(timeout - now);
13384                            } catch (InterruptedException e) {
13385                            }
13386                        }
13387                    }
13388                    if (conn.mContainerService == null) {
13389                        return;
13390                    }
13391
13392                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13393                    clearDirectory(conn.mContainerService,
13394                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13395                    if (allData) {
13396                        clearDirectory(conn.mContainerService,
13397                                userEnv.buildExternalStorageAppDataDirs(packageName));
13398                        clearDirectory(conn.mContainerService,
13399                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13400                    }
13401                }
13402            } finally {
13403                mContext.unbindService(conn);
13404            }
13405        }
13406    }
13407
13408    @Override
13409    public void clearApplicationUserData(final String packageName,
13410            final IPackageDataObserver observer, final int userId) {
13411        mContext.enforceCallingOrSelfPermission(
13412                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13413        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13414        // Queue up an async operation since the package deletion may take a little while.
13415        mHandler.post(new Runnable() {
13416            public void run() {
13417                mHandler.removeCallbacks(this);
13418                final boolean succeeded;
13419                synchronized (mInstallLock) {
13420                    succeeded = clearApplicationUserDataLI(packageName, userId);
13421                }
13422                clearExternalStorageDataSync(packageName, userId, true);
13423                if (succeeded) {
13424                    // invoke DeviceStorageMonitor's update method to clear any notifications
13425                    DeviceStorageMonitorInternal
13426                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13427                    if (dsm != null) {
13428                        dsm.checkMemory();
13429                    }
13430                }
13431                if(observer != null) {
13432                    try {
13433                        observer.onRemoveCompleted(packageName, succeeded);
13434                    } catch (RemoteException e) {
13435                        Log.i(TAG, "Observer no longer exists.");
13436                    }
13437                } //end if observer
13438            } //end run
13439        });
13440    }
13441
13442    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13443        if (packageName == null) {
13444            Slog.w(TAG, "Attempt to delete null packageName.");
13445            return false;
13446        }
13447
13448        // Try finding details about the requested package
13449        PackageParser.Package pkg;
13450        synchronized (mPackages) {
13451            pkg = mPackages.get(packageName);
13452            if (pkg == null) {
13453                final PackageSetting ps = mSettings.mPackages.get(packageName);
13454                if (ps != null) {
13455                    pkg = ps.pkg;
13456                }
13457            }
13458
13459            if (pkg == null) {
13460                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13461                return false;
13462            }
13463
13464            PackageSetting ps = (PackageSetting) pkg.mExtras;
13465            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13466        }
13467
13468        // Always delete data directories for package, even if we found no other
13469        // record of app. This helps users recover from UID mismatches without
13470        // resorting to a full data wipe.
13471        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13472        if (retCode < 0) {
13473            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13474            return false;
13475        }
13476
13477        final int appId = pkg.applicationInfo.uid;
13478        removeKeystoreDataIfNeeded(userId, appId);
13479
13480        // Create a native library symlink only if we have native libraries
13481        // and if the native libraries are 32 bit libraries. We do not provide
13482        // this symlink for 64 bit libraries.
13483        if (pkg.applicationInfo.primaryCpuAbi != null &&
13484                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13485            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13486            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13487                    nativeLibPath, userId) < 0) {
13488                Slog.w(TAG, "Failed linking native library dir");
13489                return false;
13490            }
13491        }
13492
13493        return true;
13494    }
13495
13496    /**
13497     * Reverts user permission state changes (permissions and flags) in
13498     * all packages for a given user.
13499     *
13500     * @param userId The device user for which to do a reset.
13501     */
13502    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
13503        final int packageCount = mPackages.size();
13504        for (int i = 0; i < packageCount; i++) {
13505            PackageParser.Package pkg = mPackages.valueAt(i);
13506            PackageSetting ps = (PackageSetting) pkg.mExtras;
13507            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13508        }
13509    }
13510
13511    /**
13512     * Reverts user permission state changes (permissions and flags).
13513     *
13514     * @param ps The package for which to reset.
13515     * @param userId The device user for which to do a reset.
13516     */
13517    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
13518            final PackageSetting ps, final int userId) {
13519        if (ps.pkg == null) {
13520            return;
13521        }
13522
13523        final int userSettableFlags = FLAG_PERMISSION_USER_SET
13524                | FLAG_PERMISSION_USER_FIXED
13525                | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13526
13527        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13528                | FLAG_PERMISSION_POLICY_FIXED;
13529
13530        boolean writeInstallPermissions = false;
13531        boolean writeRuntimePermissions = false;
13532
13533        final int permissionCount = ps.pkg.requestedPermissions.size();
13534        for (int i = 0; i < permissionCount; i++) {
13535            String permission = ps.pkg.requestedPermissions.get(i);
13536
13537            BasePermission bp = mSettings.mPermissions.get(permission);
13538            if (bp == null) {
13539                continue;
13540            }
13541
13542            // If shared user we just reset the state to which only this app contributed.
13543            if (ps.sharedUser != null) {
13544                boolean used = false;
13545                final int packageCount = ps.sharedUser.packages.size();
13546                for (int j = 0; j < packageCount; j++) {
13547                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13548                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13549                            && pkg.pkg.requestedPermissions.contains(permission)) {
13550                        used = true;
13551                        break;
13552                    }
13553                }
13554                if (used) {
13555                    continue;
13556                }
13557            }
13558
13559            PermissionsState permissionsState = ps.getPermissionsState();
13560
13561            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13562
13563            // Always clear the user settable flags.
13564            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13565                    bp.name) != null;
13566            if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13567                if (hasInstallState) {
13568                    writeInstallPermissions = true;
13569                } else {
13570                    writeRuntimePermissions = true;
13571                }
13572            }
13573
13574            // Below is only runtime permission handling.
13575            if (!bp.isRuntime()) {
13576                continue;
13577            }
13578
13579            // Never clobber system or policy.
13580            if ((oldFlags & policyOrSystemFlags) != 0) {
13581                continue;
13582            }
13583
13584            // If this permission was granted by default, make sure it is.
13585            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13586                if (permissionsState.grantRuntimePermission(bp, userId)
13587                        != PERMISSION_OPERATION_FAILURE) {
13588                    writeRuntimePermissions = true;
13589                }
13590            } else {
13591                // Otherwise, reset the permission.
13592                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13593                switch (revokeResult) {
13594                    case PERMISSION_OPERATION_SUCCESS: {
13595                        writeRuntimePermissions = true;
13596                    } break;
13597
13598                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13599                        writeRuntimePermissions = true;
13600                        final int appId = ps.appId;
13601                        mHandler.post(new Runnable() {
13602                            @Override
13603                            public void run() {
13604                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
13605                            }
13606                        });
13607                    } break;
13608                }
13609            }
13610        }
13611
13612        // Synchronously write as we are taking permissions away.
13613        if (writeRuntimePermissions) {
13614            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13615        }
13616
13617        // Synchronously write as we are taking permissions away.
13618        if (writeInstallPermissions) {
13619            mSettings.writeLPr();
13620        }
13621    }
13622
13623    /**
13624     * Remove entries from the keystore daemon. Will only remove it if the
13625     * {@code appId} is valid.
13626     */
13627    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13628        if (appId < 0) {
13629            return;
13630        }
13631
13632        final KeyStore keyStore = KeyStore.getInstance();
13633        if (keyStore != null) {
13634            if (userId == UserHandle.USER_ALL) {
13635                for (final int individual : sUserManager.getUserIds()) {
13636                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13637                }
13638            } else {
13639                keyStore.clearUid(UserHandle.getUid(userId, appId));
13640            }
13641        } else {
13642            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13643        }
13644    }
13645
13646    @Override
13647    public void deleteApplicationCacheFiles(final String packageName,
13648            final IPackageDataObserver observer) {
13649        mContext.enforceCallingOrSelfPermission(
13650                android.Manifest.permission.DELETE_CACHE_FILES, null);
13651        // Queue up an async operation since the package deletion may take a little while.
13652        final int userId = UserHandle.getCallingUserId();
13653        mHandler.post(new Runnable() {
13654            public void run() {
13655                mHandler.removeCallbacks(this);
13656                final boolean succeded;
13657                synchronized (mInstallLock) {
13658                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13659                }
13660                clearExternalStorageDataSync(packageName, userId, false);
13661                if (observer != null) {
13662                    try {
13663                        observer.onRemoveCompleted(packageName, succeded);
13664                    } catch (RemoteException e) {
13665                        Log.i(TAG, "Observer no longer exists.");
13666                    }
13667                } //end if observer
13668            } //end run
13669        });
13670    }
13671
13672    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13673        if (packageName == null) {
13674            Slog.w(TAG, "Attempt to delete null packageName.");
13675            return false;
13676        }
13677        PackageParser.Package p;
13678        synchronized (mPackages) {
13679            p = mPackages.get(packageName);
13680        }
13681        if (p == null) {
13682            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13683            return false;
13684        }
13685        final ApplicationInfo applicationInfo = p.applicationInfo;
13686        if (applicationInfo == null) {
13687            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13688            return false;
13689        }
13690        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13691        if (retCode < 0) {
13692            Slog.w(TAG, "Couldn't remove cache files for package: "
13693                       + packageName + " u" + userId);
13694            return false;
13695        }
13696        return true;
13697    }
13698
13699    @Override
13700    public void getPackageSizeInfo(final String packageName, int userHandle,
13701            final IPackageStatsObserver observer) {
13702        mContext.enforceCallingOrSelfPermission(
13703                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13704        if (packageName == null) {
13705            throw new IllegalArgumentException("Attempt to get size of null packageName");
13706        }
13707
13708        PackageStats stats = new PackageStats(packageName, userHandle);
13709
13710        /*
13711         * Queue up an async operation since the package measurement may take a
13712         * little while.
13713         */
13714        Message msg = mHandler.obtainMessage(INIT_COPY);
13715        msg.obj = new MeasureParams(stats, observer);
13716        mHandler.sendMessage(msg);
13717    }
13718
13719    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13720            PackageStats pStats) {
13721        if (packageName == null) {
13722            Slog.w(TAG, "Attempt to get size of null packageName.");
13723            return false;
13724        }
13725        PackageParser.Package p;
13726        boolean dataOnly = false;
13727        String libDirRoot = null;
13728        String asecPath = null;
13729        PackageSetting ps = null;
13730        synchronized (mPackages) {
13731            p = mPackages.get(packageName);
13732            ps = mSettings.mPackages.get(packageName);
13733            if(p == null) {
13734                dataOnly = true;
13735                if((ps == null) || (ps.pkg == null)) {
13736                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13737                    return false;
13738                }
13739                p = ps.pkg;
13740            }
13741            if (ps != null) {
13742                libDirRoot = ps.legacyNativeLibraryPathString;
13743            }
13744            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
13745                final long token = Binder.clearCallingIdentity();
13746                try {
13747                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13748                    if (secureContainerId != null) {
13749                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13750                    }
13751                } finally {
13752                    Binder.restoreCallingIdentity(token);
13753                }
13754            }
13755        }
13756        String publicSrcDir = null;
13757        if(!dataOnly) {
13758            final ApplicationInfo applicationInfo = p.applicationInfo;
13759            if (applicationInfo == null) {
13760                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13761                return false;
13762            }
13763            if (p.isForwardLocked()) {
13764                publicSrcDir = applicationInfo.getBaseResourcePath();
13765            }
13766        }
13767        // TODO: extend to measure size of split APKs
13768        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13769        // not just the first level.
13770        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13771        // just the primary.
13772        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13773
13774        String apkPath;
13775        File packageDir = new File(p.codePath);
13776
13777        if (packageDir.isDirectory() && p.canHaveOatDir()) {
13778            apkPath = packageDir.getAbsolutePath();
13779            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
13780            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
13781                libDirRoot = null;
13782            }
13783        } else {
13784            apkPath = p.baseCodePath;
13785        }
13786
13787        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath,
13788                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13789        if (res < 0) {
13790            return false;
13791        }
13792
13793        // Fix-up for forward-locked applications in ASEC containers.
13794        if (!isExternal(p)) {
13795            pStats.codeSize += pStats.externalCodeSize;
13796            pStats.externalCodeSize = 0L;
13797        }
13798
13799        return true;
13800    }
13801
13802
13803    @Override
13804    public void addPackageToPreferred(String packageName) {
13805        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13806    }
13807
13808    @Override
13809    public void removePackageFromPreferred(String packageName) {
13810        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13811    }
13812
13813    @Override
13814    public List<PackageInfo> getPreferredPackages(int flags) {
13815        return new ArrayList<PackageInfo>();
13816    }
13817
13818    private int getUidTargetSdkVersionLockedLPr(int uid) {
13819        Object obj = mSettings.getUserIdLPr(uid);
13820        if (obj instanceof SharedUserSetting) {
13821            final SharedUserSetting sus = (SharedUserSetting) obj;
13822            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13823            final Iterator<PackageSetting> it = sus.packages.iterator();
13824            while (it.hasNext()) {
13825                final PackageSetting ps = it.next();
13826                if (ps.pkg != null) {
13827                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13828                    if (v < vers) vers = v;
13829                }
13830            }
13831            return vers;
13832        } else if (obj instanceof PackageSetting) {
13833            final PackageSetting ps = (PackageSetting) obj;
13834            if (ps.pkg != null) {
13835                return ps.pkg.applicationInfo.targetSdkVersion;
13836            }
13837        }
13838        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13839    }
13840
13841    @Override
13842    public void addPreferredActivity(IntentFilter filter, int match,
13843            ComponentName[] set, ComponentName activity, int userId) {
13844        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13845                "Adding preferred");
13846    }
13847
13848    private void addPreferredActivityInternal(IntentFilter filter, int match,
13849            ComponentName[] set, ComponentName activity, boolean always, int userId,
13850            String opname) {
13851        // writer
13852        int callingUid = Binder.getCallingUid();
13853        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13854        if (filter.countActions() == 0) {
13855            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13856            return;
13857        }
13858        synchronized (mPackages) {
13859            if (mContext.checkCallingOrSelfPermission(
13860                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13861                    != PackageManager.PERMISSION_GRANTED) {
13862                if (getUidTargetSdkVersionLockedLPr(callingUid)
13863                        < Build.VERSION_CODES.FROYO) {
13864                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13865                            + callingUid);
13866                    return;
13867                }
13868                mContext.enforceCallingOrSelfPermission(
13869                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13870            }
13871
13872            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13873            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13874                    + userId + ":");
13875            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13876            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13877            scheduleWritePackageRestrictionsLocked(userId);
13878        }
13879    }
13880
13881    @Override
13882    public void replacePreferredActivity(IntentFilter filter, int match,
13883            ComponentName[] set, ComponentName activity, int userId) {
13884        if (filter.countActions() != 1) {
13885            throw new IllegalArgumentException(
13886                    "replacePreferredActivity expects filter to have only 1 action.");
13887        }
13888        if (filter.countDataAuthorities() != 0
13889                || filter.countDataPaths() != 0
13890                || filter.countDataSchemes() > 1
13891                || filter.countDataTypes() != 0) {
13892            throw new IllegalArgumentException(
13893                    "replacePreferredActivity expects filter to have no data authorities, " +
13894                    "paths, or types; and at most one scheme.");
13895        }
13896
13897        final int callingUid = Binder.getCallingUid();
13898        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13899        synchronized (mPackages) {
13900            if (mContext.checkCallingOrSelfPermission(
13901                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13902                    != PackageManager.PERMISSION_GRANTED) {
13903                if (getUidTargetSdkVersionLockedLPr(callingUid)
13904                        < Build.VERSION_CODES.FROYO) {
13905                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13906                            + Binder.getCallingUid());
13907                    return;
13908                }
13909                mContext.enforceCallingOrSelfPermission(
13910                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13911            }
13912
13913            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13914            if (pir != null) {
13915                // Get all of the existing entries that exactly match this filter.
13916                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13917                if (existing != null && existing.size() == 1) {
13918                    PreferredActivity cur = existing.get(0);
13919                    if (DEBUG_PREFERRED) {
13920                        Slog.i(TAG, "Checking replace of preferred:");
13921                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13922                        if (!cur.mPref.mAlways) {
13923                            Slog.i(TAG, "  -- CUR; not mAlways!");
13924                        } else {
13925                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13926                            Slog.i(TAG, "  -- CUR: mSet="
13927                                    + Arrays.toString(cur.mPref.mSetComponents));
13928                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13929                            Slog.i(TAG, "  -- NEW: mMatch="
13930                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13931                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13932                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13933                        }
13934                    }
13935                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13936                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13937                            && cur.mPref.sameSet(set)) {
13938                        // Setting the preferred activity to what it happens to be already
13939                        if (DEBUG_PREFERRED) {
13940                            Slog.i(TAG, "Replacing with same preferred activity "
13941                                    + cur.mPref.mShortComponent + " for user "
13942                                    + userId + ":");
13943                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13944                        }
13945                        return;
13946                    }
13947                }
13948
13949                if (existing != null) {
13950                    if (DEBUG_PREFERRED) {
13951                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13952                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13953                    }
13954                    for (int i = 0; i < existing.size(); i++) {
13955                        PreferredActivity pa = existing.get(i);
13956                        if (DEBUG_PREFERRED) {
13957                            Slog.i(TAG, "Removing existing preferred activity "
13958                                    + pa.mPref.mComponent + ":");
13959                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13960                        }
13961                        pir.removeFilter(pa);
13962                    }
13963                }
13964            }
13965            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13966                    "Replacing preferred");
13967        }
13968    }
13969
13970    @Override
13971    public void clearPackagePreferredActivities(String packageName) {
13972        final int uid = Binder.getCallingUid();
13973        // writer
13974        synchronized (mPackages) {
13975            PackageParser.Package pkg = mPackages.get(packageName);
13976            if (pkg == null || pkg.applicationInfo.uid != uid) {
13977                if (mContext.checkCallingOrSelfPermission(
13978                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13979                        != PackageManager.PERMISSION_GRANTED) {
13980                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13981                            < Build.VERSION_CODES.FROYO) {
13982                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13983                                + Binder.getCallingUid());
13984                        return;
13985                    }
13986                    mContext.enforceCallingOrSelfPermission(
13987                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13988                }
13989            }
13990
13991            int user = UserHandle.getCallingUserId();
13992            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13993                scheduleWritePackageRestrictionsLocked(user);
13994            }
13995        }
13996    }
13997
13998    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13999    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
14000        ArrayList<PreferredActivity> removed = null;
14001        boolean changed = false;
14002        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14003            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
14004            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14005            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
14006                continue;
14007            }
14008            Iterator<PreferredActivity> it = pir.filterIterator();
14009            while (it.hasNext()) {
14010                PreferredActivity pa = it.next();
14011                // Mark entry for removal only if it matches the package name
14012                // and the entry is of type "always".
14013                if (packageName == null ||
14014                        (pa.mPref.mComponent.getPackageName().equals(packageName)
14015                                && pa.mPref.mAlways)) {
14016                    if (removed == null) {
14017                        removed = new ArrayList<PreferredActivity>();
14018                    }
14019                    removed.add(pa);
14020                }
14021            }
14022            if (removed != null) {
14023                for (int j=0; j<removed.size(); j++) {
14024                    PreferredActivity pa = removed.get(j);
14025                    pir.removeFilter(pa);
14026                }
14027                changed = true;
14028            }
14029        }
14030        return changed;
14031    }
14032
14033    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14034    private void clearIntentFilterVerificationsLPw(int userId) {
14035        final int packageCount = mPackages.size();
14036        for (int i = 0; i < packageCount; i++) {
14037            PackageParser.Package pkg = mPackages.valueAt(i);
14038            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
14039        }
14040    }
14041
14042    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14043    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
14044        if (userId == UserHandle.USER_ALL) {
14045            if (mSettings.removeIntentFilterVerificationLPw(packageName,
14046                    sUserManager.getUserIds())) {
14047                for (int oneUserId : sUserManager.getUserIds()) {
14048                    scheduleWritePackageRestrictionsLocked(oneUserId);
14049                }
14050            }
14051        } else {
14052            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
14053                scheduleWritePackageRestrictionsLocked(userId);
14054            }
14055        }
14056    }
14057
14058    void clearDefaultBrowserIfNeeded(String packageName) {
14059        for (int oneUserId : sUserManager.getUserIds()) {
14060            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
14061            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
14062            if (packageName.equals(defaultBrowserPackageName)) {
14063                setDefaultBrowserPackageName(null, oneUserId);
14064            }
14065        }
14066    }
14067
14068    @Override
14069    public void resetApplicationPreferences(int userId) {
14070        mContext.enforceCallingOrSelfPermission(
14071                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14072        // writer
14073        synchronized (mPackages) {
14074            final long identity = Binder.clearCallingIdentity();
14075            try {
14076                clearPackagePreferredActivitiesLPw(null, userId);
14077                mSettings.applyDefaultPreferredAppsLPw(this, userId);
14078                // TODO: We have to reset the default SMS and Phone. This requires
14079                // significant refactoring to keep all default apps in the package
14080                // manager (cleaner but more work) or have the services provide
14081                // callbacks to the package manager to request a default app reset.
14082                applyFactoryDefaultBrowserLPw(userId);
14083                clearIntentFilterVerificationsLPw(userId);
14084                primeDomainVerificationsLPw(userId);
14085                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
14086                scheduleWritePackageRestrictionsLocked(userId);
14087            } finally {
14088                Binder.restoreCallingIdentity(identity);
14089            }
14090        }
14091    }
14092
14093    @Override
14094    public int getPreferredActivities(List<IntentFilter> outFilters,
14095            List<ComponentName> outActivities, String packageName) {
14096
14097        int num = 0;
14098        final int userId = UserHandle.getCallingUserId();
14099        // reader
14100        synchronized (mPackages) {
14101            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14102            if (pir != null) {
14103                final Iterator<PreferredActivity> it = pir.filterIterator();
14104                while (it.hasNext()) {
14105                    final PreferredActivity pa = it.next();
14106                    if (packageName == null
14107                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
14108                                    && pa.mPref.mAlways)) {
14109                        if (outFilters != null) {
14110                            outFilters.add(new IntentFilter(pa));
14111                        }
14112                        if (outActivities != null) {
14113                            outActivities.add(pa.mPref.mComponent);
14114                        }
14115                    }
14116                }
14117            }
14118        }
14119
14120        return num;
14121    }
14122
14123    @Override
14124    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
14125            int userId) {
14126        int callingUid = Binder.getCallingUid();
14127        if (callingUid != Process.SYSTEM_UID) {
14128            throw new SecurityException(
14129                    "addPersistentPreferredActivity can only be run by the system");
14130        }
14131        if (filter.countActions() == 0) {
14132            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14133            return;
14134        }
14135        synchronized (mPackages) {
14136            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
14137                    " :");
14138            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14139            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
14140                    new PersistentPreferredActivity(filter, activity));
14141            scheduleWritePackageRestrictionsLocked(userId);
14142        }
14143    }
14144
14145    @Override
14146    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
14147        int callingUid = Binder.getCallingUid();
14148        if (callingUid != Process.SYSTEM_UID) {
14149            throw new SecurityException(
14150                    "clearPackagePersistentPreferredActivities can only be run by the system");
14151        }
14152        ArrayList<PersistentPreferredActivity> removed = null;
14153        boolean changed = false;
14154        synchronized (mPackages) {
14155            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
14156                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
14157                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
14158                        .valueAt(i);
14159                if (userId != thisUserId) {
14160                    continue;
14161                }
14162                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
14163                while (it.hasNext()) {
14164                    PersistentPreferredActivity ppa = it.next();
14165                    // Mark entry for removal only if it matches the package name.
14166                    if (ppa.mComponent.getPackageName().equals(packageName)) {
14167                        if (removed == null) {
14168                            removed = new ArrayList<PersistentPreferredActivity>();
14169                        }
14170                        removed.add(ppa);
14171                    }
14172                }
14173                if (removed != null) {
14174                    for (int j=0; j<removed.size(); j++) {
14175                        PersistentPreferredActivity ppa = removed.get(j);
14176                        ppir.removeFilter(ppa);
14177                    }
14178                    changed = true;
14179                }
14180            }
14181
14182            if (changed) {
14183                scheduleWritePackageRestrictionsLocked(userId);
14184            }
14185        }
14186    }
14187
14188    /**
14189     * Common machinery for picking apart a restored XML blob and passing
14190     * it to a caller-supplied functor to be applied to the running system.
14191     */
14192    private void restoreFromXml(XmlPullParser parser, int userId,
14193            String expectedStartTag, BlobXmlRestorer functor)
14194            throws IOException, XmlPullParserException {
14195        int type;
14196        while ((type = parser.next()) != XmlPullParser.START_TAG
14197                && type != XmlPullParser.END_DOCUMENT) {
14198        }
14199        if (type != XmlPullParser.START_TAG) {
14200            // oops didn't find a start tag?!
14201            if (DEBUG_BACKUP) {
14202                Slog.e(TAG, "Didn't find start tag during restore");
14203            }
14204            return;
14205        }
14206
14207        // this is supposed to be TAG_PREFERRED_BACKUP
14208        if (!expectedStartTag.equals(parser.getName())) {
14209            if (DEBUG_BACKUP) {
14210                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14211            }
14212            return;
14213        }
14214
14215        // skip interfering stuff, then we're aligned with the backing implementation
14216        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14217        functor.apply(parser, userId);
14218    }
14219
14220    private interface BlobXmlRestorer {
14221        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14222    }
14223
14224    /**
14225     * Non-Binder method, support for the backup/restore mechanism: write the
14226     * full set of preferred activities in its canonical XML format.  Returns the
14227     * XML output as a byte array, or null if there is none.
14228     */
14229    @Override
14230    public byte[] getPreferredActivityBackup(int userId) {
14231        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14232            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14233        }
14234
14235        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14236        try {
14237            final XmlSerializer serializer = new FastXmlSerializer();
14238            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14239            serializer.startDocument(null, true);
14240            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14241
14242            synchronized (mPackages) {
14243                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14244            }
14245
14246            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14247            serializer.endDocument();
14248            serializer.flush();
14249        } catch (Exception e) {
14250            if (DEBUG_BACKUP) {
14251                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14252            }
14253            return null;
14254        }
14255
14256        return dataStream.toByteArray();
14257    }
14258
14259    @Override
14260    public void restorePreferredActivities(byte[] backup, int userId) {
14261        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14262            throw new SecurityException("Only the system may call restorePreferredActivities()");
14263        }
14264
14265        try {
14266            final XmlPullParser parser = Xml.newPullParser();
14267            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14268            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14269                    new BlobXmlRestorer() {
14270                        @Override
14271                        public void apply(XmlPullParser parser, int userId)
14272                                throws XmlPullParserException, IOException {
14273                            synchronized (mPackages) {
14274                                mSettings.readPreferredActivitiesLPw(parser, userId);
14275                            }
14276                        }
14277                    } );
14278        } catch (Exception e) {
14279            if (DEBUG_BACKUP) {
14280                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14281            }
14282        }
14283    }
14284
14285    /**
14286     * Non-Binder method, support for the backup/restore mechanism: write the
14287     * default browser (etc) settings in its canonical XML format.  Returns the default
14288     * browser XML representation as a byte array, or null if there is none.
14289     */
14290    @Override
14291    public byte[] getDefaultAppsBackup(int userId) {
14292        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14293            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14294        }
14295
14296        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14297        try {
14298            final XmlSerializer serializer = new FastXmlSerializer();
14299            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14300            serializer.startDocument(null, true);
14301            serializer.startTag(null, TAG_DEFAULT_APPS);
14302
14303            synchronized (mPackages) {
14304                mSettings.writeDefaultAppsLPr(serializer, userId);
14305            }
14306
14307            serializer.endTag(null, TAG_DEFAULT_APPS);
14308            serializer.endDocument();
14309            serializer.flush();
14310        } catch (Exception e) {
14311            if (DEBUG_BACKUP) {
14312                Slog.e(TAG, "Unable to write default apps for backup", e);
14313            }
14314            return null;
14315        }
14316
14317        return dataStream.toByteArray();
14318    }
14319
14320    @Override
14321    public void restoreDefaultApps(byte[] backup, int userId) {
14322        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14323            throw new SecurityException("Only the system may call restoreDefaultApps()");
14324        }
14325
14326        try {
14327            final XmlPullParser parser = Xml.newPullParser();
14328            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14329            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14330                    new BlobXmlRestorer() {
14331                        @Override
14332                        public void apply(XmlPullParser parser, int userId)
14333                                throws XmlPullParserException, IOException {
14334                            synchronized (mPackages) {
14335                                mSettings.readDefaultAppsLPw(parser, userId);
14336                            }
14337                        }
14338                    } );
14339        } catch (Exception e) {
14340            if (DEBUG_BACKUP) {
14341                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14342            }
14343        }
14344    }
14345
14346    @Override
14347    public byte[] getIntentFilterVerificationBackup(int userId) {
14348        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14349            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14350        }
14351
14352        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14353        try {
14354            final XmlSerializer serializer = new FastXmlSerializer();
14355            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14356            serializer.startDocument(null, true);
14357            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14358
14359            synchronized (mPackages) {
14360                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14361            }
14362
14363            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14364            serializer.endDocument();
14365            serializer.flush();
14366        } catch (Exception e) {
14367            if (DEBUG_BACKUP) {
14368                Slog.e(TAG, "Unable to write default apps for backup", e);
14369            }
14370            return null;
14371        }
14372
14373        return dataStream.toByteArray();
14374    }
14375
14376    @Override
14377    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14378        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14379            throw new SecurityException("Only the system may call restorePreferredActivities()");
14380        }
14381
14382        try {
14383            final XmlPullParser parser = Xml.newPullParser();
14384            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14385            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14386                    new BlobXmlRestorer() {
14387                        @Override
14388                        public void apply(XmlPullParser parser, int userId)
14389                                throws XmlPullParserException, IOException {
14390                            synchronized (mPackages) {
14391                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14392                                mSettings.writeLPr();
14393                            }
14394                        }
14395                    } );
14396        } catch (Exception e) {
14397            if (DEBUG_BACKUP) {
14398                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14399            }
14400        }
14401    }
14402
14403    @Override
14404    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14405            int sourceUserId, int targetUserId, int flags) {
14406        mContext.enforceCallingOrSelfPermission(
14407                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14408        int callingUid = Binder.getCallingUid();
14409        enforceOwnerRights(ownerPackage, callingUid);
14410        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14411        if (intentFilter.countActions() == 0) {
14412            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14413            return;
14414        }
14415        synchronized (mPackages) {
14416            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14417                    ownerPackage, targetUserId, flags);
14418            CrossProfileIntentResolver resolver =
14419                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14420            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14421            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14422            if (existing != null) {
14423                int size = existing.size();
14424                for (int i = 0; i < size; i++) {
14425                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14426                        return;
14427                    }
14428                }
14429            }
14430            resolver.addFilter(newFilter);
14431            scheduleWritePackageRestrictionsLocked(sourceUserId);
14432        }
14433    }
14434
14435    @Override
14436    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14437        mContext.enforceCallingOrSelfPermission(
14438                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14439        int callingUid = Binder.getCallingUid();
14440        enforceOwnerRights(ownerPackage, callingUid);
14441        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14442        synchronized (mPackages) {
14443            CrossProfileIntentResolver resolver =
14444                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14445            ArraySet<CrossProfileIntentFilter> set =
14446                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14447            for (CrossProfileIntentFilter filter : set) {
14448                if (filter.getOwnerPackage().equals(ownerPackage)) {
14449                    resolver.removeFilter(filter);
14450                }
14451            }
14452            scheduleWritePackageRestrictionsLocked(sourceUserId);
14453        }
14454    }
14455
14456    // Enforcing that callingUid is owning pkg on userId
14457    private void enforceOwnerRights(String pkg, int callingUid) {
14458        // The system owns everything.
14459        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14460            return;
14461        }
14462        int callingUserId = UserHandle.getUserId(callingUid);
14463        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14464        if (pi == null) {
14465            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14466                    + callingUserId);
14467        }
14468        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14469            throw new SecurityException("Calling uid " + callingUid
14470                    + " does not own package " + pkg);
14471        }
14472    }
14473
14474    @Override
14475    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14476        Intent intent = new Intent(Intent.ACTION_MAIN);
14477        intent.addCategory(Intent.CATEGORY_HOME);
14478
14479        final int callingUserId = UserHandle.getCallingUserId();
14480        List<ResolveInfo> list = queryIntentActivities(intent, null,
14481                PackageManager.GET_META_DATA, callingUserId);
14482        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14483                true, false, false, callingUserId);
14484
14485        allHomeCandidates.clear();
14486        if (list != null) {
14487            for (ResolveInfo ri : list) {
14488                allHomeCandidates.add(ri);
14489            }
14490        }
14491        return (preferred == null || preferred.activityInfo == null)
14492                ? null
14493                : new ComponentName(preferred.activityInfo.packageName,
14494                        preferred.activityInfo.name);
14495    }
14496
14497    @Override
14498    public void setApplicationEnabledSetting(String appPackageName,
14499            int newState, int flags, int userId, String callingPackage) {
14500        if (!sUserManager.exists(userId)) return;
14501        if (callingPackage == null) {
14502            callingPackage = Integer.toString(Binder.getCallingUid());
14503        }
14504        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14505    }
14506
14507    @Override
14508    public void setComponentEnabledSetting(ComponentName componentName,
14509            int newState, int flags, int userId) {
14510        if (!sUserManager.exists(userId)) return;
14511        setEnabledSetting(componentName.getPackageName(),
14512                componentName.getClassName(), newState, flags, userId, null);
14513    }
14514
14515    private void setEnabledSetting(final String packageName, String className, int newState,
14516            final int flags, int userId, String callingPackage) {
14517        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14518              || newState == COMPONENT_ENABLED_STATE_ENABLED
14519              || newState == COMPONENT_ENABLED_STATE_DISABLED
14520              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14521              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14522            throw new IllegalArgumentException("Invalid new component state: "
14523                    + newState);
14524        }
14525        PackageSetting pkgSetting;
14526        final int uid = Binder.getCallingUid();
14527        final int permission = mContext.checkCallingOrSelfPermission(
14528                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14529        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14530        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14531        boolean sendNow = false;
14532        boolean isApp = (className == null);
14533        String componentName = isApp ? packageName : className;
14534        int packageUid = -1;
14535        ArrayList<String> components;
14536
14537        // writer
14538        synchronized (mPackages) {
14539            pkgSetting = mSettings.mPackages.get(packageName);
14540            if (pkgSetting == null) {
14541                if (className == null) {
14542                    throw new IllegalArgumentException(
14543                            "Unknown package: " + packageName);
14544                }
14545                throw new IllegalArgumentException(
14546                        "Unknown component: " + packageName
14547                        + "/" + className);
14548            }
14549            // Allow root and verify that userId is not being specified by a different user
14550            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14551                throw new SecurityException(
14552                        "Permission Denial: attempt to change component state from pid="
14553                        + Binder.getCallingPid()
14554                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14555            }
14556            if (className == null) {
14557                // We're dealing with an application/package level state change
14558                if (pkgSetting.getEnabled(userId) == newState) {
14559                    // Nothing to do
14560                    return;
14561                }
14562                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14563                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14564                    // Don't care about who enables an app.
14565                    callingPackage = null;
14566                }
14567                pkgSetting.setEnabled(newState, userId, callingPackage);
14568                // pkgSetting.pkg.mSetEnabled = newState;
14569            } else {
14570                // We're dealing with a component level state change
14571                // First, verify that this is a valid class name.
14572                PackageParser.Package pkg = pkgSetting.pkg;
14573                if (pkg == null || !pkg.hasComponentClassName(className)) {
14574                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14575                        throw new IllegalArgumentException("Component class " + className
14576                                + " does not exist in " + packageName);
14577                    } else {
14578                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14579                                + className + " does not exist in " + packageName);
14580                    }
14581                }
14582                switch (newState) {
14583                case COMPONENT_ENABLED_STATE_ENABLED:
14584                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14585                        return;
14586                    }
14587                    break;
14588                case COMPONENT_ENABLED_STATE_DISABLED:
14589                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14590                        return;
14591                    }
14592                    break;
14593                case COMPONENT_ENABLED_STATE_DEFAULT:
14594                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14595                        return;
14596                    }
14597                    break;
14598                default:
14599                    Slog.e(TAG, "Invalid new component state: " + newState);
14600                    return;
14601                }
14602            }
14603            scheduleWritePackageRestrictionsLocked(userId);
14604            components = mPendingBroadcasts.get(userId, packageName);
14605            final boolean newPackage = components == null;
14606            if (newPackage) {
14607                components = new ArrayList<String>();
14608            }
14609            if (!components.contains(componentName)) {
14610                components.add(componentName);
14611            }
14612            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14613                sendNow = true;
14614                // Purge entry from pending broadcast list if another one exists already
14615                // since we are sending one right away.
14616                mPendingBroadcasts.remove(userId, packageName);
14617            } else {
14618                if (newPackage) {
14619                    mPendingBroadcasts.put(userId, packageName, components);
14620                }
14621                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14622                    // Schedule a message
14623                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14624                }
14625            }
14626        }
14627
14628        long callingId = Binder.clearCallingIdentity();
14629        try {
14630            if (sendNow) {
14631                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14632                sendPackageChangedBroadcast(packageName,
14633                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14634            }
14635        } finally {
14636            Binder.restoreCallingIdentity(callingId);
14637        }
14638    }
14639
14640    private void sendPackageChangedBroadcast(String packageName,
14641            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14642        if (DEBUG_INSTALL)
14643            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14644                    + componentNames);
14645        Bundle extras = new Bundle(4);
14646        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14647        String nameList[] = new String[componentNames.size()];
14648        componentNames.toArray(nameList);
14649        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14650        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14651        extras.putInt(Intent.EXTRA_UID, packageUid);
14652        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14653                new int[] {UserHandle.getUserId(packageUid)});
14654    }
14655
14656    @Override
14657    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14658        if (!sUserManager.exists(userId)) return;
14659        final int uid = Binder.getCallingUid();
14660        final int permission = mContext.checkCallingOrSelfPermission(
14661                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14662        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14663        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14664        // writer
14665        synchronized (mPackages) {
14666            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14667                    allowedByPermission, uid, userId)) {
14668                scheduleWritePackageRestrictionsLocked(userId);
14669            }
14670        }
14671    }
14672
14673    @Override
14674    public String getInstallerPackageName(String packageName) {
14675        // reader
14676        synchronized (mPackages) {
14677            return mSettings.getInstallerPackageNameLPr(packageName);
14678        }
14679    }
14680
14681    @Override
14682    public int getApplicationEnabledSetting(String packageName, int userId) {
14683        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14684        int uid = Binder.getCallingUid();
14685        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14686        // reader
14687        synchronized (mPackages) {
14688            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14689        }
14690    }
14691
14692    @Override
14693    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14694        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14695        int uid = Binder.getCallingUid();
14696        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14697        // reader
14698        synchronized (mPackages) {
14699            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14700        }
14701    }
14702
14703    @Override
14704    public void enterSafeMode() {
14705        enforceSystemOrRoot("Only the system can request entering safe mode");
14706
14707        if (!mSystemReady) {
14708            mSafeMode = true;
14709        }
14710    }
14711
14712    @Override
14713    public void systemReady() {
14714        mSystemReady = true;
14715
14716        // Read the compatibilty setting when the system is ready.
14717        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14718                mContext.getContentResolver(),
14719                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14720        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14721        if (DEBUG_SETTINGS) {
14722            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14723        }
14724
14725        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14726
14727        synchronized (mPackages) {
14728            // Verify that all of the preferred activity components actually
14729            // exist.  It is possible for applications to be updated and at
14730            // that point remove a previously declared activity component that
14731            // had been set as a preferred activity.  We try to clean this up
14732            // the next time we encounter that preferred activity, but it is
14733            // possible for the user flow to never be able to return to that
14734            // situation so here we do a sanity check to make sure we haven't
14735            // left any junk around.
14736            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14737            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14738                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14739                removed.clear();
14740                for (PreferredActivity pa : pir.filterSet()) {
14741                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14742                        removed.add(pa);
14743                    }
14744                }
14745                if (removed.size() > 0) {
14746                    for (int r=0; r<removed.size(); r++) {
14747                        PreferredActivity pa = removed.get(r);
14748                        Slog.w(TAG, "Removing dangling preferred activity: "
14749                                + pa.mPref.mComponent);
14750                        pir.removeFilter(pa);
14751                    }
14752                    mSettings.writePackageRestrictionsLPr(
14753                            mSettings.mPreferredActivities.keyAt(i));
14754                }
14755            }
14756
14757            for (int userId : UserManagerService.getInstance().getUserIds()) {
14758                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14759                    grantPermissionsUserIds = ArrayUtils.appendInt(
14760                            grantPermissionsUserIds, userId);
14761                }
14762            }
14763        }
14764        sUserManager.systemReady();
14765
14766        // If we upgraded grant all default permissions before kicking off.
14767        for (int userId : grantPermissionsUserIds) {
14768            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14769        }
14770
14771        // Kick off any messages waiting for system ready
14772        if (mPostSystemReadyMessages != null) {
14773            for (Message msg : mPostSystemReadyMessages) {
14774                msg.sendToTarget();
14775            }
14776            mPostSystemReadyMessages = null;
14777        }
14778
14779        // Watch for external volumes that come and go over time
14780        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14781        storage.registerListener(mStorageListener);
14782
14783        mInstallerService.systemReady();
14784        mPackageDexOptimizer.systemReady();
14785
14786        MountServiceInternal mountServiceInternal = LocalServices.getService(
14787                MountServiceInternal.class);
14788        mountServiceInternal.addExternalStoragePolicy(
14789                new MountServiceInternal.ExternalStorageMountPolicy() {
14790            @Override
14791            public int getMountMode(int uid, String packageName) {
14792                if (Process.isIsolated(uid)) {
14793                    return Zygote.MOUNT_EXTERNAL_NONE;
14794                }
14795                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
14796                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14797                }
14798                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14799                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14800                }
14801                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14802                    return Zygote.MOUNT_EXTERNAL_READ;
14803                }
14804                return Zygote.MOUNT_EXTERNAL_WRITE;
14805            }
14806
14807            @Override
14808            public boolean hasExternalStorage(int uid, String packageName) {
14809                return true;
14810            }
14811        });
14812    }
14813
14814    @Override
14815    public boolean isSafeMode() {
14816        return mSafeMode;
14817    }
14818
14819    @Override
14820    public boolean hasSystemUidErrors() {
14821        return mHasSystemUidErrors;
14822    }
14823
14824    static String arrayToString(int[] array) {
14825        StringBuffer buf = new StringBuffer(128);
14826        buf.append('[');
14827        if (array != null) {
14828            for (int i=0; i<array.length; i++) {
14829                if (i > 0) buf.append(", ");
14830                buf.append(array[i]);
14831            }
14832        }
14833        buf.append(']');
14834        return buf.toString();
14835    }
14836
14837    static class DumpState {
14838        public static final int DUMP_LIBS = 1 << 0;
14839        public static final int DUMP_FEATURES = 1 << 1;
14840        public static final int DUMP_RESOLVERS = 1 << 2;
14841        public static final int DUMP_PERMISSIONS = 1 << 3;
14842        public static final int DUMP_PACKAGES = 1 << 4;
14843        public static final int DUMP_SHARED_USERS = 1 << 5;
14844        public static final int DUMP_MESSAGES = 1 << 6;
14845        public static final int DUMP_PROVIDERS = 1 << 7;
14846        public static final int DUMP_VERIFIERS = 1 << 8;
14847        public static final int DUMP_PREFERRED = 1 << 9;
14848        public static final int DUMP_PREFERRED_XML = 1 << 10;
14849        public static final int DUMP_KEYSETS = 1 << 11;
14850        public static final int DUMP_VERSION = 1 << 12;
14851        public static final int DUMP_INSTALLS = 1 << 13;
14852        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14853        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14854
14855        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14856
14857        private int mTypes;
14858
14859        private int mOptions;
14860
14861        private boolean mTitlePrinted;
14862
14863        private SharedUserSetting mSharedUser;
14864
14865        public boolean isDumping(int type) {
14866            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14867                return true;
14868            }
14869
14870            return (mTypes & type) != 0;
14871        }
14872
14873        public void setDump(int type) {
14874            mTypes |= type;
14875        }
14876
14877        public boolean isOptionEnabled(int option) {
14878            return (mOptions & option) != 0;
14879        }
14880
14881        public void setOptionEnabled(int option) {
14882            mOptions |= option;
14883        }
14884
14885        public boolean onTitlePrinted() {
14886            final boolean printed = mTitlePrinted;
14887            mTitlePrinted = true;
14888            return printed;
14889        }
14890
14891        public boolean getTitlePrinted() {
14892            return mTitlePrinted;
14893        }
14894
14895        public void setTitlePrinted(boolean enabled) {
14896            mTitlePrinted = enabled;
14897        }
14898
14899        public SharedUserSetting getSharedUser() {
14900            return mSharedUser;
14901        }
14902
14903        public void setSharedUser(SharedUserSetting user) {
14904            mSharedUser = user;
14905        }
14906    }
14907
14908    @Override
14909    public void onShellCommand(FileDescriptor in, FileDescriptor out,
14910            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
14911        (new PackageManagerShellCommand(this)).exec(
14912                this, in, out, err, args, resultReceiver);
14913    }
14914
14915    @Override
14916    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14917        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14918                != PackageManager.PERMISSION_GRANTED) {
14919            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14920                    + Binder.getCallingPid()
14921                    + ", uid=" + Binder.getCallingUid()
14922                    + " without permission "
14923                    + android.Manifest.permission.DUMP);
14924            return;
14925        }
14926
14927        DumpState dumpState = new DumpState();
14928        boolean fullPreferred = false;
14929        boolean checkin = false;
14930
14931        String packageName = null;
14932        ArraySet<String> permissionNames = null;
14933
14934        int opti = 0;
14935        while (opti < args.length) {
14936            String opt = args[opti];
14937            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14938                break;
14939            }
14940            opti++;
14941
14942            if ("-a".equals(opt)) {
14943                // Right now we only know how to print all.
14944            } else if ("-h".equals(opt)) {
14945                pw.println("Package manager dump options:");
14946                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14947                pw.println("    --checkin: dump for a checkin");
14948                pw.println("    -f: print details of intent filters");
14949                pw.println("    -h: print this help");
14950                pw.println("  cmd may be one of:");
14951                pw.println("    l[ibraries]: list known shared libraries");
14952                pw.println("    f[ibraries]: list device features");
14953                pw.println("    k[eysets]: print known keysets");
14954                pw.println("    r[esolvers]: dump intent resolvers");
14955                pw.println("    perm[issions]: dump permissions");
14956                pw.println("    permission [name ...]: dump declaration and use of given permission");
14957                pw.println("    pref[erred]: print preferred package settings");
14958                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14959                pw.println("    prov[iders]: dump content providers");
14960                pw.println("    p[ackages]: dump installed packages");
14961                pw.println("    s[hared-users]: dump shared user IDs");
14962                pw.println("    m[essages]: print collected runtime messages");
14963                pw.println("    v[erifiers]: print package verifier info");
14964                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14965                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14966                pw.println("    version: print database version info");
14967                pw.println("    write: write current settings now");
14968                pw.println("    installs: details about install sessions");
14969                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
14970                pw.println("    <package.name>: info about given package");
14971                return;
14972            } else if ("--checkin".equals(opt)) {
14973                checkin = true;
14974            } else if ("-f".equals(opt)) {
14975                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14976            } else {
14977                pw.println("Unknown argument: " + opt + "; use -h for help");
14978            }
14979        }
14980
14981        // Is the caller requesting to dump a particular piece of data?
14982        if (opti < args.length) {
14983            String cmd = args[opti];
14984            opti++;
14985            // Is this a package name?
14986            if ("android".equals(cmd) || cmd.contains(".")) {
14987                packageName = cmd;
14988                // When dumping a single package, we always dump all of its
14989                // filter information since the amount of data will be reasonable.
14990                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14991            } else if ("check-permission".equals(cmd)) {
14992                if (opti >= args.length) {
14993                    pw.println("Error: check-permission missing permission argument");
14994                    return;
14995                }
14996                String perm = args[opti];
14997                opti++;
14998                if (opti >= args.length) {
14999                    pw.println("Error: check-permission missing package argument");
15000                    return;
15001                }
15002                String pkg = args[opti];
15003                opti++;
15004                int user = UserHandle.getUserId(Binder.getCallingUid());
15005                if (opti < args.length) {
15006                    try {
15007                        user = Integer.parseInt(args[opti]);
15008                    } catch (NumberFormatException e) {
15009                        pw.println("Error: check-permission user argument is not a number: "
15010                                + args[opti]);
15011                        return;
15012                    }
15013                }
15014                pw.println(checkPermission(perm, pkg, user));
15015                return;
15016            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
15017                dumpState.setDump(DumpState.DUMP_LIBS);
15018            } else if ("f".equals(cmd) || "features".equals(cmd)) {
15019                dumpState.setDump(DumpState.DUMP_FEATURES);
15020            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
15021                dumpState.setDump(DumpState.DUMP_RESOLVERS);
15022            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
15023                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
15024            } else if ("permission".equals(cmd)) {
15025                if (opti >= args.length) {
15026                    pw.println("Error: permission requires permission name");
15027                    return;
15028                }
15029                permissionNames = new ArraySet<>();
15030                while (opti < args.length) {
15031                    permissionNames.add(args[opti]);
15032                    opti++;
15033                }
15034                dumpState.setDump(DumpState.DUMP_PERMISSIONS
15035                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
15036            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
15037                dumpState.setDump(DumpState.DUMP_PREFERRED);
15038            } else if ("preferred-xml".equals(cmd)) {
15039                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
15040                if (opti < args.length && "--full".equals(args[opti])) {
15041                    fullPreferred = true;
15042                    opti++;
15043                }
15044            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
15045                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
15046            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
15047                dumpState.setDump(DumpState.DUMP_PACKAGES);
15048            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
15049                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
15050            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
15051                dumpState.setDump(DumpState.DUMP_PROVIDERS);
15052            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
15053                dumpState.setDump(DumpState.DUMP_MESSAGES);
15054            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
15055                dumpState.setDump(DumpState.DUMP_VERIFIERS);
15056            } else if ("i".equals(cmd) || "ifv".equals(cmd)
15057                    || "intent-filter-verifiers".equals(cmd)) {
15058                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
15059            } else if ("version".equals(cmd)) {
15060                dumpState.setDump(DumpState.DUMP_VERSION);
15061            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
15062                dumpState.setDump(DumpState.DUMP_KEYSETS);
15063            } else if ("installs".equals(cmd)) {
15064                dumpState.setDump(DumpState.DUMP_INSTALLS);
15065            } else if ("write".equals(cmd)) {
15066                synchronized (mPackages) {
15067                    mSettings.writeLPr();
15068                    pw.println("Settings written.");
15069                    return;
15070                }
15071            }
15072        }
15073
15074        if (checkin) {
15075            pw.println("vers,1");
15076        }
15077
15078        // reader
15079        synchronized (mPackages) {
15080            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
15081                if (!checkin) {
15082                    if (dumpState.onTitlePrinted())
15083                        pw.println();
15084                    pw.println("Database versions:");
15085                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
15086                }
15087            }
15088
15089            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
15090                if (!checkin) {
15091                    if (dumpState.onTitlePrinted())
15092                        pw.println();
15093                    pw.println("Verifiers:");
15094                    pw.print("  Required: ");
15095                    pw.print(mRequiredVerifierPackage);
15096                    pw.print(" (uid=");
15097                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
15098                    pw.println(")");
15099                } else if (mRequiredVerifierPackage != null) {
15100                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
15101                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
15102                }
15103            }
15104
15105            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
15106                    packageName == null) {
15107                if (mIntentFilterVerifierComponent != null) {
15108                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
15109                    if (!checkin) {
15110                        if (dumpState.onTitlePrinted())
15111                            pw.println();
15112                        pw.println("Intent Filter Verifier:");
15113                        pw.print("  Using: ");
15114                        pw.print(verifierPackageName);
15115                        pw.print(" (uid=");
15116                        pw.print(getPackageUid(verifierPackageName, 0));
15117                        pw.println(")");
15118                    } else if (verifierPackageName != null) {
15119                        pw.print("ifv,"); pw.print(verifierPackageName);
15120                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
15121                    }
15122                } else {
15123                    pw.println();
15124                    pw.println("No Intent Filter Verifier available!");
15125                }
15126            }
15127
15128            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
15129                boolean printedHeader = false;
15130                final Iterator<String> it = mSharedLibraries.keySet().iterator();
15131                while (it.hasNext()) {
15132                    String name = it.next();
15133                    SharedLibraryEntry ent = mSharedLibraries.get(name);
15134                    if (!checkin) {
15135                        if (!printedHeader) {
15136                            if (dumpState.onTitlePrinted())
15137                                pw.println();
15138                            pw.println("Libraries:");
15139                            printedHeader = true;
15140                        }
15141                        pw.print("  ");
15142                    } else {
15143                        pw.print("lib,");
15144                    }
15145                    pw.print(name);
15146                    if (!checkin) {
15147                        pw.print(" -> ");
15148                    }
15149                    if (ent.path != null) {
15150                        if (!checkin) {
15151                            pw.print("(jar) ");
15152                            pw.print(ent.path);
15153                        } else {
15154                            pw.print(",jar,");
15155                            pw.print(ent.path);
15156                        }
15157                    } else {
15158                        if (!checkin) {
15159                            pw.print("(apk) ");
15160                            pw.print(ent.apk);
15161                        } else {
15162                            pw.print(",apk,");
15163                            pw.print(ent.apk);
15164                        }
15165                    }
15166                    pw.println();
15167                }
15168            }
15169
15170            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
15171                if (dumpState.onTitlePrinted())
15172                    pw.println();
15173                if (!checkin) {
15174                    pw.println("Features:");
15175                }
15176                Iterator<String> it = mAvailableFeatures.keySet().iterator();
15177                while (it.hasNext()) {
15178                    String name = it.next();
15179                    if (!checkin) {
15180                        pw.print("  ");
15181                    } else {
15182                        pw.print("feat,");
15183                    }
15184                    pw.println(name);
15185                }
15186            }
15187
15188            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
15189                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
15190                        : "Activity Resolver Table:", "  ", packageName,
15191                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15192                    dumpState.setTitlePrinted(true);
15193                }
15194                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
15195                        : "Receiver Resolver Table:", "  ", packageName,
15196                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15197                    dumpState.setTitlePrinted(true);
15198                }
15199                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
15200                        : "Service Resolver Table:", "  ", packageName,
15201                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15202                    dumpState.setTitlePrinted(true);
15203                }
15204                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
15205                        : "Provider Resolver Table:", "  ", packageName,
15206                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15207                    dumpState.setTitlePrinted(true);
15208                }
15209            }
15210
15211            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
15212                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15213                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15214                    int user = mSettings.mPreferredActivities.keyAt(i);
15215                    if (pir.dump(pw,
15216                            dumpState.getTitlePrinted()
15217                                ? "\nPreferred Activities User " + user + ":"
15218                                : "Preferred Activities User " + user + ":", "  ",
15219                            packageName, true, false)) {
15220                        dumpState.setTitlePrinted(true);
15221                    }
15222                }
15223            }
15224
15225            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
15226                pw.flush();
15227                FileOutputStream fout = new FileOutputStream(fd);
15228                BufferedOutputStream str = new BufferedOutputStream(fout);
15229                XmlSerializer serializer = new FastXmlSerializer();
15230                try {
15231                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
15232                    serializer.startDocument(null, true);
15233                    serializer.setFeature(
15234                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
15235                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
15236                    serializer.endDocument();
15237                    serializer.flush();
15238                } catch (IllegalArgumentException e) {
15239                    pw.println("Failed writing: " + e);
15240                } catch (IllegalStateException e) {
15241                    pw.println("Failed writing: " + e);
15242                } catch (IOException e) {
15243                    pw.println("Failed writing: " + e);
15244                }
15245            }
15246
15247            if (!checkin
15248                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15249                    && packageName == null) {
15250                pw.println();
15251                int count = mSettings.mPackages.size();
15252                if (count == 0) {
15253                    pw.println("No applications!");
15254                    pw.println();
15255                } else {
15256                    final String prefix = "  ";
15257                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15258                    if (allPackageSettings.size() == 0) {
15259                        pw.println("No domain preferred apps!");
15260                        pw.println();
15261                    } else {
15262                        pw.println("App verification status:");
15263                        pw.println();
15264                        count = 0;
15265                        for (PackageSetting ps : allPackageSettings) {
15266                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15267                            if (ivi == null || ivi.getPackageName() == null) continue;
15268                            pw.println(prefix + "Package: " + ivi.getPackageName());
15269                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15270                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15271                            pw.println();
15272                            count++;
15273                        }
15274                        if (count == 0) {
15275                            pw.println(prefix + "No app verification established.");
15276                            pw.println();
15277                        }
15278                        for (int userId : sUserManager.getUserIds()) {
15279                            pw.println("App linkages for user " + userId + ":");
15280                            pw.println();
15281                            count = 0;
15282                            for (PackageSetting ps : allPackageSettings) {
15283                                final long status = ps.getDomainVerificationStatusForUser(userId);
15284                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15285                                    continue;
15286                                }
15287                                pw.println(prefix + "Package: " + ps.name);
15288                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15289                                String statusStr = IntentFilterVerificationInfo.
15290                                        getStatusStringFromValue(status);
15291                                pw.println(prefix + "Status:  " + statusStr);
15292                                pw.println();
15293                                count++;
15294                            }
15295                            if (count == 0) {
15296                                pw.println(prefix + "No configured app linkages.");
15297                                pw.println();
15298                            }
15299                        }
15300                    }
15301                }
15302            }
15303
15304            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15305                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15306                if (packageName == null && permissionNames == null) {
15307                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15308                        if (iperm == 0) {
15309                            if (dumpState.onTitlePrinted())
15310                                pw.println();
15311                            pw.println("AppOp Permissions:");
15312                        }
15313                        pw.print("  AppOp Permission ");
15314                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15315                        pw.println(":");
15316                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15317                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15318                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15319                        }
15320                    }
15321                }
15322            }
15323
15324            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15325                boolean printedSomething = false;
15326                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15327                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15328                        continue;
15329                    }
15330                    if (!printedSomething) {
15331                        if (dumpState.onTitlePrinted())
15332                            pw.println();
15333                        pw.println("Registered ContentProviders:");
15334                        printedSomething = true;
15335                    }
15336                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15337                    pw.print("    "); pw.println(p.toString());
15338                }
15339                printedSomething = false;
15340                for (Map.Entry<String, PackageParser.Provider> entry :
15341                        mProvidersByAuthority.entrySet()) {
15342                    PackageParser.Provider p = entry.getValue();
15343                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15344                        continue;
15345                    }
15346                    if (!printedSomething) {
15347                        if (dumpState.onTitlePrinted())
15348                            pw.println();
15349                        pw.println("ContentProvider Authorities:");
15350                        printedSomething = true;
15351                    }
15352                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15353                    pw.print("    "); pw.println(p.toString());
15354                    if (p.info != null && p.info.applicationInfo != null) {
15355                        final String appInfo = p.info.applicationInfo.toString();
15356                        pw.print("      applicationInfo="); pw.println(appInfo);
15357                    }
15358                }
15359            }
15360
15361            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15362                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15363            }
15364
15365            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15366                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15367            }
15368
15369            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15370                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15371            }
15372
15373            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15374                // XXX should handle packageName != null by dumping only install data that
15375                // the given package is involved with.
15376                if (dumpState.onTitlePrinted()) pw.println();
15377                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15378            }
15379
15380            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15381                if (dumpState.onTitlePrinted()) pw.println();
15382                mSettings.dumpReadMessagesLPr(pw, dumpState);
15383
15384                pw.println();
15385                pw.println("Package warning messages:");
15386                BufferedReader in = null;
15387                String line = null;
15388                try {
15389                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15390                    while ((line = in.readLine()) != null) {
15391                        if (line.contains("ignored: updated version")) continue;
15392                        pw.println(line);
15393                    }
15394                } catch (IOException ignored) {
15395                } finally {
15396                    IoUtils.closeQuietly(in);
15397                }
15398            }
15399
15400            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15401                BufferedReader in = null;
15402                String line = null;
15403                try {
15404                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15405                    while ((line = in.readLine()) != null) {
15406                        if (line.contains("ignored: updated version")) continue;
15407                        pw.print("msg,");
15408                        pw.println(line);
15409                    }
15410                } catch (IOException ignored) {
15411                } finally {
15412                    IoUtils.closeQuietly(in);
15413                }
15414            }
15415        }
15416    }
15417
15418    private String dumpDomainString(String packageName) {
15419        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15420        List<IntentFilter> filters = getAllIntentFilters(packageName);
15421
15422        ArraySet<String> result = new ArraySet<>();
15423        if (iviList.size() > 0) {
15424            for (IntentFilterVerificationInfo ivi : iviList) {
15425                for (String host : ivi.getDomains()) {
15426                    result.add(host);
15427                }
15428            }
15429        }
15430        if (filters != null && filters.size() > 0) {
15431            for (IntentFilter filter : filters) {
15432                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
15433                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15434                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
15435                    result.addAll(filter.getHostsList());
15436                }
15437            }
15438        }
15439
15440        StringBuilder sb = new StringBuilder(result.size() * 16);
15441        for (String domain : result) {
15442            if (sb.length() > 0) sb.append(" ");
15443            sb.append(domain);
15444        }
15445        return sb.toString();
15446    }
15447
15448    // ------- apps on sdcard specific code -------
15449    static final boolean DEBUG_SD_INSTALL = false;
15450
15451    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15452
15453    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15454
15455    private boolean mMediaMounted = false;
15456
15457    static String getEncryptKey() {
15458        try {
15459            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15460                    SD_ENCRYPTION_KEYSTORE_NAME);
15461            if (sdEncKey == null) {
15462                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15463                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15464                if (sdEncKey == null) {
15465                    Slog.e(TAG, "Failed to create encryption keys");
15466                    return null;
15467                }
15468            }
15469            return sdEncKey;
15470        } catch (NoSuchAlgorithmException nsae) {
15471            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15472            return null;
15473        } catch (IOException ioe) {
15474            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15475            return null;
15476        }
15477    }
15478
15479    /*
15480     * Update media status on PackageManager.
15481     */
15482    @Override
15483    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15484        int callingUid = Binder.getCallingUid();
15485        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15486            throw new SecurityException("Media status can only be updated by the system");
15487        }
15488        // reader; this apparently protects mMediaMounted, but should probably
15489        // be a different lock in that case.
15490        synchronized (mPackages) {
15491            Log.i(TAG, "Updating external media status from "
15492                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15493                    + (mediaStatus ? "mounted" : "unmounted"));
15494            if (DEBUG_SD_INSTALL)
15495                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15496                        + ", mMediaMounted=" + mMediaMounted);
15497            if (mediaStatus == mMediaMounted) {
15498                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15499                        : 0, -1);
15500                mHandler.sendMessage(msg);
15501                return;
15502            }
15503            mMediaMounted = mediaStatus;
15504        }
15505        // Queue up an async operation since the package installation may take a
15506        // little while.
15507        mHandler.post(new Runnable() {
15508            public void run() {
15509                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15510            }
15511        });
15512    }
15513
15514    /**
15515     * Called by MountService when the initial ASECs to scan are available.
15516     * Should block until all the ASEC containers are finished being scanned.
15517     */
15518    public void scanAvailableAsecs() {
15519        updateExternalMediaStatusInner(true, false, false);
15520        if (mShouldRestoreconData) {
15521            SELinuxMMAC.setRestoreconDone();
15522            mShouldRestoreconData = false;
15523        }
15524    }
15525
15526    /*
15527     * Collect information of applications on external media, map them against
15528     * existing containers and update information based on current mount status.
15529     * Please note that we always have to report status if reportStatus has been
15530     * set to true especially when unloading packages.
15531     */
15532    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15533            boolean externalStorage) {
15534        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15535        int[] uidArr = EmptyArray.INT;
15536
15537        final String[] list = PackageHelper.getSecureContainerList();
15538        if (ArrayUtils.isEmpty(list)) {
15539            Log.i(TAG, "No secure containers found");
15540        } else {
15541            // Process list of secure containers and categorize them
15542            // as active or stale based on their package internal state.
15543
15544            // reader
15545            synchronized (mPackages) {
15546                for (String cid : list) {
15547                    // Leave stages untouched for now; installer service owns them
15548                    if (PackageInstallerService.isStageName(cid)) continue;
15549
15550                    if (DEBUG_SD_INSTALL)
15551                        Log.i(TAG, "Processing container " + cid);
15552                    String pkgName = getAsecPackageName(cid);
15553                    if (pkgName == null) {
15554                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15555                        continue;
15556                    }
15557                    if (DEBUG_SD_INSTALL)
15558                        Log.i(TAG, "Looking for pkg : " + pkgName);
15559
15560                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15561                    if (ps == null) {
15562                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15563                        continue;
15564                    }
15565
15566                    /*
15567                     * Skip packages that are not external if we're unmounting
15568                     * external storage.
15569                     */
15570                    if (externalStorage && !isMounted && !isExternal(ps)) {
15571                        continue;
15572                    }
15573
15574                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15575                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15576                    // The package status is changed only if the code path
15577                    // matches between settings and the container id.
15578                    if (ps.codePathString != null
15579                            && ps.codePathString.startsWith(args.getCodePath())) {
15580                        if (DEBUG_SD_INSTALL) {
15581                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15582                                    + " at code path: " + ps.codePathString);
15583                        }
15584
15585                        // We do have a valid package installed on sdcard
15586                        processCids.put(args, ps.codePathString);
15587                        final int uid = ps.appId;
15588                        if (uid != -1) {
15589                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15590                        }
15591                    } else {
15592                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15593                                + ps.codePathString);
15594                    }
15595                }
15596            }
15597
15598            Arrays.sort(uidArr);
15599        }
15600
15601        // Process packages with valid entries.
15602        if (isMounted) {
15603            if (DEBUG_SD_INSTALL)
15604                Log.i(TAG, "Loading packages");
15605            loadMediaPackages(processCids, uidArr, externalStorage);
15606            startCleaningPackages();
15607            mInstallerService.onSecureContainersAvailable();
15608        } else {
15609            if (DEBUG_SD_INSTALL)
15610                Log.i(TAG, "Unloading packages");
15611            unloadMediaPackages(processCids, uidArr, reportStatus);
15612        }
15613    }
15614
15615    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15616            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15617        final int size = infos.size();
15618        final String[] packageNames = new String[size];
15619        final int[] packageUids = new int[size];
15620        for (int i = 0; i < size; i++) {
15621            final ApplicationInfo info = infos.get(i);
15622            packageNames[i] = info.packageName;
15623            packageUids[i] = info.uid;
15624        }
15625        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15626                finishedReceiver);
15627    }
15628
15629    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15630            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15631        sendResourcesChangedBroadcast(mediaStatus, replacing,
15632                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15633    }
15634
15635    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15636            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15637        int size = pkgList.length;
15638        if (size > 0) {
15639            // Send broadcasts here
15640            Bundle extras = new Bundle();
15641            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15642            if (uidArr != null) {
15643                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15644            }
15645            if (replacing) {
15646                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15647            }
15648            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15649                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15650            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15651        }
15652    }
15653
15654   /*
15655     * Look at potentially valid container ids from processCids If package
15656     * information doesn't match the one on record or package scanning fails,
15657     * the cid is added to list of removeCids. We currently don't delete stale
15658     * containers.
15659     */
15660    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
15661            boolean externalStorage) {
15662        ArrayList<String> pkgList = new ArrayList<String>();
15663        Set<AsecInstallArgs> keys = processCids.keySet();
15664
15665        for (AsecInstallArgs args : keys) {
15666            String codePath = processCids.get(args);
15667            if (DEBUG_SD_INSTALL)
15668                Log.i(TAG, "Loading container : " + args.cid);
15669            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15670            try {
15671                // Make sure there are no container errors first.
15672                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15673                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15674                            + " when installing from sdcard");
15675                    continue;
15676                }
15677                // Check code path here.
15678                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15679                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15680                            + " does not match one in settings " + codePath);
15681                    continue;
15682                }
15683                // Parse package
15684                int parseFlags = mDefParseFlags;
15685                if (args.isExternalAsec()) {
15686                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15687                }
15688                if (args.isFwdLocked()) {
15689                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15690                }
15691
15692                synchronized (mInstallLock) {
15693                    PackageParser.Package pkg = null;
15694                    try {
15695                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
15696                    } catch (PackageManagerException e) {
15697                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15698                    }
15699                    // Scan the package
15700                    if (pkg != null) {
15701                        /*
15702                         * TODO why is the lock being held? doPostInstall is
15703                         * called in other places without the lock. This needs
15704                         * to be straightened out.
15705                         */
15706                        // writer
15707                        synchronized (mPackages) {
15708                            retCode = PackageManager.INSTALL_SUCCEEDED;
15709                            pkgList.add(pkg.packageName);
15710                            // Post process args
15711                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15712                                    pkg.applicationInfo.uid);
15713                        }
15714                    } else {
15715                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15716                    }
15717                }
15718
15719            } finally {
15720                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15721                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15722                }
15723            }
15724        }
15725        // writer
15726        synchronized (mPackages) {
15727            // If the platform SDK has changed since the last time we booted,
15728            // we need to re-grant app permission to catch any new ones that
15729            // appear. This is really a hack, and means that apps can in some
15730            // cases get permissions that the user didn't initially explicitly
15731            // allow... it would be nice to have some better way to handle
15732            // this situation.
15733            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
15734                    : mSettings.getInternalVersion();
15735            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
15736                    : StorageManager.UUID_PRIVATE_INTERNAL;
15737
15738            int updateFlags = UPDATE_PERMISSIONS_ALL;
15739            if (ver.sdkVersion != mSdkVersion) {
15740                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15741                        + mSdkVersion + "; regranting permissions for external");
15742                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15743            }
15744            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
15745
15746            // Yay, everything is now upgraded
15747            ver.forceCurrent();
15748
15749            // can downgrade to reader
15750            // Persist settings
15751            mSettings.writeLPr();
15752        }
15753        // Send a broadcast to let everyone know we are done processing
15754        if (pkgList.size() > 0) {
15755            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15756        }
15757    }
15758
15759   /*
15760     * Utility method to unload a list of specified containers
15761     */
15762    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15763        // Just unmount all valid containers.
15764        for (AsecInstallArgs arg : cidArgs) {
15765            synchronized (mInstallLock) {
15766                arg.doPostDeleteLI(false);
15767           }
15768       }
15769   }
15770
15771    /*
15772     * Unload packages mounted on external media. This involves deleting package
15773     * data from internal structures, sending broadcasts about diabled packages,
15774     * gc'ing to free up references, unmounting all secure containers
15775     * corresponding to packages on external media, and posting a
15776     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15777     * that we always have to post this message if status has been requested no
15778     * matter what.
15779     */
15780    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15781            final boolean reportStatus) {
15782        if (DEBUG_SD_INSTALL)
15783            Log.i(TAG, "unloading media packages");
15784        ArrayList<String> pkgList = new ArrayList<String>();
15785        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15786        final Set<AsecInstallArgs> keys = processCids.keySet();
15787        for (AsecInstallArgs args : keys) {
15788            String pkgName = args.getPackageName();
15789            if (DEBUG_SD_INSTALL)
15790                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15791            // Delete package internally
15792            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15793            synchronized (mInstallLock) {
15794                boolean res = deletePackageLI(pkgName, null, false, null, null,
15795                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15796                if (res) {
15797                    pkgList.add(pkgName);
15798                } else {
15799                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15800                    failedList.add(args);
15801                }
15802            }
15803        }
15804
15805        // reader
15806        synchronized (mPackages) {
15807            // We didn't update the settings after removing each package;
15808            // write them now for all packages.
15809            mSettings.writeLPr();
15810        }
15811
15812        // We have to absolutely send UPDATED_MEDIA_STATUS only
15813        // after confirming that all the receivers processed the ordered
15814        // broadcast when packages get disabled, force a gc to clean things up.
15815        // and unload all the containers.
15816        if (pkgList.size() > 0) {
15817            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15818                    new IIntentReceiver.Stub() {
15819                public void performReceive(Intent intent, int resultCode, String data,
15820                        Bundle extras, boolean ordered, boolean sticky,
15821                        int sendingUser) throws RemoteException {
15822                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15823                            reportStatus ? 1 : 0, 1, keys);
15824                    mHandler.sendMessage(msg);
15825                }
15826            });
15827        } else {
15828            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15829                    keys);
15830            mHandler.sendMessage(msg);
15831        }
15832    }
15833
15834    private void loadPrivatePackages(final VolumeInfo vol) {
15835        mHandler.post(new Runnable() {
15836            @Override
15837            public void run() {
15838                loadPrivatePackagesInner(vol);
15839            }
15840        });
15841    }
15842
15843    private void loadPrivatePackagesInner(VolumeInfo vol) {
15844        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15845        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15846
15847        final VersionInfo ver;
15848        final List<PackageSetting> packages;
15849        synchronized (mPackages) {
15850            ver = mSettings.findOrCreateVersion(vol.fsUuid);
15851            packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15852        }
15853
15854        for (PackageSetting ps : packages) {
15855            synchronized (mInstallLock) {
15856                final PackageParser.Package pkg;
15857                try {
15858                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
15859                    loaded.add(pkg.applicationInfo);
15860                } catch (PackageManagerException e) {
15861                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15862                }
15863
15864                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
15865                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
15866                }
15867            }
15868        }
15869
15870        synchronized (mPackages) {
15871            int updateFlags = UPDATE_PERMISSIONS_ALL;
15872            if (ver.sdkVersion != mSdkVersion) {
15873                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15874                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
15875                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15876            }
15877            updatePermissionsLPw(null, null, vol.fsUuid, updateFlags);
15878
15879            // Yay, everything is now upgraded
15880            ver.forceCurrent();
15881
15882            mSettings.writeLPr();
15883        }
15884
15885        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15886        sendResourcesChangedBroadcast(true, false, loaded, null);
15887    }
15888
15889    private void unloadPrivatePackages(final VolumeInfo vol) {
15890        mHandler.post(new Runnable() {
15891            @Override
15892            public void run() {
15893                unloadPrivatePackagesInner(vol);
15894            }
15895        });
15896    }
15897
15898    private void unloadPrivatePackagesInner(VolumeInfo vol) {
15899        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15900        synchronized (mInstallLock) {
15901        synchronized (mPackages) {
15902            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15903            for (PackageSetting ps : packages) {
15904                if (ps.pkg == null) continue;
15905
15906                final ApplicationInfo info = ps.pkg.applicationInfo;
15907                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15908                if (deletePackageLI(ps.name, null, false, null, null,
15909                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15910                    unloaded.add(info);
15911                } else {
15912                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15913                }
15914            }
15915
15916            mSettings.writeLPr();
15917        }
15918        }
15919
15920        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15921        sendResourcesChangedBroadcast(false, false, unloaded, null);
15922    }
15923
15924    /**
15925     * Examine all users present on given mounted volume, and destroy data
15926     * belonging to users that are no longer valid, or whose user ID has been
15927     * recycled.
15928     */
15929    private void reconcileUsers(String volumeUuid) {
15930        final File[] files = FileUtils
15931                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
15932        for (File file : files) {
15933            if (!file.isDirectory()) continue;
15934
15935            final int userId;
15936            final UserInfo info;
15937            try {
15938                userId = Integer.parseInt(file.getName());
15939                info = sUserManager.getUserInfo(userId);
15940            } catch (NumberFormatException e) {
15941                Slog.w(TAG, "Invalid user directory " + file);
15942                continue;
15943            }
15944
15945            boolean destroyUser = false;
15946            if (info == null) {
15947                logCriticalInfo(Log.WARN, "Destroying user directory " + file
15948                        + " because no matching user was found");
15949                destroyUser = true;
15950            } else {
15951                try {
15952                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
15953                } catch (IOException e) {
15954                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
15955                            + " because we failed to enforce serial number: " + e);
15956                    destroyUser = true;
15957                }
15958            }
15959
15960            if (destroyUser) {
15961                synchronized (mInstallLock) {
15962                    mInstaller.removeUserDataDirs(volumeUuid, userId);
15963                }
15964            }
15965        }
15966
15967        final StorageManager sm = mContext.getSystemService(StorageManager.class);
15968        final UserManager um = mContext.getSystemService(UserManager.class);
15969        for (UserInfo user : um.getUsers()) {
15970            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
15971            if (userDir.exists()) continue;
15972
15973            try {
15974                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber);
15975                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
15976            } catch (IOException e) {
15977                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
15978            }
15979        }
15980    }
15981
15982    /**
15983     * Examine all apps present on given mounted volume, and destroy apps that
15984     * aren't expected, either due to uninstallation or reinstallation on
15985     * another volume.
15986     */
15987    private void reconcileApps(String volumeUuid) {
15988        final File[] files = FileUtils
15989                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
15990        for (File file : files) {
15991            final boolean isPackage = (isApkFile(file) || file.isDirectory())
15992                    && !PackageInstallerService.isStageName(file.getName());
15993            if (!isPackage) {
15994                // Ignore entries which are not packages
15995                continue;
15996            }
15997
15998            boolean destroyApp = false;
15999            String packageName = null;
16000            try {
16001                final PackageLite pkg = PackageParser.parsePackageLite(file,
16002                        PackageParser.PARSE_MUST_BE_APK);
16003                packageName = pkg.packageName;
16004
16005                synchronized (mPackages) {
16006                    final PackageSetting ps = mSettings.mPackages.get(packageName);
16007                    if (ps == null) {
16008                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
16009                                + volumeUuid + " because we found no install record");
16010                        destroyApp = true;
16011                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
16012                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
16013                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
16014                        destroyApp = true;
16015                    }
16016                }
16017
16018            } catch (PackageParserException e) {
16019                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
16020                destroyApp = true;
16021            }
16022
16023            if (destroyApp) {
16024                synchronized (mInstallLock) {
16025                    if (packageName != null) {
16026                        removeDataDirsLI(volumeUuid, packageName);
16027                    }
16028                    if (file.isDirectory()) {
16029                        mInstaller.rmPackageDir(file.getAbsolutePath());
16030                    } else {
16031                        file.delete();
16032                    }
16033                }
16034            }
16035        }
16036    }
16037
16038    private void unfreezePackage(String packageName) {
16039        synchronized (mPackages) {
16040            final PackageSetting ps = mSettings.mPackages.get(packageName);
16041            if (ps != null) {
16042                ps.frozen = false;
16043            }
16044        }
16045    }
16046
16047    @Override
16048    public int movePackage(final String packageName, final String volumeUuid) {
16049        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16050
16051        final int moveId = mNextMoveId.getAndIncrement();
16052        mHandler.post(new Runnable() {
16053            @Override
16054            public void run() {
16055                try {
16056                    movePackageInternal(packageName, volumeUuid, moveId);
16057                } catch (PackageManagerException e) {
16058                    Slog.w(TAG, "Failed to move " + packageName, e);
16059                    mMoveCallbacks.notifyStatusChanged(moveId,
16060                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16061                }
16062            }
16063        });
16064        return moveId;
16065    }
16066
16067    private void movePackageInternal(final String packageName, final String volumeUuid,
16068            final int moveId) throws PackageManagerException {
16069        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
16070        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16071        final PackageManager pm = mContext.getPackageManager();
16072
16073        final boolean currentAsec;
16074        final String currentVolumeUuid;
16075        final File codeFile;
16076        final String installerPackageName;
16077        final String packageAbiOverride;
16078        final int appId;
16079        final String seinfo;
16080        final String label;
16081
16082        // reader
16083        synchronized (mPackages) {
16084            final PackageParser.Package pkg = mPackages.get(packageName);
16085            final PackageSetting ps = mSettings.mPackages.get(packageName);
16086            if (pkg == null || ps == null) {
16087                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
16088            }
16089
16090            if (pkg.applicationInfo.isSystemApp()) {
16091                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
16092                        "Cannot move system application");
16093            }
16094
16095            if (pkg.applicationInfo.isExternalAsec()) {
16096                currentAsec = true;
16097                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
16098            } else if (pkg.applicationInfo.isForwardLocked()) {
16099                currentAsec = true;
16100                currentVolumeUuid = "forward_locked";
16101            } else {
16102                currentAsec = false;
16103                currentVolumeUuid = ps.volumeUuid;
16104
16105                final File probe = new File(pkg.codePath);
16106                final File probeOat = new File(probe, "oat");
16107                if (!probe.isDirectory() || !probeOat.isDirectory()) {
16108                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16109                            "Move only supported for modern cluster style installs");
16110                }
16111            }
16112
16113            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
16114                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16115                        "Package already moved to " + volumeUuid);
16116            }
16117
16118            if (ps.frozen) {
16119                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
16120                        "Failed to move already frozen package");
16121            }
16122            ps.frozen = true;
16123
16124            codeFile = new File(pkg.codePath);
16125            installerPackageName = ps.installerPackageName;
16126            packageAbiOverride = ps.cpuAbiOverrideString;
16127            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16128            seinfo = pkg.applicationInfo.seinfo;
16129            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
16130        }
16131
16132        // Now that we're guarded by frozen state, kill app during move
16133        final long token = Binder.clearCallingIdentity();
16134        try {
16135            killApplication(packageName, appId, "move pkg");
16136        } finally {
16137            Binder.restoreCallingIdentity(token);
16138        }
16139
16140        final Bundle extras = new Bundle();
16141        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
16142        extras.putString(Intent.EXTRA_TITLE, label);
16143        mMoveCallbacks.notifyCreated(moveId, extras);
16144
16145        int installFlags;
16146        final boolean moveCompleteApp;
16147        final File measurePath;
16148
16149        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
16150            installFlags = INSTALL_INTERNAL;
16151            moveCompleteApp = !currentAsec;
16152            measurePath = Environment.getDataAppDirectory(volumeUuid);
16153        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
16154            installFlags = INSTALL_EXTERNAL;
16155            moveCompleteApp = false;
16156            measurePath = storage.getPrimaryPhysicalVolume().getPath();
16157        } else {
16158            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
16159            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
16160                    || !volume.isMountedWritable()) {
16161                unfreezePackage(packageName);
16162                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16163                        "Move location not mounted private volume");
16164            }
16165
16166            Preconditions.checkState(!currentAsec);
16167
16168            installFlags = INSTALL_INTERNAL;
16169            moveCompleteApp = true;
16170            measurePath = Environment.getDataAppDirectory(volumeUuid);
16171        }
16172
16173        final PackageStats stats = new PackageStats(null, -1);
16174        synchronized (mInstaller) {
16175            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
16176                unfreezePackage(packageName);
16177                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16178                        "Failed to measure package size");
16179            }
16180        }
16181
16182        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
16183                + stats.dataSize);
16184
16185        final long startFreeBytes = measurePath.getFreeSpace();
16186        final long sizeBytes;
16187        if (moveCompleteApp) {
16188            sizeBytes = stats.codeSize + stats.dataSize;
16189        } else {
16190            sizeBytes = stats.codeSize;
16191        }
16192
16193        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
16194            unfreezePackage(packageName);
16195            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16196                    "Not enough free space to move");
16197        }
16198
16199        mMoveCallbacks.notifyStatusChanged(moveId, 10);
16200
16201        final CountDownLatch installedLatch = new CountDownLatch(1);
16202        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
16203            @Override
16204            public void onUserActionRequired(Intent intent) throws RemoteException {
16205                throw new IllegalStateException();
16206            }
16207
16208            @Override
16209            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
16210                    Bundle extras) throws RemoteException {
16211                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
16212                        + PackageManager.installStatusToString(returnCode, msg));
16213
16214                installedLatch.countDown();
16215
16216                // Regardless of success or failure of the move operation,
16217                // always unfreeze the package
16218                unfreezePackage(packageName);
16219
16220                final int status = PackageManager.installStatusToPublicStatus(returnCode);
16221                switch (status) {
16222                    case PackageInstaller.STATUS_SUCCESS:
16223                        mMoveCallbacks.notifyStatusChanged(moveId,
16224                                PackageManager.MOVE_SUCCEEDED);
16225                        break;
16226                    case PackageInstaller.STATUS_FAILURE_STORAGE:
16227                        mMoveCallbacks.notifyStatusChanged(moveId,
16228                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
16229                        break;
16230                    default:
16231                        mMoveCallbacks.notifyStatusChanged(moveId,
16232                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16233                        break;
16234                }
16235            }
16236        };
16237
16238        final MoveInfo move;
16239        if (moveCompleteApp) {
16240            // Kick off a thread to report progress estimates
16241            new Thread() {
16242                @Override
16243                public void run() {
16244                    while (true) {
16245                        try {
16246                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
16247                                break;
16248                            }
16249                        } catch (InterruptedException ignored) {
16250                        }
16251
16252                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
16253                        final int progress = 10 + (int) MathUtils.constrain(
16254                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
16255                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
16256                    }
16257                }
16258            }.start();
16259
16260            final String dataAppName = codeFile.getName();
16261            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
16262                    dataAppName, appId, seinfo);
16263        } else {
16264            move = null;
16265        }
16266
16267        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
16268
16269        final Message msg = mHandler.obtainMessage(INIT_COPY);
16270        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
16271        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
16272                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
16273        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
16274        msg.obj = params;
16275
16276        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
16277                System.identityHashCode(msg.obj));
16278        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
16279                System.identityHashCode(msg.obj));
16280
16281        mHandler.sendMessage(msg);
16282    }
16283
16284    @Override
16285    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
16286        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16287
16288        final int realMoveId = mNextMoveId.getAndIncrement();
16289        final Bundle extras = new Bundle();
16290        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
16291        mMoveCallbacks.notifyCreated(realMoveId, extras);
16292
16293        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
16294            @Override
16295            public void onCreated(int moveId, Bundle extras) {
16296                // Ignored
16297            }
16298
16299            @Override
16300            public void onStatusChanged(int moveId, int status, long estMillis) {
16301                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16302            }
16303        };
16304
16305        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16306        storage.setPrimaryStorageUuid(volumeUuid, callback);
16307        return realMoveId;
16308    }
16309
16310    @Override
16311    public int getMoveStatus(int moveId) {
16312        mContext.enforceCallingOrSelfPermission(
16313                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16314        return mMoveCallbacks.mLastStatus.get(moveId);
16315    }
16316
16317    @Override
16318    public void registerMoveCallback(IPackageMoveObserver callback) {
16319        mContext.enforceCallingOrSelfPermission(
16320                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16321        mMoveCallbacks.register(callback);
16322    }
16323
16324    @Override
16325    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16326        mContext.enforceCallingOrSelfPermission(
16327                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16328        mMoveCallbacks.unregister(callback);
16329    }
16330
16331    @Override
16332    public boolean setInstallLocation(int loc) {
16333        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16334                null);
16335        if (getInstallLocation() == loc) {
16336            return true;
16337        }
16338        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16339                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16340            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16341                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16342            return true;
16343        }
16344        return false;
16345   }
16346
16347    @Override
16348    public int getInstallLocation() {
16349        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16350                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16351                PackageHelper.APP_INSTALL_AUTO);
16352    }
16353
16354    /** Called by UserManagerService */
16355    void cleanUpUser(UserManagerService userManager, int userHandle) {
16356        synchronized (mPackages) {
16357            mDirtyUsers.remove(userHandle);
16358            mUserNeedsBadging.delete(userHandle);
16359            mSettings.removeUserLPw(userHandle);
16360            mPendingBroadcasts.remove(userHandle);
16361        }
16362        synchronized (mInstallLock) {
16363            if (mInstaller != null) {
16364                final StorageManager storage = mContext.getSystemService(StorageManager.class);
16365                for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16366                    final String volumeUuid = vol.getFsUuid();
16367                    if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16368                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16369                }
16370            }
16371            synchronized (mPackages) {
16372                removeUnusedPackagesLILPw(userManager, userHandle);
16373            }
16374        }
16375    }
16376
16377    /**
16378     * We're removing userHandle and would like to remove any downloaded packages
16379     * that are no longer in use by any other user.
16380     * @param userHandle the user being removed
16381     */
16382    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16383        final boolean DEBUG_CLEAN_APKS = false;
16384        int [] users = userManager.getUserIds();
16385        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16386        while (psit.hasNext()) {
16387            PackageSetting ps = psit.next();
16388            if (ps.pkg == null) {
16389                continue;
16390            }
16391            final String packageName = ps.pkg.packageName;
16392            // Skip over if system app
16393            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16394                continue;
16395            }
16396            if (DEBUG_CLEAN_APKS) {
16397                Slog.i(TAG, "Checking package " + packageName);
16398            }
16399            boolean keep = false;
16400            for (int i = 0; i < users.length; i++) {
16401                if (users[i] != userHandle && ps.getInstalled(users[i])) {
16402                    keep = true;
16403                    if (DEBUG_CLEAN_APKS) {
16404                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
16405                                + users[i]);
16406                    }
16407                    break;
16408                }
16409            }
16410            if (!keep) {
16411                if (DEBUG_CLEAN_APKS) {
16412                    Slog.i(TAG, "  Removing package " + packageName);
16413                }
16414                mHandler.post(new Runnable() {
16415                    public void run() {
16416                        deletePackageX(packageName, userHandle, 0);
16417                    } //end run
16418                });
16419            }
16420        }
16421    }
16422
16423    /** Called by UserManagerService */
16424    void createNewUser(int userHandle) {
16425        if (mInstaller != null) {
16426            synchronized (mInstallLock) {
16427                synchronized (mPackages) {
16428                    mInstaller.createUserConfig(userHandle);
16429                    mSettings.createNewUserLILPw(this, mInstaller, userHandle);
16430                }
16431            }
16432            synchronized (mPackages) {
16433                applyFactoryDefaultBrowserLPw(userHandle);
16434                primeDomainVerificationsLPw(userHandle);
16435            }
16436        }
16437    }
16438
16439    void newUserCreated(final int userHandle) {
16440        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
16441    }
16442
16443    @Override
16444    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
16445        mContext.enforceCallingOrSelfPermission(
16446                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16447                "Only package verification agents can read the verifier device identity");
16448
16449        synchronized (mPackages) {
16450            return mSettings.getVerifierDeviceIdentityLPw();
16451        }
16452    }
16453
16454    @Override
16455    public void setPermissionEnforced(String permission, boolean enforced) {
16456        // TODO: Now that we no longer change GID for storage, this should to away.
16457        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
16458                "setPermissionEnforced");
16459        if (READ_EXTERNAL_STORAGE.equals(permission)) {
16460            synchronized (mPackages) {
16461                if (mSettings.mReadExternalStorageEnforced == null
16462                        || mSettings.mReadExternalStorageEnforced != enforced) {
16463                    mSettings.mReadExternalStorageEnforced = enforced;
16464                    mSettings.writeLPr();
16465                }
16466            }
16467            // kill any non-foreground processes so we restart them and
16468            // grant/revoke the GID.
16469            final IActivityManager am = ActivityManagerNative.getDefault();
16470            if (am != null) {
16471                final long token = Binder.clearCallingIdentity();
16472                try {
16473                    am.killProcessesBelowForeground("setPermissionEnforcement");
16474                } catch (RemoteException e) {
16475                } finally {
16476                    Binder.restoreCallingIdentity(token);
16477                }
16478            }
16479        } else {
16480            throw new IllegalArgumentException("No selective enforcement for " + permission);
16481        }
16482    }
16483
16484    @Override
16485    @Deprecated
16486    public boolean isPermissionEnforced(String permission) {
16487        return true;
16488    }
16489
16490    @Override
16491    public boolean isStorageLow() {
16492        final long token = Binder.clearCallingIdentity();
16493        try {
16494            final DeviceStorageMonitorInternal
16495                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16496            if (dsm != null) {
16497                return dsm.isMemoryLow();
16498            } else {
16499                return false;
16500            }
16501        } finally {
16502            Binder.restoreCallingIdentity(token);
16503        }
16504    }
16505
16506    @Override
16507    public IPackageInstaller getPackageInstaller() {
16508        return mInstallerService;
16509    }
16510
16511    private boolean userNeedsBadging(int userId) {
16512        int index = mUserNeedsBadging.indexOfKey(userId);
16513        if (index < 0) {
16514            final UserInfo userInfo;
16515            final long token = Binder.clearCallingIdentity();
16516            try {
16517                userInfo = sUserManager.getUserInfo(userId);
16518            } finally {
16519                Binder.restoreCallingIdentity(token);
16520            }
16521            final boolean b;
16522            if (userInfo != null && userInfo.isManagedProfile()) {
16523                b = true;
16524            } else {
16525                b = false;
16526            }
16527            mUserNeedsBadging.put(userId, b);
16528            return b;
16529        }
16530        return mUserNeedsBadging.valueAt(index);
16531    }
16532
16533    @Override
16534    public KeySet getKeySetByAlias(String packageName, String alias) {
16535        if (packageName == null || alias == null) {
16536            return null;
16537        }
16538        synchronized(mPackages) {
16539            final PackageParser.Package pkg = mPackages.get(packageName);
16540            if (pkg == null) {
16541                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16542                throw new IllegalArgumentException("Unknown package: " + packageName);
16543            }
16544            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16545            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16546        }
16547    }
16548
16549    @Override
16550    public KeySet getSigningKeySet(String packageName) {
16551        if (packageName == null) {
16552            return null;
16553        }
16554        synchronized(mPackages) {
16555            final PackageParser.Package pkg = mPackages.get(packageName);
16556            if (pkg == null) {
16557                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16558                throw new IllegalArgumentException("Unknown package: " + packageName);
16559            }
16560            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16561                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16562                throw new SecurityException("May not access signing KeySet of other apps.");
16563            }
16564            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16565            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16566        }
16567    }
16568
16569    @Override
16570    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16571        if (packageName == null || ks == null) {
16572            return false;
16573        }
16574        synchronized(mPackages) {
16575            final PackageParser.Package pkg = mPackages.get(packageName);
16576            if (pkg == null) {
16577                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16578                throw new IllegalArgumentException("Unknown package: " + packageName);
16579            }
16580            IBinder ksh = ks.getToken();
16581            if (ksh instanceof KeySetHandle) {
16582                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16583                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16584            }
16585            return false;
16586        }
16587    }
16588
16589    @Override
16590    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16591        if (packageName == null || ks == null) {
16592            return false;
16593        }
16594        synchronized(mPackages) {
16595            final PackageParser.Package pkg = mPackages.get(packageName);
16596            if (pkg == null) {
16597                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16598                throw new IllegalArgumentException("Unknown package: " + packageName);
16599            }
16600            IBinder ksh = ks.getToken();
16601            if (ksh instanceof KeySetHandle) {
16602                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16603                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16604            }
16605            return false;
16606        }
16607    }
16608
16609    /**
16610     * Check and throw if the given before/after packages would be considered a
16611     * downgrade.
16612     */
16613    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16614            throws PackageManagerException {
16615        if (after.versionCode < before.mVersionCode) {
16616            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16617                    "Update version code " + after.versionCode + " is older than current "
16618                    + before.mVersionCode);
16619        } else if (after.versionCode == before.mVersionCode) {
16620            if (after.baseRevisionCode < before.baseRevisionCode) {
16621                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16622                        "Update base revision code " + after.baseRevisionCode
16623                        + " is older than current " + before.baseRevisionCode);
16624            }
16625
16626            if (!ArrayUtils.isEmpty(after.splitNames)) {
16627                for (int i = 0; i < after.splitNames.length; i++) {
16628                    final String splitName = after.splitNames[i];
16629                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16630                    if (j != -1) {
16631                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16632                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16633                                    "Update split " + splitName + " revision code "
16634                                    + after.splitRevisionCodes[i] + " is older than current "
16635                                    + before.splitRevisionCodes[j]);
16636                        }
16637                    }
16638                }
16639            }
16640        }
16641    }
16642
16643    private static class MoveCallbacks extends Handler {
16644        private static final int MSG_CREATED = 1;
16645        private static final int MSG_STATUS_CHANGED = 2;
16646
16647        private final RemoteCallbackList<IPackageMoveObserver>
16648                mCallbacks = new RemoteCallbackList<>();
16649
16650        private final SparseIntArray mLastStatus = new SparseIntArray();
16651
16652        public MoveCallbacks(Looper looper) {
16653            super(looper);
16654        }
16655
16656        public void register(IPackageMoveObserver callback) {
16657            mCallbacks.register(callback);
16658        }
16659
16660        public void unregister(IPackageMoveObserver callback) {
16661            mCallbacks.unregister(callback);
16662        }
16663
16664        @Override
16665        public void handleMessage(Message msg) {
16666            final SomeArgs args = (SomeArgs) msg.obj;
16667            final int n = mCallbacks.beginBroadcast();
16668            for (int i = 0; i < n; i++) {
16669                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16670                try {
16671                    invokeCallback(callback, msg.what, args);
16672                } catch (RemoteException ignored) {
16673                }
16674            }
16675            mCallbacks.finishBroadcast();
16676            args.recycle();
16677        }
16678
16679        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16680                throws RemoteException {
16681            switch (what) {
16682                case MSG_CREATED: {
16683                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16684                    break;
16685                }
16686                case MSG_STATUS_CHANGED: {
16687                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16688                    break;
16689                }
16690            }
16691        }
16692
16693        private void notifyCreated(int moveId, Bundle extras) {
16694            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16695
16696            final SomeArgs args = SomeArgs.obtain();
16697            args.argi1 = moveId;
16698            args.arg2 = extras;
16699            obtainMessage(MSG_CREATED, args).sendToTarget();
16700        }
16701
16702        private void notifyStatusChanged(int moveId, int status) {
16703            notifyStatusChanged(moveId, status, -1);
16704        }
16705
16706        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16707            Slog.v(TAG, "Move " + moveId + " status " + status);
16708
16709            final SomeArgs args = SomeArgs.obtain();
16710            args.argi1 = moveId;
16711            args.argi2 = status;
16712            args.arg3 = estMillis;
16713            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16714
16715            synchronized (mLastStatus) {
16716                mLastStatus.put(moveId, status);
16717            }
16718        }
16719    }
16720
16721    private final class OnPermissionChangeListeners extends Handler {
16722        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16723
16724        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16725                new RemoteCallbackList<>();
16726
16727        public OnPermissionChangeListeners(Looper looper) {
16728            super(looper);
16729        }
16730
16731        @Override
16732        public void handleMessage(Message msg) {
16733            switch (msg.what) {
16734                case MSG_ON_PERMISSIONS_CHANGED: {
16735                    final int uid = msg.arg1;
16736                    handleOnPermissionsChanged(uid);
16737                } break;
16738            }
16739        }
16740
16741        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16742            mPermissionListeners.register(listener);
16743
16744        }
16745
16746        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16747            mPermissionListeners.unregister(listener);
16748        }
16749
16750        public void onPermissionsChanged(int uid) {
16751            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16752                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16753            }
16754        }
16755
16756        private void handleOnPermissionsChanged(int uid) {
16757            final int count = mPermissionListeners.beginBroadcast();
16758            try {
16759                for (int i = 0; i < count; i++) {
16760                    IOnPermissionsChangeListener callback = mPermissionListeners
16761                            .getBroadcastItem(i);
16762                    try {
16763                        callback.onPermissionsChanged(uid);
16764                    } catch (RemoteException e) {
16765                        Log.e(TAG, "Permission listener is dead", e);
16766                    }
16767                }
16768            } finally {
16769                mPermissionListeners.finishBroadcast();
16770            }
16771        }
16772    }
16773
16774    private class PackageManagerInternalImpl extends PackageManagerInternal {
16775        @Override
16776        public void setLocationPackagesProvider(PackagesProvider provider) {
16777            synchronized (mPackages) {
16778                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16779            }
16780        }
16781
16782        @Override
16783        public void setImePackagesProvider(PackagesProvider provider) {
16784            synchronized (mPackages) {
16785                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16786            }
16787        }
16788
16789        @Override
16790        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16791            synchronized (mPackages) {
16792                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16793            }
16794        }
16795
16796        @Override
16797        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16798            synchronized (mPackages) {
16799                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16800            }
16801        }
16802
16803        @Override
16804        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16805            synchronized (mPackages) {
16806                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16807            }
16808        }
16809
16810        @Override
16811        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
16812            synchronized (mPackages) {
16813                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
16814            }
16815        }
16816
16817        @Override
16818        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16819            synchronized (mPackages) {
16820                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
16821            }
16822        }
16823
16824        @Override
16825        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16826            synchronized (mPackages) {
16827                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16828                        packageName, userId);
16829            }
16830        }
16831
16832        @Override
16833        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16834            synchronized (mPackages) {
16835                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16836                        packageName, userId);
16837            }
16838        }
16839        @Override
16840        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
16841            synchronized (mPackages) {
16842                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
16843                        packageName, userId);
16844            }
16845        }
16846    }
16847
16848    @Override
16849    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16850        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16851        synchronized (mPackages) {
16852            final long identity = Binder.clearCallingIdentity();
16853            try {
16854                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16855                        packageNames, userId);
16856            } finally {
16857                Binder.restoreCallingIdentity(identity);
16858            }
16859        }
16860    }
16861
16862    private static void enforceSystemOrPhoneCaller(String tag) {
16863        int callingUid = Binder.getCallingUid();
16864        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16865            throw new SecurityException(
16866                    "Cannot call " + tag + " from UID " + callingUid);
16867        }
16868    }
16869}
16870