PackageManagerService.java revision 9dacbf6fd4b602f3abe9b1a347690d474c54f9a7
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.MATCH_ALL;
60import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
61import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
62import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
63import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
64import static android.content.pm.PackageManager.PERMISSION_DENIED;
65import static android.content.pm.PackageManager.PERMISSION_GRANTED;
66import static android.content.pm.PackageParser.isApkFile;
67import static android.os.Process.PACKAGE_INFO_GID;
68import static android.os.Process.SYSTEM_UID;
69import static android.system.OsConstants.O_CREAT;
70import static android.system.OsConstants.O_RDWR;
71import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
72import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
73import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
74import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
75import static com.android.internal.util.ArrayUtils.appendInt;
76import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
77import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
78import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
79import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
80import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
81import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
82import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
83import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
84
85import android.Manifest;
86import android.app.ActivityManager;
87import android.app.ActivityManagerNative;
88import android.app.AppGlobals;
89import android.app.IActivityManager;
90import android.app.admin.IDevicePolicyManager;
91import android.app.backup.IBackupManager;
92import android.app.usage.UsageStats;
93import android.app.usage.UsageStatsManager;
94import android.content.BroadcastReceiver;
95import android.content.ComponentName;
96import android.content.Context;
97import android.content.IIntentReceiver;
98import android.content.Intent;
99import android.content.IntentFilter;
100import android.content.IntentSender;
101import android.content.IntentSender.SendIntentException;
102import android.content.ServiceConnection;
103import android.content.pm.ActivityInfo;
104import android.content.pm.ApplicationInfo;
105import android.content.pm.FeatureInfo;
106import android.content.pm.IOnPermissionsChangeListener;
107import android.content.pm.IPackageDataObserver;
108import android.content.pm.IPackageDeleteObserver;
109import android.content.pm.IPackageDeleteObserver2;
110import android.content.pm.IPackageInstallObserver2;
111import android.content.pm.IPackageInstaller;
112import android.content.pm.IPackageManager;
113import android.content.pm.IPackageMoveObserver;
114import android.content.pm.IPackageStatsObserver;
115import android.content.pm.InstrumentationInfo;
116import android.content.pm.IntentFilterVerificationInfo;
117import android.content.pm.KeySet;
118import android.content.pm.ManifestDigest;
119import android.content.pm.PackageCleanItem;
120import android.content.pm.PackageInfo;
121import android.content.pm.PackageInfoLite;
122import android.content.pm.PackageInstaller;
123import android.content.pm.PackageManager;
124import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
125import android.content.pm.PackageManagerInternal;
126import android.content.pm.PackageParser;
127import android.content.pm.PackageParser.ActivityIntentInfo;
128import android.content.pm.PackageParser.PackageLite;
129import android.content.pm.PackageParser.PackageParserException;
130import android.content.pm.PackageStats;
131import android.content.pm.PackageUserState;
132import android.content.pm.ParceledListSlice;
133import android.content.pm.PermissionGroupInfo;
134import android.content.pm.PermissionInfo;
135import android.content.pm.ProviderInfo;
136import android.content.pm.ResolveInfo;
137import android.content.pm.ServiceInfo;
138import android.content.pm.Signature;
139import android.content.pm.UserInfo;
140import android.content.pm.VerificationParams;
141import android.content.pm.VerifierDeviceIdentity;
142import android.content.pm.VerifierInfo;
143import android.content.res.Resources;
144import android.hardware.display.DisplayManager;
145import android.net.Uri;
146import android.os.Debug;
147import android.os.Binder;
148import android.os.Build;
149import android.os.Bundle;
150import android.os.Environment;
151import android.os.Environment.UserEnvironment;
152import android.os.FileUtils;
153import android.os.Handler;
154import android.os.IBinder;
155import android.os.Looper;
156import android.os.Message;
157import android.os.Parcel;
158import android.os.ParcelFileDescriptor;
159import android.os.Process;
160import android.os.RemoteCallbackList;
161import android.os.RemoteException;
162import android.os.SELinux;
163import android.os.ServiceManager;
164import android.os.SystemClock;
165import android.os.SystemProperties;
166import android.os.UserHandle;
167import android.os.UserManager;
168import android.os.storage.IMountService;
169import android.os.storage.MountServiceInternal;
170import android.os.storage.StorageEventListener;
171import android.os.storage.StorageManager;
172import android.os.storage.VolumeInfo;
173import android.os.storage.VolumeRecord;
174import android.security.KeyStore;
175import android.security.SystemKeyStore;
176import android.system.ErrnoException;
177import android.system.Os;
178import android.system.StructStat;
179import android.text.TextUtils;
180import android.text.format.DateUtils;
181import android.util.ArrayMap;
182import android.util.ArraySet;
183import android.util.AtomicFile;
184import android.util.DisplayMetrics;
185import android.util.EventLog;
186import android.util.ExceptionUtils;
187import android.util.Log;
188import android.util.LogPrinter;
189import android.util.MathUtils;
190import android.util.PrintStreamPrinter;
191import android.util.Slog;
192import android.util.SparseArray;
193import android.util.SparseBooleanArray;
194import android.util.SparseIntArray;
195import android.util.Xml;
196import android.view.Display;
197
198import dalvik.system.DexFile;
199import dalvik.system.VMRuntime;
200
201import libcore.io.IoUtils;
202import libcore.util.EmptyArray;
203
204import com.android.internal.R;
205import com.android.internal.annotations.GuardedBy;
206import com.android.internal.app.IMediaContainerService;
207import com.android.internal.app.ResolverActivity;
208import com.android.internal.content.NativeLibraryHelper;
209import com.android.internal.content.PackageHelper;
210import com.android.internal.os.IParcelFileDescriptorFactory;
211import com.android.internal.os.SomeArgs;
212import com.android.internal.os.Zygote;
213import com.android.internal.util.ArrayUtils;
214import com.android.internal.util.FastPrintWriter;
215import com.android.internal.util.FastXmlSerializer;
216import com.android.internal.util.IndentingPrintWriter;
217import com.android.internal.util.Preconditions;
218import com.android.server.EventLogTags;
219import com.android.server.FgThread;
220import com.android.server.IntentResolver;
221import com.android.server.LocalServices;
222import com.android.server.ServiceThread;
223import com.android.server.SystemConfig;
224import com.android.server.Watchdog;
225import com.android.server.pm.PermissionsState.PermissionState;
226import com.android.server.pm.Settings.DatabaseVersion;
227import com.android.server.pm.Settings.VersionInfo;
228import com.android.server.storage.DeviceStorageMonitorInternal;
229
230import org.xmlpull.v1.XmlPullParser;
231import org.xmlpull.v1.XmlPullParserException;
232import org.xmlpull.v1.XmlSerializer;
233
234import java.io.BufferedInputStream;
235import java.io.BufferedOutputStream;
236import java.io.BufferedReader;
237import java.io.ByteArrayInputStream;
238import java.io.ByteArrayOutputStream;
239import java.io.File;
240import java.io.FileDescriptor;
241import java.io.FileNotFoundException;
242import java.io.FileOutputStream;
243import java.io.FileReader;
244import java.io.FilenameFilter;
245import java.io.IOException;
246import java.io.InputStream;
247import java.io.PrintWriter;
248import java.nio.charset.StandardCharsets;
249import java.security.NoSuchAlgorithmException;
250import java.security.PublicKey;
251import java.security.cert.CertificateEncodingException;
252import java.security.cert.CertificateException;
253import java.text.SimpleDateFormat;
254import java.util.ArrayList;
255import java.util.Arrays;
256import java.util.Collection;
257import java.util.Collections;
258import java.util.Comparator;
259import java.util.Date;
260import java.util.Iterator;
261import java.util.List;
262import java.util.Map;
263import java.util.Objects;
264import java.util.Set;
265import java.util.concurrent.CountDownLatch;
266import java.util.concurrent.TimeUnit;
267import java.util.concurrent.atomic.AtomicBoolean;
268import java.util.concurrent.atomic.AtomicInteger;
269import java.util.concurrent.atomic.AtomicLong;
270
271/**
272 * Keep track of all those .apks everywhere.
273 *
274 * This is very central to the platform's security; please run the unit
275 * tests whenever making modifications here:
276 *
277mmm frameworks/base/tests/AndroidTests
278adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
279adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
280 *
281 * {@hide}
282 */
283public class PackageManagerService extends IPackageManager.Stub {
284    static final String TAG = "PackageManager";
285    static final boolean DEBUG_SETTINGS = false;
286    static final boolean DEBUG_PREFERRED = false;
287    static final boolean DEBUG_UPGRADE = false;
288    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
289    private static final boolean DEBUG_BACKUP = false;
290    private static final boolean DEBUG_INSTALL = false;
291    private static final boolean DEBUG_REMOVE = false;
292    private static final boolean DEBUG_BROADCASTS = false;
293    private static final boolean DEBUG_SHOW_INFO = false;
294    private static final boolean DEBUG_PACKAGE_INFO = false;
295    private static final boolean DEBUG_INTENT_MATCHING = false;
296    private static final boolean DEBUG_PACKAGE_SCANNING = false;
297    private static final boolean DEBUG_VERIFY = false;
298    private static final boolean DEBUG_DEXOPT = false;
299    private static final boolean DEBUG_ABI_SELECTION = false;
300
301    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = Build.IS_DEBUGGABLE;
302
303    private static final int RADIO_UID = Process.PHONE_UID;
304    private static final int LOG_UID = Process.LOG_UID;
305    private static final int NFC_UID = Process.NFC_UID;
306    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
307    private static final int SHELL_UID = Process.SHELL_UID;
308
309    // Cap the size of permission trees that 3rd party apps can define
310    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
311
312    // Suffix used during package installation when copying/moving
313    // package apks to install directory.
314    private static final String INSTALL_PACKAGE_SUFFIX = "-";
315
316    static final int SCAN_NO_DEX = 1<<1;
317    static final int SCAN_FORCE_DEX = 1<<2;
318    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
319    static final int SCAN_NEW_INSTALL = 1<<4;
320    static final int SCAN_NO_PATHS = 1<<5;
321    static final int SCAN_UPDATE_TIME = 1<<6;
322    static final int SCAN_DEFER_DEX = 1<<7;
323    static final int SCAN_BOOTING = 1<<8;
324    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
325    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
326    static final int SCAN_REQUIRE_KNOWN = 1<<12;
327    static final int SCAN_MOVE = 1<<13;
328    static final int SCAN_INITIAL = 1<<14;
329
330    static final int REMOVE_CHATTY = 1<<16;
331
332    private static final int[] EMPTY_INT_ARRAY = new int[0];
333
334    /**
335     * Timeout (in milliseconds) after which the watchdog should declare that
336     * our handler thread is wedged.  The usual default for such things is one
337     * minute but we sometimes do very lengthy I/O operations on this thread,
338     * such as installing multi-gigabyte applications, so ours needs to be longer.
339     */
340    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
341
342    /**
343     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
344     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
345     * settings entry if available, otherwise we use the hardcoded default.  If it's been
346     * more than this long since the last fstrim, we force one during the boot sequence.
347     *
348     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
349     * one gets run at the next available charging+idle time.  This final mandatory
350     * no-fstrim check kicks in only of the other scheduling criteria is never met.
351     */
352    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
353
354    /**
355     * Whether verification is enabled by default.
356     */
357    private static final boolean DEFAULT_VERIFY_ENABLE = true;
358
359    /**
360     * The default maximum time to wait for the verification agent to return in
361     * milliseconds.
362     */
363    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
364
365    /**
366     * The default response for package verification timeout.
367     *
368     * This can be either PackageManager.VERIFICATION_ALLOW or
369     * PackageManager.VERIFICATION_REJECT.
370     */
371    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
372
373    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
374
375    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
376            DEFAULT_CONTAINER_PACKAGE,
377            "com.android.defcontainer.DefaultContainerService");
378
379    private static final String KILL_APP_REASON_GIDS_CHANGED =
380            "permission grant or revoke changed gids";
381
382    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
383            "permissions revoked";
384
385    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
386
387    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
388
389    /** Permission grant: not grant the permission. */
390    private static final int GRANT_DENIED = 1;
391
392    /** Permission grant: grant the permission as an install permission. */
393    private static final int GRANT_INSTALL = 2;
394
395    /** Permission grant: grant the permission as an install permission for a legacy app. */
396    private static final int GRANT_INSTALL_LEGACY = 3;
397
398    /** Permission grant: grant the permission as a runtime one. */
399    private static final int GRANT_RUNTIME = 4;
400
401    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
402    private static final int GRANT_UPGRADE = 5;
403
404    /** Canonical intent used to identify what counts as a "web browser" app */
405    private static final Intent sBrowserIntent;
406    static {
407        sBrowserIntent = new Intent();
408        sBrowserIntent.setAction(Intent.ACTION_VIEW);
409        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
410        sBrowserIntent.setData(Uri.parse("http:"));
411    }
412
413    final ServiceThread mHandlerThread;
414
415    final PackageHandler mHandler;
416
417    /**
418     * Messages for {@link #mHandler} that need to wait for system ready before
419     * being dispatched.
420     */
421    private ArrayList<Message> mPostSystemReadyMessages;
422
423    final int mSdkVersion = Build.VERSION.SDK_INT;
424
425    final Context mContext;
426    final boolean mFactoryTest;
427    final boolean mOnlyCore;
428    final boolean mLazyDexOpt;
429    final long mDexOptLRUThresholdInMills;
430    final DisplayMetrics mMetrics;
431    final int mDefParseFlags;
432    final String[] mSeparateProcesses;
433    final boolean mIsUpgrade;
434
435    // This is where all application persistent data goes.
436    final File mAppDataDir;
437
438    // This is where all application persistent data goes for secondary users.
439    final File mUserAppDataDir;
440
441    /** The location for ASEC container files on internal storage. */
442    final String mAsecInternalPath;
443
444    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
445    // LOCK HELD.  Can be called with mInstallLock held.
446    @GuardedBy("mInstallLock")
447    final Installer mInstaller;
448
449    /** Directory where installed third-party apps stored */
450    final File mAppInstallDir;
451
452    /**
453     * Directory to which applications installed internally have their
454     * 32 bit native libraries copied.
455     */
456    private File mAppLib32InstallDir;
457
458    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
459    // apps.
460    final File mDrmAppPrivateInstallDir;
461
462    // ----------------------------------------------------------------
463
464    // Lock for state used when installing and doing other long running
465    // operations.  Methods that must be called with this lock held have
466    // the suffix "LI".
467    final Object mInstallLock = new Object();
468
469    // ----------------------------------------------------------------
470
471    // Keys are String (package name), values are Package.  This also serves
472    // as the lock for the global state.  Methods that must be called with
473    // this lock held have the prefix "LP".
474    @GuardedBy("mPackages")
475    final ArrayMap<String, PackageParser.Package> mPackages =
476            new ArrayMap<String, PackageParser.Package>();
477
478    // Tracks available target package names -> overlay package paths.
479    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
480        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
481
482    /**
483     * Tracks new system packages [receiving in an OTA] that we expect to
484     * find updated user-installed versions. Keys are package name, values
485     * are package location.
486     */
487    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
488
489    final Settings mSettings;
490    boolean mRestoredSettings;
491
492    // System configuration read by SystemConfig.
493    final int[] mGlobalGids;
494    final SparseArray<ArraySet<String>> mSystemPermissions;
495    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
496
497    // If mac_permissions.xml was found for seinfo labeling.
498    boolean mFoundPolicyFile;
499
500    // If a recursive restorecon of /data/data/<pkg> is needed.
501    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
502
503    public static final class SharedLibraryEntry {
504        public final String path;
505        public final String apk;
506
507        SharedLibraryEntry(String _path, String _apk) {
508            path = _path;
509            apk = _apk;
510        }
511    }
512
513    // Currently known shared libraries.
514    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
515            new ArrayMap<String, SharedLibraryEntry>();
516
517    // All available activities, for your resolving pleasure.
518    final ActivityIntentResolver mActivities =
519            new ActivityIntentResolver();
520
521    // All available receivers, for your resolving pleasure.
522    final ActivityIntentResolver mReceivers =
523            new ActivityIntentResolver();
524
525    // All available services, for your resolving pleasure.
526    final ServiceIntentResolver mServices = new ServiceIntentResolver();
527
528    // All available providers, for your resolving pleasure.
529    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
530
531    // Mapping from provider base names (first directory in content URI codePath)
532    // to the provider information.
533    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
534            new ArrayMap<String, PackageParser.Provider>();
535
536    // Mapping from instrumentation class names to info about them.
537    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
538            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
539
540    // Mapping from permission names to info about them.
541    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
542            new ArrayMap<String, PackageParser.PermissionGroup>();
543
544    // Packages whose data we have transfered into another package, thus
545    // should no longer exist.
546    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
547
548    // Broadcast actions that are only available to the system.
549    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
550
551    /** List of packages waiting for verification. */
552    final SparseArray<PackageVerificationState> mPendingVerification
553            = new SparseArray<PackageVerificationState>();
554
555    /** Set of packages associated with each app op permission. */
556    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
557
558    final PackageInstallerService mInstallerService;
559
560    private final PackageDexOptimizer mPackageDexOptimizer;
561
562    private AtomicInteger mNextMoveId = new AtomicInteger();
563    private final MoveCallbacks mMoveCallbacks;
564
565    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
566
567    // Cache of users who need badging.
568    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
569
570    /** Token for keys in mPendingVerification. */
571    private int mPendingVerificationToken = 0;
572
573    volatile boolean mSystemReady;
574    volatile boolean mSafeMode;
575    volatile boolean mHasSystemUidErrors;
576
577    ApplicationInfo mAndroidApplication;
578    final ActivityInfo mResolveActivity = new ActivityInfo();
579    final ResolveInfo mResolveInfo = new ResolveInfo();
580    ComponentName mResolveComponentName;
581    PackageParser.Package mPlatformPackage;
582    ComponentName mCustomResolverComponentName;
583
584    boolean mResolverReplaced = false;
585
586    private final ComponentName mIntentFilterVerifierComponent;
587    private int mIntentFilterVerificationToken = 0;
588
589    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
590            = new SparseArray<IntentFilterVerificationState>();
591
592    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
593            new DefaultPermissionGrantPolicy(this);
594
595    private static class IFVerificationParams {
596        PackageParser.Package pkg;
597        boolean replacing;
598        int userId;
599        int verifierUid;
600
601        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
602                int _userId, int _verifierUid) {
603            pkg = _pkg;
604            replacing = _replacing;
605            userId = _userId;
606            replacing = _replacing;
607            verifierUid = _verifierUid;
608        }
609    }
610
611    private interface IntentFilterVerifier<T extends IntentFilter> {
612        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
613                                               T filter, String packageName);
614        void startVerifications(int userId);
615        void receiveVerificationResponse(int verificationId);
616    }
617
618    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
619        private Context mContext;
620        private ComponentName mIntentFilterVerifierComponent;
621        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
622
623        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
624            mContext = context;
625            mIntentFilterVerifierComponent = verifierComponent;
626        }
627
628        private String getDefaultScheme() {
629            return IntentFilter.SCHEME_HTTPS;
630        }
631
632        @Override
633        public void startVerifications(int userId) {
634            // Launch verifications requests
635            int count = mCurrentIntentFilterVerifications.size();
636            for (int n=0; n<count; n++) {
637                int verificationId = mCurrentIntentFilterVerifications.get(n);
638                final IntentFilterVerificationState ivs =
639                        mIntentFilterVerificationStates.get(verificationId);
640
641                String packageName = ivs.getPackageName();
642
643                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
644                final int filterCount = filters.size();
645                ArraySet<String> domainsSet = new ArraySet<>();
646                for (int m=0; m<filterCount; m++) {
647                    PackageParser.ActivityIntentInfo filter = filters.get(m);
648                    domainsSet.addAll(filter.getHostsList());
649                }
650                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
651                synchronized (mPackages) {
652                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
653                            packageName, domainsList) != null) {
654                        scheduleWriteSettingsLocked();
655                    }
656                }
657                sendVerificationRequest(userId, verificationId, ivs);
658            }
659            mCurrentIntentFilterVerifications.clear();
660        }
661
662        private void sendVerificationRequest(int userId, int verificationId,
663                IntentFilterVerificationState ivs) {
664
665            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
666            verificationIntent.putExtra(
667                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
668                    verificationId);
669            verificationIntent.putExtra(
670                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
671                    getDefaultScheme());
672            verificationIntent.putExtra(
673                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
674                    ivs.getHostsString());
675            verificationIntent.putExtra(
676                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
677                    ivs.getPackageName());
678            verificationIntent.setComponent(mIntentFilterVerifierComponent);
679            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
680
681            UserHandle user = new UserHandle(userId);
682            mContext.sendBroadcastAsUser(verificationIntent, user);
683            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
684                    "Sending IntentFilter verification broadcast");
685        }
686
687        public void receiveVerificationResponse(int verificationId) {
688            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
689
690            final boolean verified = ivs.isVerified();
691
692            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
693            final int count = filters.size();
694            if (DEBUG_DOMAIN_VERIFICATION) {
695                Slog.i(TAG, "Received verification response " + verificationId
696                        + " for " + count + " filters, verified=" + verified);
697            }
698            for (int n=0; n<count; n++) {
699                PackageParser.ActivityIntentInfo filter = filters.get(n);
700                filter.setVerified(verified);
701
702                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
703                        + " verified with result:" + verified + " and hosts:"
704                        + ivs.getHostsString());
705            }
706
707            mIntentFilterVerificationStates.remove(verificationId);
708
709            final String packageName = ivs.getPackageName();
710            IntentFilterVerificationInfo ivi = null;
711
712            synchronized (mPackages) {
713                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
714            }
715            if (ivi == null) {
716                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
717                        + verificationId + " packageName:" + packageName);
718                return;
719            }
720            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
721                    "Updating IntentFilterVerificationInfo for package " + packageName
722                            +" verificationId:" + verificationId);
723
724            synchronized (mPackages) {
725                if (verified) {
726                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
727                } else {
728                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
729                }
730                scheduleWriteSettingsLocked();
731
732                final int userId = ivs.getUserId();
733                if (userId != UserHandle.USER_ALL) {
734                    final int userStatus =
735                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
736
737                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
738                    boolean needUpdate = false;
739
740                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
741                    // already been set by the User thru the Disambiguation dialog
742                    switch (userStatus) {
743                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
744                            if (verified) {
745                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
746                            } else {
747                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
748                            }
749                            needUpdate = true;
750                            break;
751
752                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
753                            if (verified) {
754                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
755                                needUpdate = true;
756                            }
757                            break;
758
759                        default:
760                            // Nothing to do
761                    }
762
763                    if (needUpdate) {
764                        mSettings.updateIntentFilterVerificationStatusLPw(
765                                packageName, updatedStatus, userId);
766                        scheduleWritePackageRestrictionsLocked(userId);
767                    }
768                }
769            }
770        }
771
772        @Override
773        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
774                    ActivityIntentInfo filter, String packageName) {
775            if (!hasValidDomains(filter)) {
776                return false;
777            }
778            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
779            if (ivs == null) {
780                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
781                        packageName);
782            }
783            if (DEBUG_DOMAIN_VERIFICATION) {
784                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
785            }
786            ivs.addFilter(filter);
787            return true;
788        }
789
790        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
791                int userId, int verificationId, String packageName) {
792            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
793                    verifierUid, userId, packageName);
794            ivs.setPendingState();
795            synchronized (mPackages) {
796                mIntentFilterVerificationStates.append(verificationId, ivs);
797                mCurrentIntentFilterVerifications.add(verificationId);
798            }
799            return ivs;
800        }
801    }
802
803    private static boolean hasValidDomains(ActivityIntentInfo filter) {
804        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
805                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
806                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
807    }
808
809    private IntentFilterVerifier mIntentFilterVerifier;
810
811    // Set of pending broadcasts for aggregating enable/disable of components.
812    static class PendingPackageBroadcasts {
813        // for each user id, a map of <package name -> components within that package>
814        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
815
816        public PendingPackageBroadcasts() {
817            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
818        }
819
820        public ArrayList<String> get(int userId, String packageName) {
821            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
822            return packages.get(packageName);
823        }
824
825        public void put(int userId, String packageName, ArrayList<String> components) {
826            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
827            packages.put(packageName, components);
828        }
829
830        public void remove(int userId, String packageName) {
831            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
832            if (packages != null) {
833                packages.remove(packageName);
834            }
835        }
836
837        public void remove(int userId) {
838            mUidMap.remove(userId);
839        }
840
841        public int userIdCount() {
842            return mUidMap.size();
843        }
844
845        public int userIdAt(int n) {
846            return mUidMap.keyAt(n);
847        }
848
849        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
850            return mUidMap.get(userId);
851        }
852
853        public int size() {
854            // total number of pending broadcast entries across all userIds
855            int num = 0;
856            for (int i = 0; i< mUidMap.size(); i++) {
857                num += mUidMap.valueAt(i).size();
858            }
859            return num;
860        }
861
862        public void clear() {
863            mUidMap.clear();
864        }
865
866        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
867            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
868            if (map == null) {
869                map = new ArrayMap<String, ArrayList<String>>();
870                mUidMap.put(userId, map);
871            }
872            return map;
873        }
874    }
875    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
876
877    // Service Connection to remote media container service to copy
878    // package uri's from external media onto secure containers
879    // or internal storage.
880    private IMediaContainerService mContainerService = null;
881
882    static final int SEND_PENDING_BROADCAST = 1;
883    static final int MCS_BOUND = 3;
884    static final int END_COPY = 4;
885    static final int INIT_COPY = 5;
886    static final int MCS_UNBIND = 6;
887    static final int START_CLEANING_PACKAGE = 7;
888    static final int FIND_INSTALL_LOC = 8;
889    static final int POST_INSTALL = 9;
890    static final int MCS_RECONNECT = 10;
891    static final int MCS_GIVE_UP = 11;
892    static final int UPDATED_MEDIA_STATUS = 12;
893    static final int WRITE_SETTINGS = 13;
894    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
895    static final int PACKAGE_VERIFIED = 15;
896    static final int CHECK_PENDING_VERIFICATION = 16;
897    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
898    static final int INTENT_FILTER_VERIFIED = 18;
899
900    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
901
902    // Delay time in millisecs
903    static final int BROADCAST_DELAY = 10 * 1000;
904
905    static UserManagerService sUserManager;
906
907    // Stores a list of users whose package restrictions file needs to be updated
908    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
909
910    final private DefaultContainerConnection mDefContainerConn =
911            new DefaultContainerConnection();
912    class DefaultContainerConnection implements ServiceConnection {
913        public void onServiceConnected(ComponentName name, IBinder service) {
914            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
915            IMediaContainerService imcs =
916                IMediaContainerService.Stub.asInterface(service);
917            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
918        }
919
920        public void onServiceDisconnected(ComponentName name) {
921            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
922        }
923    }
924
925    // Recordkeeping of restore-after-install operations that are currently in flight
926    // between the Package Manager and the Backup Manager
927    class PostInstallData {
928        public InstallArgs args;
929        public PackageInstalledInfo res;
930
931        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
932            args = _a;
933            res = _r;
934        }
935    }
936
937    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
938    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
939
940    // XML tags for backup/restore of various bits of state
941    private static final String TAG_PREFERRED_BACKUP = "pa";
942    private static final String TAG_DEFAULT_APPS = "da";
943    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
944
945    final String mRequiredVerifierPackage;
946    final String mRequiredInstallerPackage;
947
948    private final PackageUsage mPackageUsage = new PackageUsage();
949
950    private class PackageUsage {
951        private static final int WRITE_INTERVAL
952            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
953
954        private final Object mFileLock = new Object();
955        private final AtomicLong mLastWritten = new AtomicLong(0);
956        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
957
958        private boolean mIsHistoricalPackageUsageAvailable = true;
959
960        boolean isHistoricalPackageUsageAvailable() {
961            return mIsHistoricalPackageUsageAvailable;
962        }
963
964        void write(boolean force) {
965            if (force) {
966                writeInternal();
967                return;
968            }
969            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
970                && !DEBUG_DEXOPT) {
971                return;
972            }
973            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
974                new Thread("PackageUsage_DiskWriter") {
975                    @Override
976                    public void run() {
977                        try {
978                            writeInternal();
979                        } finally {
980                            mBackgroundWriteRunning.set(false);
981                        }
982                    }
983                }.start();
984            }
985        }
986
987        private void writeInternal() {
988            synchronized (mPackages) {
989                synchronized (mFileLock) {
990                    AtomicFile file = getFile();
991                    FileOutputStream f = null;
992                    try {
993                        f = file.startWrite();
994                        BufferedOutputStream out = new BufferedOutputStream(f);
995                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
996                        StringBuilder sb = new StringBuilder();
997                        for (PackageParser.Package pkg : mPackages.values()) {
998                            if (pkg.mLastPackageUsageTimeInMills == 0) {
999                                continue;
1000                            }
1001                            sb.setLength(0);
1002                            sb.append(pkg.packageName);
1003                            sb.append(' ');
1004                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1005                            sb.append('\n');
1006                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1007                        }
1008                        out.flush();
1009                        file.finishWrite(f);
1010                    } catch (IOException e) {
1011                        if (f != null) {
1012                            file.failWrite(f);
1013                        }
1014                        Log.e(TAG, "Failed to write package usage times", e);
1015                    }
1016                }
1017            }
1018            mLastWritten.set(SystemClock.elapsedRealtime());
1019        }
1020
1021        void readLP() {
1022            synchronized (mFileLock) {
1023                AtomicFile file = getFile();
1024                BufferedInputStream in = null;
1025                try {
1026                    in = new BufferedInputStream(file.openRead());
1027                    StringBuffer sb = new StringBuffer();
1028                    while (true) {
1029                        String packageName = readToken(in, sb, ' ');
1030                        if (packageName == null) {
1031                            break;
1032                        }
1033                        String timeInMillisString = readToken(in, sb, '\n');
1034                        if (timeInMillisString == null) {
1035                            throw new IOException("Failed to find last usage time for package "
1036                                                  + packageName);
1037                        }
1038                        PackageParser.Package pkg = mPackages.get(packageName);
1039                        if (pkg == null) {
1040                            continue;
1041                        }
1042                        long timeInMillis;
1043                        try {
1044                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1045                        } catch (NumberFormatException e) {
1046                            throw new IOException("Failed to parse " + timeInMillisString
1047                                                  + " as a long.", e);
1048                        }
1049                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1050                    }
1051                } catch (FileNotFoundException expected) {
1052                    mIsHistoricalPackageUsageAvailable = false;
1053                } catch (IOException e) {
1054                    Log.w(TAG, "Failed to read package usage times", e);
1055                } finally {
1056                    IoUtils.closeQuietly(in);
1057                }
1058            }
1059            mLastWritten.set(SystemClock.elapsedRealtime());
1060        }
1061
1062        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1063                throws IOException {
1064            sb.setLength(0);
1065            while (true) {
1066                int ch = in.read();
1067                if (ch == -1) {
1068                    if (sb.length() == 0) {
1069                        return null;
1070                    }
1071                    throw new IOException("Unexpected EOF");
1072                }
1073                if (ch == endOfToken) {
1074                    return sb.toString();
1075                }
1076                sb.append((char)ch);
1077            }
1078        }
1079
1080        private AtomicFile getFile() {
1081            File dataDir = Environment.getDataDirectory();
1082            File systemDir = new File(dataDir, "system");
1083            File fname = new File(systemDir, "package-usage.list");
1084            return new AtomicFile(fname);
1085        }
1086    }
1087
1088    class PackageHandler extends Handler {
1089        private boolean mBound = false;
1090        final ArrayList<HandlerParams> mPendingInstalls =
1091            new ArrayList<HandlerParams>();
1092
1093        private boolean connectToService() {
1094            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1095                    " DefaultContainerService");
1096            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1097            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1098            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1099                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1100                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1101                mBound = true;
1102                return true;
1103            }
1104            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1105            return false;
1106        }
1107
1108        private void disconnectService() {
1109            mContainerService = null;
1110            mBound = false;
1111            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1112            mContext.unbindService(mDefContainerConn);
1113            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1114        }
1115
1116        PackageHandler(Looper looper) {
1117            super(looper);
1118        }
1119
1120        public void handleMessage(Message msg) {
1121            try {
1122                doHandleMessage(msg);
1123            } finally {
1124                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1125            }
1126        }
1127
1128        void doHandleMessage(Message msg) {
1129            switch (msg.what) {
1130                case INIT_COPY: {
1131                    HandlerParams params = (HandlerParams) msg.obj;
1132                    int idx = mPendingInstalls.size();
1133                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1134                    // If a bind was already initiated we dont really
1135                    // need to do anything. The pending install
1136                    // will be processed later on.
1137                    if (!mBound) {
1138                        // If this is the only one pending we might
1139                        // have to bind to the service again.
1140                        if (!connectToService()) {
1141                            Slog.e(TAG, "Failed to bind to media container service");
1142                            params.serviceError();
1143                            return;
1144                        } else {
1145                            // Once we bind to the service, the first
1146                            // pending request will be processed.
1147                            mPendingInstalls.add(idx, params);
1148                        }
1149                    } else {
1150                        mPendingInstalls.add(idx, params);
1151                        // Already bound to the service. Just make
1152                        // sure we trigger off processing the first request.
1153                        if (idx == 0) {
1154                            mHandler.sendEmptyMessage(MCS_BOUND);
1155                        }
1156                    }
1157                    break;
1158                }
1159                case MCS_BOUND: {
1160                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1161                    if (msg.obj != null) {
1162                        mContainerService = (IMediaContainerService) msg.obj;
1163                    }
1164                    if (mContainerService == null) {
1165                        if (!mBound) {
1166                            // Something seriously wrong since we are not bound and we are not
1167                            // waiting for connection. Bail out.
1168                            Slog.e(TAG, "Cannot bind to media container service");
1169                            for (HandlerParams params : mPendingInstalls) {
1170                                // Indicate service bind error
1171                                params.serviceError();
1172                            }
1173                            mPendingInstalls.clear();
1174                        } else {
1175                            Slog.w(TAG, "Waiting to connect to media container service");
1176                        }
1177                    } else if (mPendingInstalls.size() > 0) {
1178                        HandlerParams params = mPendingInstalls.get(0);
1179                        if (params != null) {
1180                            if (params.startCopy()) {
1181                                // We are done...  look for more work or to
1182                                // go idle.
1183                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1184                                        "Checking for more work or unbind...");
1185                                // Delete pending install
1186                                if (mPendingInstalls.size() > 0) {
1187                                    mPendingInstalls.remove(0);
1188                                }
1189                                if (mPendingInstalls.size() == 0) {
1190                                    if (mBound) {
1191                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1192                                                "Posting delayed MCS_UNBIND");
1193                                        removeMessages(MCS_UNBIND);
1194                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1195                                        // Unbind after a little delay, to avoid
1196                                        // continual thrashing.
1197                                        sendMessageDelayed(ubmsg, 10000);
1198                                    }
1199                                } else {
1200                                    // There are more pending requests in queue.
1201                                    // Just post MCS_BOUND message to trigger processing
1202                                    // of next pending install.
1203                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1204                                            "Posting MCS_BOUND for next work");
1205                                    mHandler.sendEmptyMessage(MCS_BOUND);
1206                                }
1207                            }
1208                        }
1209                    } else {
1210                        // Should never happen ideally.
1211                        Slog.w(TAG, "Empty queue");
1212                    }
1213                    break;
1214                }
1215                case MCS_RECONNECT: {
1216                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1217                    if (mPendingInstalls.size() > 0) {
1218                        if (mBound) {
1219                            disconnectService();
1220                        }
1221                        if (!connectToService()) {
1222                            Slog.e(TAG, "Failed to bind to media container service");
1223                            for (HandlerParams params : mPendingInstalls) {
1224                                // Indicate service bind error
1225                                params.serviceError();
1226                            }
1227                            mPendingInstalls.clear();
1228                        }
1229                    }
1230                    break;
1231                }
1232                case MCS_UNBIND: {
1233                    // If there is no actual work left, then time to unbind.
1234                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1235
1236                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1237                        if (mBound) {
1238                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1239
1240                            disconnectService();
1241                        }
1242                    } else if (mPendingInstalls.size() > 0) {
1243                        // There are more pending requests in queue.
1244                        // Just post MCS_BOUND message to trigger processing
1245                        // of next pending install.
1246                        mHandler.sendEmptyMessage(MCS_BOUND);
1247                    }
1248
1249                    break;
1250                }
1251                case MCS_GIVE_UP: {
1252                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1253                    mPendingInstalls.remove(0);
1254                    break;
1255                }
1256                case SEND_PENDING_BROADCAST: {
1257                    String packages[];
1258                    ArrayList<String> components[];
1259                    int size = 0;
1260                    int uids[];
1261                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1262                    synchronized (mPackages) {
1263                        if (mPendingBroadcasts == null) {
1264                            return;
1265                        }
1266                        size = mPendingBroadcasts.size();
1267                        if (size <= 0) {
1268                            // Nothing to be done. Just return
1269                            return;
1270                        }
1271                        packages = new String[size];
1272                        components = new ArrayList[size];
1273                        uids = new int[size];
1274                        int i = 0;  // filling out the above arrays
1275
1276                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1277                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1278                            Iterator<Map.Entry<String, ArrayList<String>>> it
1279                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1280                                            .entrySet().iterator();
1281                            while (it.hasNext() && i < size) {
1282                                Map.Entry<String, ArrayList<String>> ent = it.next();
1283                                packages[i] = ent.getKey();
1284                                components[i] = ent.getValue();
1285                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1286                                uids[i] = (ps != null)
1287                                        ? UserHandle.getUid(packageUserId, ps.appId)
1288                                        : -1;
1289                                i++;
1290                            }
1291                        }
1292                        size = i;
1293                        mPendingBroadcasts.clear();
1294                    }
1295                    // Send broadcasts
1296                    for (int i = 0; i < size; i++) {
1297                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1298                    }
1299                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1300                    break;
1301                }
1302                case START_CLEANING_PACKAGE: {
1303                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1304                    final String packageName = (String)msg.obj;
1305                    final int userId = msg.arg1;
1306                    final boolean andCode = msg.arg2 != 0;
1307                    synchronized (mPackages) {
1308                        if (userId == UserHandle.USER_ALL) {
1309                            int[] users = sUserManager.getUserIds();
1310                            for (int user : users) {
1311                                mSettings.addPackageToCleanLPw(
1312                                        new PackageCleanItem(user, packageName, andCode));
1313                            }
1314                        } else {
1315                            mSettings.addPackageToCleanLPw(
1316                                    new PackageCleanItem(userId, packageName, andCode));
1317                        }
1318                    }
1319                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1320                    startCleaningPackages();
1321                } break;
1322                case POST_INSTALL: {
1323                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1324                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1325                    mRunningInstalls.delete(msg.arg1);
1326                    boolean deleteOld = false;
1327
1328                    if (data != null) {
1329                        InstallArgs args = data.args;
1330                        PackageInstalledInfo res = data.res;
1331
1332                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1333                            final String packageName = res.pkg.applicationInfo.packageName;
1334                            res.removedInfo.sendBroadcast(false, true, false);
1335                            Bundle extras = new Bundle(1);
1336                            extras.putInt(Intent.EXTRA_UID, res.uid);
1337
1338                            // Now that we successfully installed the package, grant runtime
1339                            // permissions if requested before broadcasting the install.
1340                            if ((args.installFlags
1341                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1342                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1343                                        args.installGrantPermissions);
1344                            }
1345
1346                            // Determine the set of users who are adding this
1347                            // package for the first time vs. those who are seeing
1348                            // an update.
1349                            int[] firstUsers;
1350                            int[] updateUsers = new int[0];
1351                            if (res.origUsers == null || res.origUsers.length == 0) {
1352                                firstUsers = res.newUsers;
1353                            } else {
1354                                firstUsers = new int[0];
1355                                for (int i=0; i<res.newUsers.length; i++) {
1356                                    int user = res.newUsers[i];
1357                                    boolean isNew = true;
1358                                    for (int j=0; j<res.origUsers.length; j++) {
1359                                        if (res.origUsers[j] == user) {
1360                                            isNew = false;
1361                                            break;
1362                                        }
1363                                    }
1364                                    if (isNew) {
1365                                        int[] newFirst = new int[firstUsers.length+1];
1366                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1367                                                firstUsers.length);
1368                                        newFirst[firstUsers.length] = user;
1369                                        firstUsers = newFirst;
1370                                    } else {
1371                                        int[] newUpdate = new int[updateUsers.length+1];
1372                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1373                                                updateUsers.length);
1374                                        newUpdate[updateUsers.length] = user;
1375                                        updateUsers = newUpdate;
1376                                    }
1377                                }
1378                            }
1379                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1380                                    packageName, extras, null, null, firstUsers);
1381                            final boolean update = res.removedInfo.removedPackage != null;
1382                            if (update) {
1383                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1384                            }
1385                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1386                                    packageName, extras, null, null, updateUsers);
1387                            if (update) {
1388                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1389                                        packageName, extras, null, null, updateUsers);
1390                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1391                                        null, null, packageName, null, updateUsers);
1392
1393                                // treat asec-hosted packages like removable media on upgrade
1394                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1395                                    if (DEBUG_INSTALL) {
1396                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1397                                                + " is ASEC-hosted -> AVAILABLE");
1398                                    }
1399                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1400                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1401                                    pkgList.add(packageName);
1402                                    sendResourcesChangedBroadcast(true, true,
1403                                            pkgList,uidArray, null);
1404                                }
1405                            }
1406                            if (res.removedInfo.args != null) {
1407                                // Remove the replaced package's older resources safely now
1408                                deleteOld = true;
1409                            }
1410
1411                            // If this app is a browser and it's newly-installed for some
1412                            // users, clear any default-browser state in those users
1413                            if (firstUsers.length > 0) {
1414                                // the app's nature doesn't depend on the user, so we can just
1415                                // check its browser nature in any user and generalize.
1416                                if (packageIsBrowser(packageName, firstUsers[0])) {
1417                                    synchronized (mPackages) {
1418                                        for (int userId : firstUsers) {
1419                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1420                                        }
1421                                    }
1422                                }
1423                            }
1424                            // Log current value of "unknown sources" setting
1425                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1426                                getUnknownSourcesSettings());
1427                        }
1428                        // Force a gc to clear up things
1429                        Runtime.getRuntime().gc();
1430                        // We delete after a gc for applications  on sdcard.
1431                        if (deleteOld) {
1432                            synchronized (mInstallLock) {
1433                                res.removedInfo.args.doPostDeleteLI(true);
1434                            }
1435                        }
1436                        if (args.observer != null) {
1437                            try {
1438                                Bundle extras = extrasForInstallResult(res);
1439                                args.observer.onPackageInstalled(res.name, res.returnCode,
1440                                        res.returnMsg, extras);
1441                            } catch (RemoteException e) {
1442                                Slog.i(TAG, "Observer no longer exists.");
1443                            }
1444                        }
1445                    } else {
1446                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1447                    }
1448                } break;
1449                case UPDATED_MEDIA_STATUS: {
1450                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1451                    boolean reportStatus = msg.arg1 == 1;
1452                    boolean doGc = msg.arg2 == 1;
1453                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1454                    if (doGc) {
1455                        // Force a gc to clear up stale containers.
1456                        Runtime.getRuntime().gc();
1457                    }
1458                    if (msg.obj != null) {
1459                        @SuppressWarnings("unchecked")
1460                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1461                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1462                        // Unload containers
1463                        unloadAllContainers(args);
1464                    }
1465                    if (reportStatus) {
1466                        try {
1467                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1468                            PackageHelper.getMountService().finishMediaUpdate();
1469                        } catch (RemoteException e) {
1470                            Log.e(TAG, "MountService not running?");
1471                        }
1472                    }
1473                } break;
1474                case WRITE_SETTINGS: {
1475                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1476                    synchronized (mPackages) {
1477                        removeMessages(WRITE_SETTINGS);
1478                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1479                        mSettings.writeLPr();
1480                        mDirtyUsers.clear();
1481                    }
1482                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1483                } break;
1484                case WRITE_PACKAGE_RESTRICTIONS: {
1485                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1486                    synchronized (mPackages) {
1487                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1488                        for (int userId : mDirtyUsers) {
1489                            mSettings.writePackageRestrictionsLPr(userId);
1490                        }
1491                        mDirtyUsers.clear();
1492                    }
1493                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1494                } break;
1495                case CHECK_PENDING_VERIFICATION: {
1496                    final int verificationId = msg.arg1;
1497                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1498
1499                    if ((state != null) && !state.timeoutExtended()) {
1500                        final InstallArgs args = state.getInstallArgs();
1501                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1502
1503                        Slog.i(TAG, "Verification timed out for " + originUri);
1504                        mPendingVerification.remove(verificationId);
1505
1506                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1507
1508                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1509                            Slog.i(TAG, "Continuing with installation of " + originUri);
1510                            state.setVerifierResponse(Binder.getCallingUid(),
1511                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1512                            broadcastPackageVerified(verificationId, originUri,
1513                                    PackageManager.VERIFICATION_ALLOW,
1514                                    state.getInstallArgs().getUser());
1515                            try {
1516                                ret = args.copyApk(mContainerService, true);
1517                            } catch (RemoteException e) {
1518                                Slog.e(TAG, "Could not contact the ContainerService");
1519                            }
1520                        } else {
1521                            broadcastPackageVerified(verificationId, originUri,
1522                                    PackageManager.VERIFICATION_REJECT,
1523                                    state.getInstallArgs().getUser());
1524                        }
1525
1526                        processPendingInstall(args, ret);
1527                        mHandler.sendEmptyMessage(MCS_UNBIND);
1528                    }
1529                    break;
1530                }
1531                case PACKAGE_VERIFIED: {
1532                    final int verificationId = msg.arg1;
1533
1534                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1535                    if (state == null) {
1536                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1537                        break;
1538                    }
1539
1540                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1541
1542                    state.setVerifierResponse(response.callerUid, response.code);
1543
1544                    if (state.isVerificationComplete()) {
1545                        mPendingVerification.remove(verificationId);
1546
1547                        final InstallArgs args = state.getInstallArgs();
1548                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1549
1550                        int ret;
1551                        if (state.isInstallAllowed()) {
1552                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1553                            broadcastPackageVerified(verificationId, originUri,
1554                                    response.code, state.getInstallArgs().getUser());
1555                            try {
1556                                ret = args.copyApk(mContainerService, true);
1557                            } catch (RemoteException e) {
1558                                Slog.e(TAG, "Could not contact the ContainerService");
1559                            }
1560                        } else {
1561                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1562                        }
1563
1564                        processPendingInstall(args, ret);
1565
1566                        mHandler.sendEmptyMessage(MCS_UNBIND);
1567                    }
1568
1569                    break;
1570                }
1571                case START_INTENT_FILTER_VERIFICATIONS: {
1572                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1573                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1574                            params.replacing, params.pkg);
1575                    break;
1576                }
1577                case INTENT_FILTER_VERIFIED: {
1578                    final int verificationId = msg.arg1;
1579
1580                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1581                            verificationId);
1582                    if (state == null) {
1583                        Slog.w(TAG, "Invalid IntentFilter verification token "
1584                                + verificationId + " received");
1585                        break;
1586                    }
1587
1588                    final int userId = state.getUserId();
1589
1590                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1591                            "Processing IntentFilter verification with token:"
1592                            + verificationId + " and userId:" + userId);
1593
1594                    final IntentFilterVerificationResponse response =
1595                            (IntentFilterVerificationResponse) msg.obj;
1596
1597                    state.setVerifierResponse(response.callerUid, response.code);
1598
1599                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1600                            "IntentFilter verification with token:" + verificationId
1601                            + " and userId:" + userId
1602                            + " is settings verifier response with response code:"
1603                            + response.code);
1604
1605                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1606                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1607                                + response.getFailedDomainsString());
1608                    }
1609
1610                    if (state.isVerificationComplete()) {
1611                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1612                    } else {
1613                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1614                                "IntentFilter verification with token:" + verificationId
1615                                + " was not said to be complete");
1616                    }
1617
1618                    break;
1619                }
1620            }
1621        }
1622    }
1623
1624    private StorageEventListener mStorageListener = new StorageEventListener() {
1625        @Override
1626        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1627            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1628                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1629                    final String volumeUuid = vol.getFsUuid();
1630
1631                    // Clean up any users or apps that were removed or recreated
1632                    // while this volume was missing
1633                    reconcileUsers(volumeUuid);
1634                    reconcileApps(volumeUuid);
1635
1636                    // Clean up any install sessions that expired or were
1637                    // cancelled while this volume was missing
1638                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1639
1640                    loadPrivatePackages(vol);
1641
1642                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1643                    unloadPrivatePackages(vol);
1644                }
1645            }
1646
1647            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1648                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1649                    updateExternalMediaStatus(true, false);
1650                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1651                    updateExternalMediaStatus(false, false);
1652                }
1653            }
1654        }
1655
1656        @Override
1657        public void onVolumeForgotten(String fsUuid) {
1658            if (TextUtils.isEmpty(fsUuid)) {
1659                Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1660                return;
1661            }
1662
1663            // Remove any apps installed on the forgotten volume
1664            synchronized (mPackages) {
1665                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1666                for (PackageSetting ps : packages) {
1667                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1668                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1669                            UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS);
1670                }
1671
1672                mSettings.onVolumeForgotten(fsUuid);
1673                mSettings.writeLPr();
1674            }
1675        }
1676    };
1677
1678    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1679            String[] grantedPermissions) {
1680        if (userId >= UserHandle.USER_OWNER) {
1681            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1682        } else if (userId == UserHandle.USER_ALL) {
1683            final int[] userIds;
1684            synchronized (mPackages) {
1685                userIds = UserManagerService.getInstance().getUserIds();
1686            }
1687            for (int someUserId : userIds) {
1688                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1689            }
1690        }
1691
1692        // We could have touched GID membership, so flush out packages.list
1693        synchronized (mPackages) {
1694            mSettings.writePackageListLPr();
1695        }
1696    }
1697
1698    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1699            String[] grantedPermissions) {
1700        SettingBase sb = (SettingBase) pkg.mExtras;
1701        if (sb == null) {
1702            return;
1703        }
1704
1705        PermissionsState permissionsState = sb.getPermissionsState();
1706
1707        for (String permission : pkg.requestedPermissions) {
1708            BasePermission bp = mSettings.mPermissions.get(permission);
1709            if (bp != null && bp.isRuntime() && (grantedPermissions == null
1710                    || ArrayUtils.contains(grantedPermissions, permission))) {
1711                permissionsState.grantRuntimePermission(bp, userId);
1712            }
1713        }
1714    }
1715
1716    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1717        Bundle extras = null;
1718        switch (res.returnCode) {
1719            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1720                extras = new Bundle();
1721                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1722                        res.origPermission);
1723                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1724                        res.origPackage);
1725                break;
1726            }
1727            case PackageManager.INSTALL_SUCCEEDED: {
1728                extras = new Bundle();
1729                extras.putBoolean(Intent.EXTRA_REPLACING,
1730                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1731                break;
1732            }
1733        }
1734        return extras;
1735    }
1736
1737    void scheduleWriteSettingsLocked() {
1738        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1739            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1740        }
1741    }
1742
1743    void scheduleWritePackageRestrictionsLocked(int userId) {
1744        if (!sUserManager.exists(userId)) return;
1745        mDirtyUsers.add(userId);
1746        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1747            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1748        }
1749    }
1750
1751    public static PackageManagerService main(Context context, Installer installer,
1752            boolean factoryTest, boolean onlyCore) {
1753        PackageManagerService m = new PackageManagerService(context, installer,
1754                factoryTest, onlyCore);
1755        ServiceManager.addService("package", m);
1756        return m;
1757    }
1758
1759    static String[] splitString(String str, char sep) {
1760        int count = 1;
1761        int i = 0;
1762        while ((i=str.indexOf(sep, i)) >= 0) {
1763            count++;
1764            i++;
1765        }
1766
1767        String[] res = new String[count];
1768        i=0;
1769        count = 0;
1770        int lastI=0;
1771        while ((i=str.indexOf(sep, i)) >= 0) {
1772            res[count] = str.substring(lastI, i);
1773            count++;
1774            i++;
1775            lastI = i;
1776        }
1777        res[count] = str.substring(lastI, str.length());
1778        return res;
1779    }
1780
1781    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1782        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1783                Context.DISPLAY_SERVICE);
1784        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1785    }
1786
1787    public PackageManagerService(Context context, Installer installer,
1788            boolean factoryTest, boolean onlyCore) {
1789        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1790                SystemClock.uptimeMillis());
1791
1792        if (mSdkVersion <= 0) {
1793            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1794        }
1795
1796        mContext = context;
1797        mFactoryTest = factoryTest;
1798        mOnlyCore = onlyCore;
1799        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1800        mMetrics = new DisplayMetrics();
1801        mSettings = new Settings(mPackages);
1802        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1803                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1804        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1805                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1806        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1807                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1808        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1809                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1810        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1811                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1812        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1813                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1814
1815        // TODO: add a property to control this?
1816        long dexOptLRUThresholdInMinutes;
1817        if (mLazyDexOpt) {
1818            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1819        } else {
1820            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1821        }
1822        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1823
1824        String separateProcesses = SystemProperties.get("debug.separate_processes");
1825        if (separateProcesses != null && separateProcesses.length() > 0) {
1826            if ("*".equals(separateProcesses)) {
1827                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1828                mSeparateProcesses = null;
1829                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1830            } else {
1831                mDefParseFlags = 0;
1832                mSeparateProcesses = separateProcesses.split(",");
1833                Slog.w(TAG, "Running with debug.separate_processes: "
1834                        + separateProcesses);
1835            }
1836        } else {
1837            mDefParseFlags = 0;
1838            mSeparateProcesses = null;
1839        }
1840
1841        mInstaller = installer;
1842        mPackageDexOptimizer = new PackageDexOptimizer(this);
1843        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1844
1845        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1846                FgThread.get().getLooper());
1847
1848        getDefaultDisplayMetrics(context, mMetrics);
1849
1850        SystemConfig systemConfig = SystemConfig.getInstance();
1851        mGlobalGids = systemConfig.getGlobalGids();
1852        mSystemPermissions = systemConfig.getSystemPermissions();
1853        mAvailableFeatures = systemConfig.getAvailableFeatures();
1854
1855        synchronized (mInstallLock) {
1856        // writer
1857        synchronized (mPackages) {
1858            mHandlerThread = new ServiceThread(TAG,
1859                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1860            mHandlerThread.start();
1861            mHandler = new PackageHandler(mHandlerThread.getLooper());
1862            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1863
1864            File dataDir = Environment.getDataDirectory();
1865            mAppDataDir = new File(dataDir, "data");
1866            mAppInstallDir = new File(dataDir, "app");
1867            mAppLib32InstallDir = new File(dataDir, "app-lib");
1868            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1869            mUserAppDataDir = new File(dataDir, "user");
1870            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1871
1872            sUserManager = new UserManagerService(context, this,
1873                    mInstallLock, mPackages);
1874
1875            // Propagate permission configuration in to package manager.
1876            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1877                    = systemConfig.getPermissions();
1878            for (int i=0; i<permConfig.size(); i++) {
1879                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1880                BasePermission bp = mSettings.mPermissions.get(perm.name);
1881                if (bp == null) {
1882                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1883                    mSettings.mPermissions.put(perm.name, bp);
1884                }
1885                if (perm.gids != null) {
1886                    bp.setGids(perm.gids, perm.perUser);
1887                }
1888            }
1889
1890            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1891            for (int i=0; i<libConfig.size(); i++) {
1892                mSharedLibraries.put(libConfig.keyAt(i),
1893                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1894            }
1895
1896            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1897
1898            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1899                    mSdkVersion, mOnlyCore);
1900
1901            String customResolverActivity = Resources.getSystem().getString(
1902                    R.string.config_customResolverActivity);
1903            if (TextUtils.isEmpty(customResolverActivity)) {
1904                customResolverActivity = null;
1905            } else {
1906                mCustomResolverComponentName = ComponentName.unflattenFromString(
1907                        customResolverActivity);
1908            }
1909
1910            long startTime = SystemClock.uptimeMillis();
1911
1912            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1913                    startTime);
1914
1915            // Set flag to monitor and not change apk file paths when
1916            // scanning install directories.
1917            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
1918
1919            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1920
1921            /**
1922             * Add everything in the in the boot class path to the
1923             * list of process files because dexopt will have been run
1924             * if necessary during zygote startup.
1925             */
1926            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1927            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1928
1929            if (bootClassPath != null) {
1930                String[] bootClassPathElements = splitString(bootClassPath, ':');
1931                for (String element : bootClassPathElements) {
1932                    alreadyDexOpted.add(element);
1933                }
1934            } else {
1935                Slog.w(TAG, "No BOOTCLASSPATH found!");
1936            }
1937
1938            if (systemServerClassPath != null) {
1939                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1940                for (String element : systemServerClassPathElements) {
1941                    alreadyDexOpted.add(element);
1942                }
1943            } else {
1944                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1945            }
1946
1947            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1948            final String[] dexCodeInstructionSets =
1949                    getDexCodeInstructionSets(
1950                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1951
1952            /**
1953             * Ensure all external libraries have had dexopt run on them.
1954             */
1955            if (mSharedLibraries.size() > 0) {
1956                // NOTE: For now, we're compiling these system "shared libraries"
1957                // (and framework jars) into all available architectures. It's possible
1958                // to compile them only when we come across an app that uses them (there's
1959                // already logic for that in scanPackageLI) but that adds some complexity.
1960                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1961                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1962                        final String lib = libEntry.path;
1963                        if (lib == null) {
1964                            continue;
1965                        }
1966
1967                        try {
1968                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1969                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1970                                alreadyDexOpted.add(lib);
1971                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1972                            }
1973                        } catch (FileNotFoundException e) {
1974                            Slog.w(TAG, "Library not found: " + lib);
1975                        } catch (IOException e) {
1976                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1977                                    + e.getMessage());
1978                        }
1979                    }
1980                }
1981            }
1982
1983            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1984
1985            // Gross hack for now: we know this file doesn't contain any
1986            // code, so don't dexopt it to avoid the resulting log spew.
1987            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1988
1989            // Gross hack for now: we know this file is only part of
1990            // the boot class path for art, so don't dexopt it to
1991            // avoid the resulting log spew.
1992            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1993
1994            /**
1995             * There are a number of commands implemented in Java, which
1996             * we currently need to do the dexopt on so that they can be
1997             * run from a non-root shell.
1998             */
1999            String[] frameworkFiles = frameworkDir.list();
2000            if (frameworkFiles != null) {
2001                // TODO: We could compile these only for the most preferred ABI. We should
2002                // first double check that the dex files for these commands are not referenced
2003                // by other system apps.
2004                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2005                    for (int i=0; i<frameworkFiles.length; i++) {
2006                        File libPath = new File(frameworkDir, frameworkFiles[i]);
2007                        String path = libPath.getPath();
2008                        // Skip the file if we already did it.
2009                        if (alreadyDexOpted.contains(path)) {
2010                            continue;
2011                        }
2012                        // Skip the file if it is not a type we want to dexopt.
2013                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
2014                            continue;
2015                        }
2016                        try {
2017                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
2018                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2019                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
2020                            }
2021                        } catch (FileNotFoundException e) {
2022                            Slog.w(TAG, "Jar not found: " + path);
2023                        } catch (IOException e) {
2024                            Slog.w(TAG, "Exception reading jar: " + path, e);
2025                        }
2026                    }
2027                }
2028            }
2029
2030            // Collect vendor overlay packages.
2031            // (Do this before scanning any apps.)
2032            // For security and version matching reason, only consider
2033            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2034            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2035            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2036                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2037
2038            // Find base frameworks (resource packages without code).
2039            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2040                    | PackageParser.PARSE_IS_SYSTEM_DIR
2041                    | PackageParser.PARSE_IS_PRIVILEGED,
2042                    scanFlags | SCAN_NO_DEX, 0);
2043
2044            // Collected privileged system packages.
2045            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2046            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2047                    | PackageParser.PARSE_IS_SYSTEM_DIR
2048                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2049
2050            // Collect ordinary system packages.
2051            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2052            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2053                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2054
2055            // Collect all vendor packages.
2056            File vendorAppDir = new File("/vendor/app");
2057            try {
2058                vendorAppDir = vendorAppDir.getCanonicalFile();
2059            } catch (IOException e) {
2060                // failed to look up canonical path, continue with original one
2061            }
2062            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2063                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2064
2065            // Collect all OEM packages.
2066            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2067            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2068                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2069
2070            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2071            mInstaller.moveFiles();
2072
2073            // Prune any system packages that no longer exist.
2074            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2075            if (!mOnlyCore) {
2076                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2077                while (psit.hasNext()) {
2078                    PackageSetting ps = psit.next();
2079
2080                    /*
2081                     * If this is not a system app, it can't be a
2082                     * disable system app.
2083                     */
2084                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2085                        continue;
2086                    }
2087
2088                    /*
2089                     * If the package is scanned, it's not erased.
2090                     */
2091                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2092                    if (scannedPkg != null) {
2093                        /*
2094                         * If the system app is both scanned and in the
2095                         * disabled packages list, then it must have been
2096                         * added via OTA. Remove it from the currently
2097                         * scanned package so the previously user-installed
2098                         * application can be scanned.
2099                         */
2100                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2101                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2102                                    + ps.name + "; removing system app.  Last known codePath="
2103                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2104                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2105                                    + scannedPkg.mVersionCode);
2106                            removePackageLI(ps, true);
2107                            mExpectingBetter.put(ps.name, ps.codePath);
2108                        }
2109
2110                        continue;
2111                    }
2112
2113                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2114                        psit.remove();
2115                        logCriticalInfo(Log.WARN, "System package " + ps.name
2116                                + " no longer exists; wiping its data");
2117                        removeDataDirsLI(null, ps.name);
2118                    } else {
2119                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2120                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2121                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2122                        }
2123                    }
2124                }
2125            }
2126
2127            //look for any incomplete package installations
2128            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2129            //clean up list
2130            for(int i = 0; i < deletePkgsList.size(); i++) {
2131                //clean up here
2132                cleanupInstallFailedPackage(deletePkgsList.get(i));
2133            }
2134            //delete tmp files
2135            deleteTempPackageFiles();
2136
2137            // Remove any shared userIDs that have no associated packages
2138            mSettings.pruneSharedUsersLPw();
2139
2140            if (!mOnlyCore) {
2141                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2142                        SystemClock.uptimeMillis());
2143                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2144
2145                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2146                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2147
2148                /**
2149                 * Remove disable package settings for any updated system
2150                 * apps that were removed via an OTA. If they're not a
2151                 * previously-updated app, remove them completely.
2152                 * Otherwise, just revoke their system-level permissions.
2153                 */
2154                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2155                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2156                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2157
2158                    String msg;
2159                    if (deletedPkg == null) {
2160                        msg = "Updated system package " + deletedAppName
2161                                + " no longer exists; wiping its data";
2162                        removeDataDirsLI(null, deletedAppName);
2163                    } else {
2164                        msg = "Updated system app + " + deletedAppName
2165                                + " no longer present; removing system privileges for "
2166                                + deletedAppName;
2167
2168                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2169
2170                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2171                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2172                    }
2173                    logCriticalInfo(Log.WARN, msg);
2174                }
2175
2176                /**
2177                 * Make sure all system apps that we expected to appear on
2178                 * the userdata partition actually showed up. If they never
2179                 * appeared, crawl back and revive the system version.
2180                 */
2181                for (int i = 0; i < mExpectingBetter.size(); i++) {
2182                    final String packageName = mExpectingBetter.keyAt(i);
2183                    if (!mPackages.containsKey(packageName)) {
2184                        final File scanFile = mExpectingBetter.valueAt(i);
2185
2186                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2187                                + " but never showed up; reverting to system");
2188
2189                        final int reparseFlags;
2190                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2191                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2192                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2193                                    | PackageParser.PARSE_IS_PRIVILEGED;
2194                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2195                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2196                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2197                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2198                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2199                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2200                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2201                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2202                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2203                        } else {
2204                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2205                            continue;
2206                        }
2207
2208                        mSettings.enableSystemPackageLPw(packageName);
2209
2210                        try {
2211                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2212                        } catch (PackageManagerException e) {
2213                            Slog.e(TAG, "Failed to parse original system package: "
2214                                    + e.getMessage());
2215                        }
2216                    }
2217                }
2218            }
2219            mExpectingBetter.clear();
2220
2221            // Now that we know all of the shared libraries, update all clients to have
2222            // the correct library paths.
2223            updateAllSharedLibrariesLPw();
2224
2225            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2226                // NOTE: We ignore potential failures here during a system scan (like
2227                // the rest of the commands above) because there's precious little we
2228                // can do about it. A settings error is reported, though.
2229                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2230                        false /* force dexopt */, false /* defer dexopt */);
2231            }
2232
2233            // Now that we know all the packages we are keeping,
2234            // read and update their last usage times.
2235            mPackageUsage.readLP();
2236
2237            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2238                    SystemClock.uptimeMillis());
2239            Slog.i(TAG, "Time to scan packages: "
2240                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2241                    + " seconds");
2242
2243            // If the platform SDK has changed since the last time we booted,
2244            // we need to re-grant app permission to catch any new ones that
2245            // appear.  This is really a hack, and means that apps can in some
2246            // cases get permissions that the user didn't initially explicitly
2247            // allow...  it would be nice to have some better way to handle
2248            // this situation.
2249            final VersionInfo ver = mSettings.getInternalVersion();
2250
2251            int updateFlags = UPDATE_PERMISSIONS_ALL;
2252            if (ver.sdkVersion != mSdkVersion) {
2253                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2254                        + mSdkVersion + "; regranting permissions for internal storage");
2255                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2256            }
2257            updatePermissionsLPw(null, null, updateFlags);
2258            ver.sdkVersion = mSdkVersion;
2259
2260            // If this is the first boot, and it is a normal boot, then
2261            // we need to initialize the default preferred apps.
2262            if (!mRestoredSettings && !onlyCore) {
2263                mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER);
2264                applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER);
2265                primeDomainVerificationsLPw(UserHandle.USER_OWNER);
2266            }
2267
2268            // If this is first boot after an OTA, and a normal boot, then
2269            // we need to clear code cache directories.
2270            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2271            if (mIsUpgrade && !onlyCore) {
2272                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2273                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2274                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2275                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2276                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2277                    }
2278                }
2279                ver.fingerprint = Build.FINGERPRINT;
2280            }
2281
2282            checkDefaultBrowser();
2283
2284            // All the changes are done during package scanning.
2285            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2286
2287            // can downgrade to reader
2288            mSettings.writeLPr();
2289
2290            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2291                    SystemClock.uptimeMillis());
2292
2293            mRequiredVerifierPackage = getRequiredVerifierLPr();
2294            mRequiredInstallerPackage = getRequiredInstallerLPr();
2295
2296            mInstallerService = new PackageInstallerService(context, this);
2297
2298            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2299            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2300                    mIntentFilterVerifierComponent);
2301
2302        } // synchronized (mPackages)
2303        } // synchronized (mInstallLock)
2304
2305        // Now after opening every single application zip, make sure they
2306        // are all flushed.  Not really needed, but keeps things nice and
2307        // tidy.
2308        Runtime.getRuntime().gc();
2309
2310        // Expose private service for system components to use.
2311        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2312    }
2313
2314    @Override
2315    public boolean isFirstBoot() {
2316        return !mRestoredSettings;
2317    }
2318
2319    @Override
2320    public boolean isOnlyCoreApps() {
2321        return mOnlyCore;
2322    }
2323
2324    @Override
2325    public boolean isUpgrade() {
2326        return mIsUpgrade;
2327    }
2328
2329    private String getRequiredVerifierLPr() {
2330        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2331        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2332                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2333
2334        String requiredVerifier = null;
2335
2336        final int N = receivers.size();
2337        for (int i = 0; i < N; i++) {
2338            final ResolveInfo info = receivers.get(i);
2339
2340            if (info.activityInfo == null) {
2341                continue;
2342            }
2343
2344            final String packageName = info.activityInfo.packageName;
2345
2346            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2347                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2348                continue;
2349            }
2350
2351            if (requiredVerifier != null) {
2352                throw new RuntimeException("There can be only one required verifier");
2353            }
2354
2355            requiredVerifier = packageName;
2356        }
2357
2358        return requiredVerifier;
2359    }
2360
2361    private String getRequiredInstallerLPr() {
2362        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2363        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2364        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2365
2366        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2367                PACKAGE_MIME_TYPE, 0, 0);
2368
2369        String requiredInstaller = null;
2370
2371        final int N = installers.size();
2372        for (int i = 0; i < N; i++) {
2373            final ResolveInfo info = installers.get(i);
2374            final String packageName = info.activityInfo.packageName;
2375
2376            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2377                continue;
2378            }
2379
2380            if (requiredInstaller != null) {
2381                throw new RuntimeException("There must be one required installer");
2382            }
2383
2384            requiredInstaller = packageName;
2385        }
2386
2387        if (requiredInstaller == null) {
2388            throw new RuntimeException("There must be one required installer");
2389        }
2390
2391        return requiredInstaller;
2392    }
2393
2394    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2395        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2396        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2397                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2398
2399        ComponentName verifierComponentName = null;
2400
2401        int priority = -1000;
2402        final int N = receivers.size();
2403        for (int i = 0; i < N; i++) {
2404            final ResolveInfo info = receivers.get(i);
2405
2406            if (info.activityInfo == null) {
2407                continue;
2408            }
2409
2410            final String packageName = info.activityInfo.packageName;
2411
2412            final PackageSetting ps = mSettings.mPackages.get(packageName);
2413            if (ps == null) {
2414                continue;
2415            }
2416
2417            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2418                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2419                continue;
2420            }
2421
2422            // Select the IntentFilterVerifier with the highest priority
2423            if (priority < info.priority) {
2424                priority = info.priority;
2425                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2426                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2427                        + verifierComponentName + " with priority: " + info.priority);
2428            }
2429        }
2430
2431        return verifierComponentName;
2432    }
2433
2434    private void primeDomainVerificationsLPw(int userId) {
2435        if (DEBUG_DOMAIN_VERIFICATION) {
2436            Slog.d(TAG, "Priming domain verifications in user " + userId);
2437        }
2438
2439        SystemConfig systemConfig = SystemConfig.getInstance();
2440        ArraySet<String> packages = systemConfig.getLinkedApps();
2441        ArraySet<String> domains = new ArraySet<String>();
2442
2443        for (String packageName : packages) {
2444            PackageParser.Package pkg = mPackages.get(packageName);
2445            if (pkg != null) {
2446                if (!pkg.isSystemApp()) {
2447                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2448                    continue;
2449                }
2450
2451                domains.clear();
2452                for (PackageParser.Activity a : pkg.activities) {
2453                    for (ActivityIntentInfo filter : a.intents) {
2454                        if (hasValidDomains(filter)) {
2455                            domains.addAll(filter.getHostsList());
2456                        }
2457                    }
2458                }
2459
2460                if (domains.size() > 0) {
2461                    if (DEBUG_DOMAIN_VERIFICATION) {
2462                        Slog.v(TAG, "      + " + packageName);
2463                    }
2464                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2465                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2466                    // and then 'always' in the per-user state actually used for intent resolution.
2467                    final IntentFilterVerificationInfo ivi;
2468                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2469                            new ArrayList<String>(domains));
2470                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2471                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2472                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2473                } else {
2474                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2475                            + "' does not handle web links");
2476                }
2477            } else {
2478                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2479            }
2480        }
2481
2482        scheduleWritePackageRestrictionsLocked(userId);
2483        scheduleWriteSettingsLocked();
2484    }
2485
2486    private void applyFactoryDefaultBrowserLPw(int userId) {
2487        // The default browser app's package name is stored in a string resource,
2488        // with a product-specific overlay used for vendor customization.
2489        String browserPkg = mContext.getResources().getString(
2490                com.android.internal.R.string.default_browser);
2491        if (!TextUtils.isEmpty(browserPkg)) {
2492            // non-empty string => required to be a known package
2493            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2494            if (ps == null) {
2495                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2496                browserPkg = null;
2497            } else {
2498                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2499            }
2500        }
2501
2502        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2503        // default.  If there's more than one, just leave everything alone.
2504        if (browserPkg == null) {
2505            calculateDefaultBrowserLPw(userId);
2506        }
2507    }
2508
2509    private void calculateDefaultBrowserLPw(int userId) {
2510        List<String> allBrowsers = resolveAllBrowserApps(userId);
2511        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2512        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2513    }
2514
2515    private List<String> resolveAllBrowserApps(int userId) {
2516        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2517        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2518                PackageManager.MATCH_ALL, userId);
2519
2520        final int count = list.size();
2521        List<String> result = new ArrayList<String>(count);
2522        for (int i=0; i<count; i++) {
2523            ResolveInfo info = list.get(i);
2524            if (info.activityInfo == null
2525                    || !info.handleAllWebDataURI
2526                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2527                    || result.contains(info.activityInfo.packageName)) {
2528                continue;
2529            }
2530            result.add(info.activityInfo.packageName);
2531        }
2532
2533        return result;
2534    }
2535
2536    private boolean packageIsBrowser(String packageName, int userId) {
2537        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2538                PackageManager.MATCH_ALL, userId);
2539        final int N = list.size();
2540        for (int i = 0; i < N; i++) {
2541            ResolveInfo info = list.get(i);
2542            if (packageName.equals(info.activityInfo.packageName)) {
2543                return true;
2544            }
2545        }
2546        return false;
2547    }
2548
2549    private void checkDefaultBrowser() {
2550        final int myUserId = UserHandle.myUserId();
2551        final String packageName = getDefaultBrowserPackageName(myUserId);
2552        if (packageName != null) {
2553            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2554            if (info == null) {
2555                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2556                synchronized (mPackages) {
2557                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2558                }
2559            }
2560        }
2561    }
2562
2563    @Override
2564    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2565            throws RemoteException {
2566        try {
2567            return super.onTransact(code, data, reply, flags);
2568        } catch (RuntimeException e) {
2569            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2570                Slog.wtf(TAG, "Package Manager Crash", e);
2571            }
2572            throw e;
2573        }
2574    }
2575
2576    void cleanupInstallFailedPackage(PackageSetting ps) {
2577        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2578
2579        removeDataDirsLI(ps.volumeUuid, ps.name);
2580        if (ps.codePath != null) {
2581            if (ps.codePath.isDirectory()) {
2582                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2583            } else {
2584                ps.codePath.delete();
2585            }
2586        }
2587        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2588            if (ps.resourcePath.isDirectory()) {
2589                FileUtils.deleteContents(ps.resourcePath);
2590            }
2591            ps.resourcePath.delete();
2592        }
2593        mSettings.removePackageLPw(ps.name);
2594    }
2595
2596    static int[] appendInts(int[] cur, int[] add) {
2597        if (add == null) return cur;
2598        if (cur == null) return add;
2599        final int N = add.length;
2600        for (int i=0; i<N; i++) {
2601            cur = appendInt(cur, add[i]);
2602        }
2603        return cur;
2604    }
2605
2606    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2607        if (!sUserManager.exists(userId)) return null;
2608        final PackageSetting ps = (PackageSetting) p.mExtras;
2609        if (ps == null) {
2610            return null;
2611        }
2612
2613        final PermissionsState permissionsState = ps.getPermissionsState();
2614
2615        final int[] gids = permissionsState.computeGids(userId);
2616        final Set<String> permissions = permissionsState.getPermissions(userId);
2617        final PackageUserState state = ps.readUserState(userId);
2618
2619        return PackageParser.generatePackageInfo(p, gids, flags,
2620                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2621    }
2622
2623    @Override
2624    public boolean isPackageFrozen(String packageName) {
2625        synchronized (mPackages) {
2626            final PackageSetting ps = mSettings.mPackages.get(packageName);
2627            if (ps != null) {
2628                return ps.frozen;
2629            }
2630        }
2631        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2632        return true;
2633    }
2634
2635    @Override
2636    public boolean isPackageAvailable(String packageName, int userId) {
2637        if (!sUserManager.exists(userId)) return false;
2638        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2639        synchronized (mPackages) {
2640            PackageParser.Package p = mPackages.get(packageName);
2641            if (p != null) {
2642                final PackageSetting ps = (PackageSetting) p.mExtras;
2643                if (ps != null) {
2644                    final PackageUserState state = ps.readUserState(userId);
2645                    if (state != null) {
2646                        return PackageParser.isAvailable(state);
2647                    }
2648                }
2649            }
2650        }
2651        return false;
2652    }
2653
2654    @Override
2655    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2656        if (!sUserManager.exists(userId)) return null;
2657        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2658        // reader
2659        synchronized (mPackages) {
2660            PackageParser.Package p = mPackages.get(packageName);
2661            if (DEBUG_PACKAGE_INFO)
2662                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2663            if (p != null) {
2664                return generatePackageInfo(p, flags, userId);
2665            }
2666            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2667                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2668            }
2669        }
2670        return null;
2671    }
2672
2673    @Override
2674    public String[] currentToCanonicalPackageNames(String[] names) {
2675        String[] out = new String[names.length];
2676        // reader
2677        synchronized (mPackages) {
2678            for (int i=names.length-1; i>=0; i--) {
2679                PackageSetting ps = mSettings.mPackages.get(names[i]);
2680                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2681            }
2682        }
2683        return out;
2684    }
2685
2686    @Override
2687    public String[] canonicalToCurrentPackageNames(String[] names) {
2688        String[] out = new String[names.length];
2689        // reader
2690        synchronized (mPackages) {
2691            for (int i=names.length-1; i>=0; i--) {
2692                String cur = mSettings.mRenamedPackages.get(names[i]);
2693                out[i] = cur != null ? cur : names[i];
2694            }
2695        }
2696        return out;
2697    }
2698
2699    @Override
2700    public int getPackageUid(String packageName, int userId) {
2701        if (!sUserManager.exists(userId)) return -1;
2702        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2703
2704        // reader
2705        synchronized (mPackages) {
2706            PackageParser.Package p = mPackages.get(packageName);
2707            if(p != null) {
2708                return UserHandle.getUid(userId, p.applicationInfo.uid);
2709            }
2710            PackageSetting ps = mSettings.mPackages.get(packageName);
2711            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2712                return -1;
2713            }
2714            p = ps.pkg;
2715            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2716        }
2717    }
2718
2719    @Override
2720    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2721        if (!sUserManager.exists(userId)) {
2722            return null;
2723        }
2724
2725        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2726                "getPackageGids");
2727
2728        // reader
2729        synchronized (mPackages) {
2730            PackageParser.Package p = mPackages.get(packageName);
2731            if (DEBUG_PACKAGE_INFO) {
2732                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2733            }
2734            if (p != null) {
2735                PackageSetting ps = (PackageSetting) p.mExtras;
2736                return ps.getPermissionsState().computeGids(userId);
2737            }
2738        }
2739
2740        return null;
2741    }
2742
2743    static PermissionInfo generatePermissionInfo(
2744            BasePermission bp, int flags) {
2745        if (bp.perm != null) {
2746            return PackageParser.generatePermissionInfo(bp.perm, flags);
2747        }
2748        PermissionInfo pi = new PermissionInfo();
2749        pi.name = bp.name;
2750        pi.packageName = bp.sourcePackage;
2751        pi.nonLocalizedLabel = bp.name;
2752        pi.protectionLevel = bp.protectionLevel;
2753        return pi;
2754    }
2755
2756    @Override
2757    public PermissionInfo getPermissionInfo(String name, int flags) {
2758        // reader
2759        synchronized (mPackages) {
2760            final BasePermission p = mSettings.mPermissions.get(name);
2761            if (p != null) {
2762                return generatePermissionInfo(p, flags);
2763            }
2764            return null;
2765        }
2766    }
2767
2768    @Override
2769    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2770        // reader
2771        synchronized (mPackages) {
2772            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2773            for (BasePermission p : mSettings.mPermissions.values()) {
2774                if (group == null) {
2775                    if (p.perm == null || p.perm.info.group == null) {
2776                        out.add(generatePermissionInfo(p, flags));
2777                    }
2778                } else {
2779                    if (p.perm != null && group.equals(p.perm.info.group)) {
2780                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2781                    }
2782                }
2783            }
2784
2785            if (out.size() > 0) {
2786                return out;
2787            }
2788            return mPermissionGroups.containsKey(group) ? out : null;
2789        }
2790    }
2791
2792    @Override
2793    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2794        // reader
2795        synchronized (mPackages) {
2796            return PackageParser.generatePermissionGroupInfo(
2797                    mPermissionGroups.get(name), flags);
2798        }
2799    }
2800
2801    @Override
2802    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2803        // reader
2804        synchronized (mPackages) {
2805            final int N = mPermissionGroups.size();
2806            ArrayList<PermissionGroupInfo> out
2807                    = new ArrayList<PermissionGroupInfo>(N);
2808            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2809                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2810            }
2811            return out;
2812        }
2813    }
2814
2815    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2816            int userId) {
2817        if (!sUserManager.exists(userId)) return null;
2818        PackageSetting ps = mSettings.mPackages.get(packageName);
2819        if (ps != null) {
2820            if (ps.pkg == null) {
2821                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2822                        flags, userId);
2823                if (pInfo != null) {
2824                    return pInfo.applicationInfo;
2825                }
2826                return null;
2827            }
2828            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2829                    ps.readUserState(userId), userId);
2830        }
2831        return null;
2832    }
2833
2834    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2835            int userId) {
2836        if (!sUserManager.exists(userId)) return null;
2837        PackageSetting ps = mSettings.mPackages.get(packageName);
2838        if (ps != null) {
2839            PackageParser.Package pkg = ps.pkg;
2840            if (pkg == null) {
2841                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2842                    return null;
2843                }
2844                // Only data remains, so we aren't worried about code paths
2845                pkg = new PackageParser.Package(packageName);
2846                pkg.applicationInfo.packageName = packageName;
2847                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2848                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2849                pkg.applicationInfo.dataDir = Environment
2850                        .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName)
2851                        .getAbsolutePath();
2852                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2853                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2854            }
2855            return generatePackageInfo(pkg, flags, userId);
2856        }
2857        return null;
2858    }
2859
2860    @Override
2861    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2862        if (!sUserManager.exists(userId)) return null;
2863        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2864        // writer
2865        synchronized (mPackages) {
2866            PackageParser.Package p = mPackages.get(packageName);
2867            if (DEBUG_PACKAGE_INFO) Log.v(
2868                    TAG, "getApplicationInfo " + packageName
2869                    + ": " + p);
2870            if (p != null) {
2871                PackageSetting ps = mSettings.mPackages.get(packageName);
2872                if (ps == null) return null;
2873                // Note: isEnabledLP() does not apply here - always return info
2874                return PackageParser.generateApplicationInfo(
2875                        p, flags, ps.readUserState(userId), userId);
2876            }
2877            if ("android".equals(packageName)||"system".equals(packageName)) {
2878                return mAndroidApplication;
2879            }
2880            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2881                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2882            }
2883        }
2884        return null;
2885    }
2886
2887    @Override
2888    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2889            final IPackageDataObserver observer) {
2890        mContext.enforceCallingOrSelfPermission(
2891                android.Manifest.permission.CLEAR_APP_CACHE, null);
2892        // Queue up an async operation since clearing cache may take a little while.
2893        mHandler.post(new Runnable() {
2894            public void run() {
2895                mHandler.removeCallbacks(this);
2896                int retCode = -1;
2897                synchronized (mInstallLock) {
2898                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2899                    if (retCode < 0) {
2900                        Slog.w(TAG, "Couldn't clear application caches");
2901                    }
2902                }
2903                if (observer != null) {
2904                    try {
2905                        observer.onRemoveCompleted(null, (retCode >= 0));
2906                    } catch (RemoteException e) {
2907                        Slog.w(TAG, "RemoveException when invoking call back");
2908                    }
2909                }
2910            }
2911        });
2912    }
2913
2914    @Override
2915    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2916            final IntentSender pi) {
2917        mContext.enforceCallingOrSelfPermission(
2918                android.Manifest.permission.CLEAR_APP_CACHE, null);
2919        // Queue up an async operation since clearing cache may take a little while.
2920        mHandler.post(new Runnable() {
2921            public void run() {
2922                mHandler.removeCallbacks(this);
2923                int retCode = -1;
2924                synchronized (mInstallLock) {
2925                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2926                    if (retCode < 0) {
2927                        Slog.w(TAG, "Couldn't clear application caches");
2928                    }
2929                }
2930                if(pi != null) {
2931                    try {
2932                        // Callback via pending intent
2933                        int code = (retCode >= 0) ? 1 : 0;
2934                        pi.sendIntent(null, code, null,
2935                                null, null);
2936                    } catch (SendIntentException e1) {
2937                        Slog.i(TAG, "Failed to send pending intent");
2938                    }
2939                }
2940            }
2941        });
2942    }
2943
2944    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2945        synchronized (mInstallLock) {
2946            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2947                throw new IOException("Failed to free enough space");
2948            }
2949        }
2950    }
2951
2952    @Override
2953    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2954        if (!sUserManager.exists(userId)) return null;
2955        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2956        synchronized (mPackages) {
2957            PackageParser.Activity a = mActivities.mActivities.get(component);
2958
2959            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2960            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2961                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2962                if (ps == null) return null;
2963                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2964                        userId);
2965            }
2966            if (mResolveComponentName.equals(component)) {
2967                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2968                        new PackageUserState(), userId);
2969            }
2970        }
2971        return null;
2972    }
2973
2974    @Override
2975    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2976            String resolvedType) {
2977        synchronized (mPackages) {
2978            if (component.equals(mResolveComponentName)) {
2979                // The resolver supports EVERYTHING!
2980                return true;
2981            }
2982            PackageParser.Activity a = mActivities.mActivities.get(component);
2983            if (a == null) {
2984                return false;
2985            }
2986            for (int i=0; i<a.intents.size(); i++) {
2987                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2988                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2989                    return true;
2990                }
2991            }
2992            return false;
2993        }
2994    }
2995
2996    @Override
2997    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2998        if (!sUserManager.exists(userId)) return null;
2999        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3000        synchronized (mPackages) {
3001            PackageParser.Activity a = mReceivers.mActivities.get(component);
3002            if (DEBUG_PACKAGE_INFO) Log.v(
3003                TAG, "getReceiverInfo " + component + ": " + a);
3004            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
3005                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3006                if (ps == null) return null;
3007                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3008                        userId);
3009            }
3010        }
3011        return null;
3012    }
3013
3014    @Override
3015    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3016        if (!sUserManager.exists(userId)) return null;
3017        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3018        synchronized (mPackages) {
3019            PackageParser.Service s = mServices.mServices.get(component);
3020            if (DEBUG_PACKAGE_INFO) Log.v(
3021                TAG, "getServiceInfo " + component + ": " + s);
3022            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
3023                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3024                if (ps == null) return null;
3025                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3026                        userId);
3027            }
3028        }
3029        return null;
3030    }
3031
3032    @Override
3033    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3034        if (!sUserManager.exists(userId)) return null;
3035        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3036        synchronized (mPackages) {
3037            PackageParser.Provider p = mProviders.mProviders.get(component);
3038            if (DEBUG_PACKAGE_INFO) Log.v(
3039                TAG, "getProviderInfo " + component + ": " + p);
3040            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
3041                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3042                if (ps == null) return null;
3043                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3044                        userId);
3045            }
3046        }
3047        return null;
3048    }
3049
3050    @Override
3051    public String[] getSystemSharedLibraryNames() {
3052        Set<String> libSet;
3053        synchronized (mPackages) {
3054            libSet = mSharedLibraries.keySet();
3055            int size = libSet.size();
3056            if (size > 0) {
3057                String[] libs = new String[size];
3058                libSet.toArray(libs);
3059                return libs;
3060            }
3061        }
3062        return null;
3063    }
3064
3065    /**
3066     * @hide
3067     */
3068    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3069        synchronized (mPackages) {
3070            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3071            if (lib != null && lib.apk != null) {
3072                return mPackages.get(lib.apk);
3073            }
3074        }
3075        return null;
3076    }
3077
3078    @Override
3079    public FeatureInfo[] getSystemAvailableFeatures() {
3080        Collection<FeatureInfo> featSet;
3081        synchronized (mPackages) {
3082            featSet = mAvailableFeatures.values();
3083            int size = featSet.size();
3084            if (size > 0) {
3085                FeatureInfo[] features = new FeatureInfo[size+1];
3086                featSet.toArray(features);
3087                FeatureInfo fi = new FeatureInfo();
3088                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3089                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3090                features[size] = fi;
3091                return features;
3092            }
3093        }
3094        return null;
3095    }
3096
3097    @Override
3098    public boolean hasSystemFeature(String name) {
3099        synchronized (mPackages) {
3100            return mAvailableFeatures.containsKey(name);
3101        }
3102    }
3103
3104    private void checkValidCaller(int uid, int userId) {
3105        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3106            return;
3107
3108        throw new SecurityException("Caller uid=" + uid
3109                + " is not privileged to communicate with user=" + userId);
3110    }
3111
3112    @Override
3113    public int checkPermission(String permName, String pkgName, int userId) {
3114        if (!sUserManager.exists(userId)) {
3115            return PackageManager.PERMISSION_DENIED;
3116        }
3117
3118        synchronized (mPackages) {
3119            final PackageParser.Package p = mPackages.get(pkgName);
3120            if (p != null && p.mExtras != null) {
3121                final PackageSetting ps = (PackageSetting) p.mExtras;
3122                final PermissionsState permissionsState = ps.getPermissionsState();
3123                if (permissionsState.hasPermission(permName, userId)) {
3124                    return PackageManager.PERMISSION_GRANTED;
3125                }
3126                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3127                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3128                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3129                    return PackageManager.PERMISSION_GRANTED;
3130                }
3131            }
3132        }
3133
3134        return PackageManager.PERMISSION_DENIED;
3135    }
3136
3137    @Override
3138    public int checkUidPermission(String permName, int uid) {
3139        final int userId = UserHandle.getUserId(uid);
3140
3141        if (!sUserManager.exists(userId)) {
3142            return PackageManager.PERMISSION_DENIED;
3143        }
3144
3145        synchronized (mPackages) {
3146            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3147            if (obj != null) {
3148                final SettingBase ps = (SettingBase) obj;
3149                final PermissionsState permissionsState = ps.getPermissionsState();
3150                if (permissionsState.hasPermission(permName, userId)) {
3151                    return PackageManager.PERMISSION_GRANTED;
3152                }
3153                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3154                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3155                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3156                    return PackageManager.PERMISSION_GRANTED;
3157                }
3158            } else {
3159                ArraySet<String> perms = mSystemPermissions.get(uid);
3160                if (perms != null) {
3161                    if (perms.contains(permName)) {
3162                        return PackageManager.PERMISSION_GRANTED;
3163                    }
3164                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3165                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3166                        return PackageManager.PERMISSION_GRANTED;
3167                    }
3168                }
3169            }
3170        }
3171
3172        return PackageManager.PERMISSION_DENIED;
3173    }
3174
3175    @Override
3176    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3177        if (UserHandle.getCallingUserId() != userId) {
3178            mContext.enforceCallingPermission(
3179                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3180                    "isPermissionRevokedByPolicy for user " + userId);
3181        }
3182
3183        if (checkPermission(permission, packageName, userId)
3184                == PackageManager.PERMISSION_GRANTED) {
3185            return false;
3186        }
3187
3188        final long identity = Binder.clearCallingIdentity();
3189        try {
3190            final int flags = getPermissionFlags(permission, packageName, userId);
3191            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3192        } finally {
3193            Binder.restoreCallingIdentity(identity);
3194        }
3195    }
3196
3197    /**
3198     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3199     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3200     * @param checkShell TODO(yamasani):
3201     * @param message the message to log on security exception
3202     */
3203    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3204            boolean checkShell, String message) {
3205        if (userId < 0) {
3206            throw new IllegalArgumentException("Invalid userId " + userId);
3207        }
3208        if (checkShell) {
3209            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3210        }
3211        if (userId == UserHandle.getUserId(callingUid)) return;
3212        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3213            if (requireFullPermission) {
3214                mContext.enforceCallingOrSelfPermission(
3215                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3216            } else {
3217                try {
3218                    mContext.enforceCallingOrSelfPermission(
3219                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3220                } catch (SecurityException se) {
3221                    mContext.enforceCallingOrSelfPermission(
3222                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3223                }
3224            }
3225        }
3226    }
3227
3228    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3229        if (callingUid == Process.SHELL_UID) {
3230            if (userHandle >= 0
3231                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3232                throw new SecurityException("Shell does not have permission to access user "
3233                        + userHandle);
3234            } else if (userHandle < 0) {
3235                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3236                        + Debug.getCallers(3));
3237            }
3238        }
3239    }
3240
3241    private BasePermission findPermissionTreeLP(String permName) {
3242        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3243            if (permName.startsWith(bp.name) &&
3244                    permName.length() > bp.name.length() &&
3245                    permName.charAt(bp.name.length()) == '.') {
3246                return bp;
3247            }
3248        }
3249        return null;
3250    }
3251
3252    private BasePermission checkPermissionTreeLP(String permName) {
3253        if (permName != null) {
3254            BasePermission bp = findPermissionTreeLP(permName);
3255            if (bp != null) {
3256                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3257                    return bp;
3258                }
3259                throw new SecurityException("Calling uid "
3260                        + Binder.getCallingUid()
3261                        + " is not allowed to add to permission tree "
3262                        + bp.name + " owned by uid " + bp.uid);
3263            }
3264        }
3265        throw new SecurityException("No permission tree found for " + permName);
3266    }
3267
3268    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3269        if (s1 == null) {
3270            return s2 == null;
3271        }
3272        if (s2 == null) {
3273            return false;
3274        }
3275        if (s1.getClass() != s2.getClass()) {
3276            return false;
3277        }
3278        return s1.equals(s2);
3279    }
3280
3281    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3282        if (pi1.icon != pi2.icon) return false;
3283        if (pi1.logo != pi2.logo) return false;
3284        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3285        if (!compareStrings(pi1.name, pi2.name)) return false;
3286        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3287        // We'll take care of setting this one.
3288        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3289        // These are not currently stored in settings.
3290        //if (!compareStrings(pi1.group, pi2.group)) return false;
3291        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3292        //if (pi1.labelRes != pi2.labelRes) return false;
3293        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3294        return true;
3295    }
3296
3297    int permissionInfoFootprint(PermissionInfo info) {
3298        int size = info.name.length();
3299        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3300        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3301        return size;
3302    }
3303
3304    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3305        int size = 0;
3306        for (BasePermission perm : mSettings.mPermissions.values()) {
3307            if (perm.uid == tree.uid) {
3308                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3309            }
3310        }
3311        return size;
3312    }
3313
3314    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3315        // We calculate the max size of permissions defined by this uid and throw
3316        // if that plus the size of 'info' would exceed our stated maximum.
3317        if (tree.uid != Process.SYSTEM_UID) {
3318            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3319            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3320                throw new SecurityException("Permission tree size cap exceeded");
3321            }
3322        }
3323    }
3324
3325    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3326        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3327            throw new SecurityException("Label must be specified in permission");
3328        }
3329        BasePermission tree = checkPermissionTreeLP(info.name);
3330        BasePermission bp = mSettings.mPermissions.get(info.name);
3331        boolean added = bp == null;
3332        boolean changed = true;
3333        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3334        if (added) {
3335            enforcePermissionCapLocked(info, tree);
3336            bp = new BasePermission(info.name, tree.sourcePackage,
3337                    BasePermission.TYPE_DYNAMIC);
3338        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3339            throw new SecurityException(
3340                    "Not allowed to modify non-dynamic permission "
3341                    + info.name);
3342        } else {
3343            if (bp.protectionLevel == fixedLevel
3344                    && bp.perm.owner.equals(tree.perm.owner)
3345                    && bp.uid == tree.uid
3346                    && comparePermissionInfos(bp.perm.info, info)) {
3347                changed = false;
3348            }
3349        }
3350        bp.protectionLevel = fixedLevel;
3351        info = new PermissionInfo(info);
3352        info.protectionLevel = fixedLevel;
3353        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3354        bp.perm.info.packageName = tree.perm.info.packageName;
3355        bp.uid = tree.uid;
3356        if (added) {
3357            mSettings.mPermissions.put(info.name, bp);
3358        }
3359        if (changed) {
3360            if (!async) {
3361                mSettings.writeLPr();
3362            } else {
3363                scheduleWriteSettingsLocked();
3364            }
3365        }
3366        return added;
3367    }
3368
3369    @Override
3370    public boolean addPermission(PermissionInfo info) {
3371        synchronized (mPackages) {
3372            return addPermissionLocked(info, false);
3373        }
3374    }
3375
3376    @Override
3377    public boolean addPermissionAsync(PermissionInfo info) {
3378        synchronized (mPackages) {
3379            return addPermissionLocked(info, true);
3380        }
3381    }
3382
3383    @Override
3384    public void removePermission(String name) {
3385        synchronized (mPackages) {
3386            checkPermissionTreeLP(name);
3387            BasePermission bp = mSettings.mPermissions.get(name);
3388            if (bp != null) {
3389                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3390                    throw new SecurityException(
3391                            "Not allowed to modify non-dynamic permission "
3392                            + name);
3393                }
3394                mSettings.mPermissions.remove(name);
3395                mSettings.writeLPr();
3396            }
3397        }
3398    }
3399
3400    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3401            BasePermission bp) {
3402        int index = pkg.requestedPermissions.indexOf(bp.name);
3403        if (index == -1) {
3404            throw new SecurityException("Package " + pkg.packageName
3405                    + " has not requested permission " + bp.name);
3406        }
3407        if (!bp.isRuntime()) {
3408            throw new SecurityException("Permission " + bp.name
3409                    + " is not a changeable permission type");
3410        }
3411    }
3412
3413    @Override
3414    public void grantRuntimePermission(String packageName, String name, final int userId) {
3415        if (!sUserManager.exists(userId)) {
3416            Log.e(TAG, "No such user:" + userId);
3417            return;
3418        }
3419
3420        mContext.enforceCallingOrSelfPermission(
3421                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3422                "grantRuntimePermission");
3423
3424        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3425                "grantRuntimePermission");
3426
3427        final int uid;
3428        final SettingBase sb;
3429
3430        synchronized (mPackages) {
3431            final PackageParser.Package pkg = mPackages.get(packageName);
3432            if (pkg == null) {
3433                throw new IllegalArgumentException("Unknown package: " + packageName);
3434            }
3435
3436            final BasePermission bp = mSettings.mPermissions.get(name);
3437            if (bp == null) {
3438                throw new IllegalArgumentException("Unknown permission: " + name);
3439            }
3440
3441            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3442
3443            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3444            sb = (SettingBase) pkg.mExtras;
3445            if (sb == null) {
3446                throw new IllegalArgumentException("Unknown package: " + packageName);
3447            }
3448
3449            final PermissionsState permissionsState = sb.getPermissionsState();
3450
3451            final int flags = permissionsState.getPermissionFlags(name, userId);
3452            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3453                throw new SecurityException("Cannot grant system fixed permission: "
3454                        + name + " for package: " + packageName);
3455            }
3456
3457            final int result = permissionsState.grantRuntimePermission(bp, userId);
3458            switch (result) {
3459                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3460                    return;
3461                }
3462
3463                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3464                    mHandler.post(new Runnable() {
3465                        @Override
3466                        public void run() {
3467                            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3468                        }
3469                    });
3470                } break;
3471            }
3472
3473            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3474
3475            // Not critical if that is lost - app has to request again.
3476            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3477        }
3478
3479        // Only need to do this if user is initialized. Otherwise it's a new user
3480        // and there are no processes running as the user yet and there's no need
3481        // to make an expensive call to remount processes for the changed permissions.
3482        if (READ_EXTERNAL_STORAGE.equals(name)
3483                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3484            final long token = Binder.clearCallingIdentity();
3485            try {
3486                if (sUserManager.isInitialized(userId)) {
3487                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3488                            MountServiceInternal.class);
3489                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3490                }
3491            } finally {
3492                Binder.restoreCallingIdentity(token);
3493            }
3494        }
3495    }
3496
3497    @Override
3498    public void revokeRuntimePermission(String packageName, String name, int userId) {
3499        if (!sUserManager.exists(userId)) {
3500            Log.e(TAG, "No such user:" + userId);
3501            return;
3502        }
3503
3504        mContext.enforceCallingOrSelfPermission(
3505                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3506                "revokeRuntimePermission");
3507
3508        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3509                "revokeRuntimePermission");
3510
3511        final SettingBase sb;
3512
3513        synchronized (mPackages) {
3514            final PackageParser.Package pkg = mPackages.get(packageName);
3515            if (pkg == null) {
3516                throw new IllegalArgumentException("Unknown package: " + packageName);
3517            }
3518
3519            final BasePermission bp = mSettings.mPermissions.get(name);
3520            if (bp == null) {
3521                throw new IllegalArgumentException("Unknown permission: " + name);
3522            }
3523
3524            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3525
3526            sb = (SettingBase) pkg.mExtras;
3527            if (sb == null) {
3528                throw new IllegalArgumentException("Unknown package: " + packageName);
3529            }
3530
3531            final PermissionsState permissionsState = sb.getPermissionsState();
3532
3533            final int flags = permissionsState.getPermissionFlags(name, userId);
3534            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3535                throw new SecurityException("Cannot revoke system fixed permission: "
3536                        + name + " for package: " + packageName);
3537            }
3538
3539            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3540                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3541                return;
3542            }
3543
3544            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3545
3546            // Critical, after this call app should never have the permission.
3547            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3548        }
3549
3550        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3551    }
3552
3553    @Override
3554    public void resetRuntimePermissions() {
3555        mContext.enforceCallingOrSelfPermission(
3556                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3557                "revokeRuntimePermission");
3558
3559        int callingUid = Binder.getCallingUid();
3560        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3561            mContext.enforceCallingOrSelfPermission(
3562                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3563                    "resetRuntimePermissions");
3564        }
3565
3566        synchronized (mPackages) {
3567            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3568            for (int userId : UserManagerService.getInstance().getUserIds()) {
3569                final int packageCount = mPackages.size();
3570                for (int i = 0; i < packageCount; i++) {
3571                    PackageParser.Package pkg = mPackages.valueAt(i);
3572                    if (!(pkg.mExtras instanceof PackageSetting)) {
3573                        continue;
3574                    }
3575                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3576                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3577                }
3578            }
3579        }
3580    }
3581
3582    @Override
3583    public int getPermissionFlags(String name, String packageName, int userId) {
3584        if (!sUserManager.exists(userId)) {
3585            return 0;
3586        }
3587
3588        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3589
3590        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3591                "getPermissionFlags");
3592
3593        synchronized (mPackages) {
3594            final PackageParser.Package pkg = mPackages.get(packageName);
3595            if (pkg == null) {
3596                throw new IllegalArgumentException("Unknown package: " + packageName);
3597            }
3598
3599            final BasePermission bp = mSettings.mPermissions.get(name);
3600            if (bp == null) {
3601                throw new IllegalArgumentException("Unknown permission: " + name);
3602            }
3603
3604            SettingBase sb = (SettingBase) pkg.mExtras;
3605            if (sb == null) {
3606                throw new IllegalArgumentException("Unknown package: " + packageName);
3607            }
3608
3609            PermissionsState permissionsState = sb.getPermissionsState();
3610            return permissionsState.getPermissionFlags(name, userId);
3611        }
3612    }
3613
3614    @Override
3615    public void updatePermissionFlags(String name, String packageName, int flagMask,
3616            int flagValues, int userId) {
3617        if (!sUserManager.exists(userId)) {
3618            return;
3619        }
3620
3621        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3622
3623        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3624                "updatePermissionFlags");
3625
3626        // Only the system can change these flags and nothing else.
3627        if (getCallingUid() != Process.SYSTEM_UID) {
3628            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3629            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3630            flagMask &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED;
3631            flagValues &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED;
3632            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3633            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3634        }
3635
3636        synchronized (mPackages) {
3637            final PackageParser.Package pkg = mPackages.get(packageName);
3638            if (pkg == null) {
3639                throw new IllegalArgumentException("Unknown package: " + packageName);
3640            }
3641
3642            final BasePermission bp = mSettings.mPermissions.get(name);
3643            if (bp == null) {
3644                throw new IllegalArgumentException("Unknown permission: " + name);
3645            }
3646
3647            SettingBase sb = (SettingBase) pkg.mExtras;
3648            if (sb == null) {
3649                throw new IllegalArgumentException("Unknown package: " + packageName);
3650            }
3651
3652            PermissionsState permissionsState = sb.getPermissionsState();
3653
3654            // Only the package manager can change flags for system component permissions.
3655            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3656            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3657                return;
3658            }
3659
3660            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3661
3662            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3663                // Install and runtime permissions are stored in different places,
3664                // so figure out what permission changed and persist the change.
3665                if (permissionsState.getInstallPermissionState(name) != null) {
3666                    scheduleWriteSettingsLocked();
3667                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3668                        || hadState) {
3669                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3670                }
3671            }
3672        }
3673    }
3674
3675    /**
3676     * Update the permission flags for all packages and runtime permissions of a user in order
3677     * to allow device or profile owner to remove POLICY_FIXED.
3678     */
3679    @Override
3680    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3681        if (!sUserManager.exists(userId)) {
3682            return;
3683        }
3684
3685        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
3686
3687        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3688                "updatePermissionFlagsForAllApps");
3689
3690        // Only the system can change system fixed flags.
3691        if (getCallingUid() != Process.SYSTEM_UID) {
3692            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3693            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3694        }
3695
3696        synchronized (mPackages) {
3697            boolean changed = false;
3698            final int packageCount = mPackages.size();
3699            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3700                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3701                SettingBase sb = (SettingBase) pkg.mExtras;
3702                if (sb == null) {
3703                    continue;
3704                }
3705                PermissionsState permissionsState = sb.getPermissionsState();
3706                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3707                        userId, flagMask, flagValues);
3708            }
3709            if (changed) {
3710                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3711            }
3712        }
3713    }
3714
3715    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
3716        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
3717                != PackageManager.PERMISSION_GRANTED
3718            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
3719                != PackageManager.PERMISSION_GRANTED) {
3720            throw new SecurityException(message + " requires "
3721                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
3722                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
3723        }
3724    }
3725
3726    @Override
3727    public boolean shouldShowRequestPermissionRationale(String permissionName,
3728            String packageName, int userId) {
3729        if (UserHandle.getCallingUserId() != userId) {
3730            mContext.enforceCallingPermission(
3731                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3732                    "canShowRequestPermissionRationale for user " + userId);
3733        }
3734
3735        final int uid = getPackageUid(packageName, userId);
3736        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3737            return false;
3738        }
3739
3740        if (checkPermission(permissionName, packageName, userId)
3741                == PackageManager.PERMISSION_GRANTED) {
3742            return false;
3743        }
3744
3745        final int flags;
3746
3747        final long identity = Binder.clearCallingIdentity();
3748        try {
3749            flags = getPermissionFlags(permissionName,
3750                    packageName, userId);
3751        } finally {
3752            Binder.restoreCallingIdentity(identity);
3753        }
3754
3755        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3756                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3757                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3758
3759        if ((flags & fixedFlags) != 0) {
3760            return false;
3761        }
3762
3763        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3764    }
3765
3766    void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) {
3767        BasePermission bp = mSettings.mPermissions.get(permission);
3768        if (bp == null) {
3769            throw new SecurityException("Missing " + permission + " permission");
3770        }
3771
3772        SettingBase sb = (SettingBase) pkg.mExtras;
3773        PermissionsState permissionsState = sb.getPermissionsState();
3774
3775        if (permissionsState.grantInstallPermission(bp) !=
3776                PermissionsState.PERMISSION_OPERATION_FAILURE) {
3777            scheduleWriteSettingsLocked();
3778        }
3779    }
3780
3781    @Override
3782    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3783        mContext.enforceCallingOrSelfPermission(
3784                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3785                "addOnPermissionsChangeListener");
3786
3787        synchronized (mPackages) {
3788            mOnPermissionChangeListeners.addListenerLocked(listener);
3789        }
3790    }
3791
3792    @Override
3793    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3794        synchronized (mPackages) {
3795            mOnPermissionChangeListeners.removeListenerLocked(listener);
3796        }
3797    }
3798
3799    @Override
3800    public boolean isProtectedBroadcast(String actionName) {
3801        synchronized (mPackages) {
3802            return mProtectedBroadcasts.contains(actionName);
3803        }
3804    }
3805
3806    @Override
3807    public int checkSignatures(String pkg1, String pkg2) {
3808        synchronized (mPackages) {
3809            final PackageParser.Package p1 = mPackages.get(pkg1);
3810            final PackageParser.Package p2 = mPackages.get(pkg2);
3811            if (p1 == null || p1.mExtras == null
3812                    || p2 == null || p2.mExtras == null) {
3813                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3814            }
3815            return compareSignatures(p1.mSignatures, p2.mSignatures);
3816        }
3817    }
3818
3819    @Override
3820    public int checkUidSignatures(int uid1, int uid2) {
3821        // Map to base uids.
3822        uid1 = UserHandle.getAppId(uid1);
3823        uid2 = UserHandle.getAppId(uid2);
3824        // reader
3825        synchronized (mPackages) {
3826            Signature[] s1;
3827            Signature[] s2;
3828            Object obj = mSettings.getUserIdLPr(uid1);
3829            if (obj != null) {
3830                if (obj instanceof SharedUserSetting) {
3831                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3832                } else if (obj instanceof PackageSetting) {
3833                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3834                } else {
3835                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3836                }
3837            } else {
3838                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3839            }
3840            obj = mSettings.getUserIdLPr(uid2);
3841            if (obj != null) {
3842                if (obj instanceof SharedUserSetting) {
3843                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3844                } else if (obj instanceof PackageSetting) {
3845                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3846                } else {
3847                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3848                }
3849            } else {
3850                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3851            }
3852            return compareSignatures(s1, s2);
3853        }
3854    }
3855
3856    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3857        final long identity = Binder.clearCallingIdentity();
3858        try {
3859            if (sb instanceof SharedUserSetting) {
3860                SharedUserSetting sus = (SharedUserSetting) sb;
3861                final int packageCount = sus.packages.size();
3862                for (int i = 0; i < packageCount; i++) {
3863                    PackageSetting susPs = sus.packages.valueAt(i);
3864                    if (userId == UserHandle.USER_ALL) {
3865                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3866                    } else {
3867                        final int uid = UserHandle.getUid(userId, susPs.appId);
3868                        killUid(uid, reason);
3869                    }
3870                }
3871            } else if (sb instanceof PackageSetting) {
3872                PackageSetting ps = (PackageSetting) sb;
3873                if (userId == UserHandle.USER_ALL) {
3874                    killApplication(ps.pkg.packageName, ps.appId, reason);
3875                } else {
3876                    final int uid = UserHandle.getUid(userId, ps.appId);
3877                    killUid(uid, reason);
3878                }
3879            }
3880        } finally {
3881            Binder.restoreCallingIdentity(identity);
3882        }
3883    }
3884
3885    private static void killUid(int uid, String reason) {
3886        IActivityManager am = ActivityManagerNative.getDefault();
3887        if (am != null) {
3888            try {
3889                am.killUid(uid, reason);
3890            } catch (RemoteException e) {
3891                /* ignore - same process */
3892            }
3893        }
3894    }
3895
3896    /**
3897     * Compares two sets of signatures. Returns:
3898     * <br />
3899     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3900     * <br />
3901     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3902     * <br />
3903     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3904     * <br />
3905     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3906     * <br />
3907     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3908     */
3909    static int compareSignatures(Signature[] s1, Signature[] s2) {
3910        if (s1 == null) {
3911            return s2 == null
3912                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3913                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3914        }
3915
3916        if (s2 == null) {
3917            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3918        }
3919
3920        if (s1.length != s2.length) {
3921            return PackageManager.SIGNATURE_NO_MATCH;
3922        }
3923
3924        // Since both signature sets are of size 1, we can compare without HashSets.
3925        if (s1.length == 1) {
3926            return s1[0].equals(s2[0]) ?
3927                    PackageManager.SIGNATURE_MATCH :
3928                    PackageManager.SIGNATURE_NO_MATCH;
3929        }
3930
3931        ArraySet<Signature> set1 = new ArraySet<Signature>();
3932        for (Signature sig : s1) {
3933            set1.add(sig);
3934        }
3935        ArraySet<Signature> set2 = new ArraySet<Signature>();
3936        for (Signature sig : s2) {
3937            set2.add(sig);
3938        }
3939        // Make sure s2 contains all signatures in s1.
3940        if (set1.equals(set2)) {
3941            return PackageManager.SIGNATURE_MATCH;
3942        }
3943        return PackageManager.SIGNATURE_NO_MATCH;
3944    }
3945
3946    /**
3947     * If the database version for this type of package (internal storage or
3948     * external storage) is less than the version where package signatures
3949     * were updated, return true.
3950     */
3951    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3952        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
3953        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
3954    }
3955
3956    /**
3957     * Used for backward compatibility to make sure any packages with
3958     * certificate chains get upgraded to the new style. {@code existingSigs}
3959     * will be in the old format (since they were stored on disk from before the
3960     * system upgrade) and {@code scannedSigs} will be in the newer format.
3961     */
3962    private int compareSignaturesCompat(PackageSignatures existingSigs,
3963            PackageParser.Package scannedPkg) {
3964        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3965            return PackageManager.SIGNATURE_NO_MATCH;
3966        }
3967
3968        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3969        for (Signature sig : existingSigs.mSignatures) {
3970            existingSet.add(sig);
3971        }
3972        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3973        for (Signature sig : scannedPkg.mSignatures) {
3974            try {
3975                Signature[] chainSignatures = sig.getChainSignatures();
3976                for (Signature chainSig : chainSignatures) {
3977                    scannedCompatSet.add(chainSig);
3978                }
3979            } catch (CertificateEncodingException e) {
3980                scannedCompatSet.add(sig);
3981            }
3982        }
3983        /*
3984         * Make sure the expanded scanned set contains all signatures in the
3985         * existing one.
3986         */
3987        if (scannedCompatSet.equals(existingSet)) {
3988            // Migrate the old signatures to the new scheme.
3989            existingSigs.assignSignatures(scannedPkg.mSignatures);
3990            // The new KeySets will be re-added later in the scanning process.
3991            synchronized (mPackages) {
3992                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3993            }
3994            return PackageManager.SIGNATURE_MATCH;
3995        }
3996        return PackageManager.SIGNATURE_NO_MATCH;
3997    }
3998
3999    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4000        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4001        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4002    }
4003
4004    private int compareSignaturesRecover(PackageSignatures existingSigs,
4005            PackageParser.Package scannedPkg) {
4006        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4007            return PackageManager.SIGNATURE_NO_MATCH;
4008        }
4009
4010        String msg = null;
4011        try {
4012            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4013                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4014                        + scannedPkg.packageName);
4015                return PackageManager.SIGNATURE_MATCH;
4016            }
4017        } catch (CertificateException e) {
4018            msg = e.getMessage();
4019        }
4020
4021        logCriticalInfo(Log.INFO,
4022                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4023        return PackageManager.SIGNATURE_NO_MATCH;
4024    }
4025
4026    @Override
4027    public String[] getPackagesForUid(int uid) {
4028        uid = UserHandle.getAppId(uid);
4029        // reader
4030        synchronized (mPackages) {
4031            Object obj = mSettings.getUserIdLPr(uid);
4032            if (obj instanceof SharedUserSetting) {
4033                final SharedUserSetting sus = (SharedUserSetting) obj;
4034                final int N = sus.packages.size();
4035                final String[] res = new String[N];
4036                final Iterator<PackageSetting> it = sus.packages.iterator();
4037                int i = 0;
4038                while (it.hasNext()) {
4039                    res[i++] = it.next().name;
4040                }
4041                return res;
4042            } else if (obj instanceof PackageSetting) {
4043                final PackageSetting ps = (PackageSetting) obj;
4044                return new String[] { ps.name };
4045            }
4046        }
4047        return null;
4048    }
4049
4050    @Override
4051    public String getNameForUid(int uid) {
4052        // reader
4053        synchronized (mPackages) {
4054            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4055            if (obj instanceof SharedUserSetting) {
4056                final SharedUserSetting sus = (SharedUserSetting) obj;
4057                return sus.name + ":" + sus.userId;
4058            } else if (obj instanceof PackageSetting) {
4059                final PackageSetting ps = (PackageSetting) obj;
4060                return ps.name;
4061            }
4062        }
4063        return null;
4064    }
4065
4066    @Override
4067    public int getUidForSharedUser(String sharedUserName) {
4068        if(sharedUserName == null) {
4069            return -1;
4070        }
4071        // reader
4072        synchronized (mPackages) {
4073            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4074            if (suid == null) {
4075                return -1;
4076            }
4077            return suid.userId;
4078        }
4079    }
4080
4081    @Override
4082    public int getFlagsForUid(int uid) {
4083        synchronized (mPackages) {
4084            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4085            if (obj instanceof SharedUserSetting) {
4086                final SharedUserSetting sus = (SharedUserSetting) obj;
4087                return sus.pkgFlags;
4088            } else if (obj instanceof PackageSetting) {
4089                final PackageSetting ps = (PackageSetting) obj;
4090                return ps.pkgFlags;
4091            }
4092        }
4093        return 0;
4094    }
4095
4096    @Override
4097    public int getPrivateFlagsForUid(int uid) {
4098        synchronized (mPackages) {
4099            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4100            if (obj instanceof SharedUserSetting) {
4101                final SharedUserSetting sus = (SharedUserSetting) obj;
4102                return sus.pkgPrivateFlags;
4103            } else if (obj instanceof PackageSetting) {
4104                final PackageSetting ps = (PackageSetting) obj;
4105                return ps.pkgPrivateFlags;
4106            }
4107        }
4108        return 0;
4109    }
4110
4111    @Override
4112    public boolean isUidPrivileged(int uid) {
4113        uid = UserHandle.getAppId(uid);
4114        // reader
4115        synchronized (mPackages) {
4116            Object obj = mSettings.getUserIdLPr(uid);
4117            if (obj instanceof SharedUserSetting) {
4118                final SharedUserSetting sus = (SharedUserSetting) obj;
4119                final Iterator<PackageSetting> it = sus.packages.iterator();
4120                while (it.hasNext()) {
4121                    if (it.next().isPrivileged()) {
4122                        return true;
4123                    }
4124                }
4125            } else if (obj instanceof PackageSetting) {
4126                final PackageSetting ps = (PackageSetting) obj;
4127                return ps.isPrivileged();
4128            }
4129        }
4130        return false;
4131    }
4132
4133    @Override
4134    public String[] getAppOpPermissionPackages(String permissionName) {
4135        synchronized (mPackages) {
4136            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4137            if (pkgs == null) {
4138                return null;
4139            }
4140            return pkgs.toArray(new String[pkgs.size()]);
4141        }
4142    }
4143
4144    @Override
4145    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4146            int flags, int userId) {
4147        if (!sUserManager.exists(userId)) return null;
4148        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4149        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4150        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4151    }
4152
4153    @Override
4154    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4155            IntentFilter filter, int match, ComponentName activity) {
4156        final int userId = UserHandle.getCallingUserId();
4157        if (DEBUG_PREFERRED) {
4158            Log.v(TAG, "setLastChosenActivity intent=" + intent
4159                + " resolvedType=" + resolvedType
4160                + " flags=" + flags
4161                + " filter=" + filter
4162                + " match=" + match
4163                + " activity=" + activity);
4164            filter.dump(new PrintStreamPrinter(System.out), "    ");
4165        }
4166        intent.setComponent(null);
4167        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4168        // Find any earlier preferred or last chosen entries and nuke them
4169        findPreferredActivity(intent, resolvedType,
4170                flags, query, 0, false, true, false, userId);
4171        // Add the new activity as the last chosen for this filter
4172        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4173                "Setting last chosen");
4174    }
4175
4176    @Override
4177    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4178        final int userId = UserHandle.getCallingUserId();
4179        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4180        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4181        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4182                false, false, false, userId);
4183    }
4184
4185    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4186            int flags, List<ResolveInfo> query, int userId) {
4187        if (query != null) {
4188            final int N = query.size();
4189            if (N == 1) {
4190                return query.get(0);
4191            } else if (N > 1) {
4192                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4193                // If there is more than one activity with the same priority,
4194                // then let the user decide between them.
4195                ResolveInfo r0 = query.get(0);
4196                ResolveInfo r1 = query.get(1);
4197                if (DEBUG_INTENT_MATCHING || debug) {
4198                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4199                            + r1.activityInfo.name + "=" + r1.priority);
4200                }
4201                // If the first activity has a higher priority, or a different
4202                // default, then it is always desireable to pick it.
4203                if (r0.priority != r1.priority
4204                        || r0.preferredOrder != r1.preferredOrder
4205                        || r0.isDefault != r1.isDefault) {
4206                    return query.get(0);
4207                }
4208                // If we have saved a preference for a preferred activity for
4209                // this Intent, use that.
4210                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4211                        flags, query, r0.priority, true, false, debug, userId);
4212                if (ri != null) {
4213                    return ri;
4214                }
4215                if (userId != 0) {
4216                    ri = new ResolveInfo(mResolveInfo);
4217                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
4218                    ri.activityInfo.applicationInfo = new ApplicationInfo(
4219                            ri.activityInfo.applicationInfo);
4220                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4221                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4222                    return ri;
4223                }
4224                return mResolveInfo;
4225            }
4226        }
4227        return null;
4228    }
4229
4230    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4231            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4232        final int N = query.size();
4233        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4234                .get(userId);
4235        // Get the list of persistent preferred activities that handle the intent
4236        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4237        List<PersistentPreferredActivity> pprefs = ppir != null
4238                ? ppir.queryIntent(intent, resolvedType,
4239                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4240                : null;
4241        if (pprefs != null && pprefs.size() > 0) {
4242            final int M = pprefs.size();
4243            for (int i=0; i<M; i++) {
4244                final PersistentPreferredActivity ppa = pprefs.get(i);
4245                if (DEBUG_PREFERRED || debug) {
4246                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4247                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4248                            + "\n  component=" + ppa.mComponent);
4249                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4250                }
4251                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4252                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4253                if (DEBUG_PREFERRED || debug) {
4254                    Slog.v(TAG, "Found persistent preferred activity:");
4255                    if (ai != null) {
4256                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4257                    } else {
4258                        Slog.v(TAG, "  null");
4259                    }
4260                }
4261                if (ai == null) {
4262                    // This previously registered persistent preferred activity
4263                    // component is no longer known. Ignore it and do NOT remove it.
4264                    continue;
4265                }
4266                for (int j=0; j<N; j++) {
4267                    final ResolveInfo ri = query.get(j);
4268                    if (!ri.activityInfo.applicationInfo.packageName
4269                            .equals(ai.applicationInfo.packageName)) {
4270                        continue;
4271                    }
4272                    if (!ri.activityInfo.name.equals(ai.name)) {
4273                        continue;
4274                    }
4275                    //  Found a persistent preference that can handle the intent.
4276                    if (DEBUG_PREFERRED || debug) {
4277                        Slog.v(TAG, "Returning persistent preferred activity: " +
4278                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4279                    }
4280                    return ri;
4281                }
4282            }
4283        }
4284        return null;
4285    }
4286
4287    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4288            List<ResolveInfo> query, int priority, boolean always,
4289            boolean removeMatches, boolean debug, int userId) {
4290        if (!sUserManager.exists(userId)) return null;
4291        // writer
4292        synchronized (mPackages) {
4293            if (intent.getSelector() != null) {
4294                intent = intent.getSelector();
4295            }
4296            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4297
4298            // Try to find a matching persistent preferred activity.
4299            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4300                    debug, userId);
4301
4302            // If a persistent preferred activity matched, use it.
4303            if (pri != null) {
4304                return pri;
4305            }
4306
4307            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4308            // Get the list of preferred activities that handle the intent
4309            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4310            List<PreferredActivity> prefs = pir != null
4311                    ? pir.queryIntent(intent, resolvedType,
4312                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4313                    : null;
4314            if (prefs != null && prefs.size() > 0) {
4315                boolean changed = false;
4316                try {
4317                    // First figure out how good the original match set is.
4318                    // We will only allow preferred activities that came
4319                    // from the same match quality.
4320                    int match = 0;
4321
4322                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4323
4324                    final int N = query.size();
4325                    for (int j=0; j<N; j++) {
4326                        final ResolveInfo ri = query.get(j);
4327                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4328                                + ": 0x" + Integer.toHexString(match));
4329                        if (ri.match > match) {
4330                            match = ri.match;
4331                        }
4332                    }
4333
4334                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4335                            + Integer.toHexString(match));
4336
4337                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4338                    final int M = prefs.size();
4339                    for (int i=0; i<M; i++) {
4340                        final PreferredActivity pa = prefs.get(i);
4341                        if (DEBUG_PREFERRED || debug) {
4342                            Slog.v(TAG, "Checking PreferredActivity ds="
4343                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4344                                    + "\n  component=" + pa.mPref.mComponent);
4345                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4346                        }
4347                        if (pa.mPref.mMatch != match) {
4348                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4349                                    + Integer.toHexString(pa.mPref.mMatch));
4350                            continue;
4351                        }
4352                        // If it's not an "always" type preferred activity and that's what we're
4353                        // looking for, skip it.
4354                        if (always && !pa.mPref.mAlways) {
4355                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4356                            continue;
4357                        }
4358                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4359                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4360                        if (DEBUG_PREFERRED || debug) {
4361                            Slog.v(TAG, "Found preferred activity:");
4362                            if (ai != null) {
4363                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4364                            } else {
4365                                Slog.v(TAG, "  null");
4366                            }
4367                        }
4368                        if (ai == null) {
4369                            // This previously registered preferred activity
4370                            // component is no longer known.  Most likely an update
4371                            // to the app was installed and in the new version this
4372                            // component no longer exists.  Clean it up by removing
4373                            // it from the preferred activities list, and skip it.
4374                            Slog.w(TAG, "Removing dangling preferred activity: "
4375                                    + pa.mPref.mComponent);
4376                            pir.removeFilter(pa);
4377                            changed = true;
4378                            continue;
4379                        }
4380                        for (int j=0; j<N; j++) {
4381                            final ResolveInfo ri = query.get(j);
4382                            if (!ri.activityInfo.applicationInfo.packageName
4383                                    .equals(ai.applicationInfo.packageName)) {
4384                                continue;
4385                            }
4386                            if (!ri.activityInfo.name.equals(ai.name)) {
4387                                continue;
4388                            }
4389
4390                            if (removeMatches) {
4391                                pir.removeFilter(pa);
4392                                changed = true;
4393                                if (DEBUG_PREFERRED) {
4394                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4395                                }
4396                                break;
4397                            }
4398
4399                            // Okay we found a previously set preferred or last chosen app.
4400                            // If the result set is different from when this
4401                            // was created, we need to clear it and re-ask the
4402                            // user their preference, if we're looking for an "always" type entry.
4403                            if (always && !pa.mPref.sameSet(query)) {
4404                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4405                                        + intent + " type " + resolvedType);
4406                                if (DEBUG_PREFERRED) {
4407                                    Slog.v(TAG, "Removing preferred activity since set changed "
4408                                            + pa.mPref.mComponent);
4409                                }
4410                                pir.removeFilter(pa);
4411                                // Re-add the filter as a "last chosen" entry (!always)
4412                                PreferredActivity lastChosen = new PreferredActivity(
4413                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4414                                pir.addFilter(lastChosen);
4415                                changed = true;
4416                                return null;
4417                            }
4418
4419                            // Yay! Either the set matched or we're looking for the last chosen
4420                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4421                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4422                            return ri;
4423                        }
4424                    }
4425                } finally {
4426                    if (changed) {
4427                        if (DEBUG_PREFERRED) {
4428                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4429                        }
4430                        scheduleWritePackageRestrictionsLocked(userId);
4431                    }
4432                }
4433            }
4434        }
4435        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4436        return null;
4437    }
4438
4439    /*
4440     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4441     */
4442    @Override
4443    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4444            int targetUserId) {
4445        mContext.enforceCallingOrSelfPermission(
4446                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4447        List<CrossProfileIntentFilter> matches =
4448                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4449        if (matches != null) {
4450            int size = matches.size();
4451            for (int i = 0; i < size; i++) {
4452                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4453            }
4454        }
4455        if (hasWebURI(intent)) {
4456            // cross-profile app linking works only towards the parent.
4457            final UserInfo parent = getProfileParent(sourceUserId);
4458            synchronized(mPackages) {
4459                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4460                        intent, resolvedType, 0, sourceUserId, parent.id);
4461                return xpDomainInfo != null;
4462            }
4463        }
4464        return false;
4465    }
4466
4467    private UserInfo getProfileParent(int userId) {
4468        final long identity = Binder.clearCallingIdentity();
4469        try {
4470            return sUserManager.getProfileParent(userId);
4471        } finally {
4472            Binder.restoreCallingIdentity(identity);
4473        }
4474    }
4475
4476    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4477            String resolvedType, int userId) {
4478        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4479        if (resolver != null) {
4480            return resolver.queryIntent(intent, resolvedType, false, userId);
4481        }
4482        return null;
4483    }
4484
4485    @Override
4486    public List<ResolveInfo> queryIntentActivities(Intent intent,
4487            String resolvedType, int flags, int userId) {
4488        if (!sUserManager.exists(userId)) return Collections.emptyList();
4489        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4490        ComponentName comp = intent.getComponent();
4491        if (comp == null) {
4492            if (intent.getSelector() != null) {
4493                intent = intent.getSelector();
4494                comp = intent.getComponent();
4495            }
4496        }
4497
4498        if (comp != null) {
4499            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4500            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4501            if (ai != null) {
4502                final ResolveInfo ri = new ResolveInfo();
4503                ri.activityInfo = ai;
4504                list.add(ri);
4505            }
4506            return list;
4507        }
4508
4509        // reader
4510        synchronized (mPackages) {
4511            final String pkgName = intent.getPackage();
4512            if (pkgName == null) {
4513                List<CrossProfileIntentFilter> matchingFilters =
4514                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4515                // Check for results that need to skip the current profile.
4516                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4517                        resolvedType, flags, userId);
4518                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4519                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4520                    result.add(xpResolveInfo);
4521                    return filterIfNotPrimaryUser(result, userId);
4522                }
4523
4524                // Check for results in the current profile.
4525                List<ResolveInfo> result = mActivities.queryIntent(
4526                        intent, resolvedType, flags, userId);
4527
4528                // Check for cross profile results.
4529                xpResolveInfo = queryCrossProfileIntents(
4530                        matchingFilters, intent, resolvedType, flags, userId);
4531                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4532                    result.add(xpResolveInfo);
4533                    Collections.sort(result, mResolvePrioritySorter);
4534                }
4535                result = filterIfNotPrimaryUser(result, userId);
4536                if (hasWebURI(intent)) {
4537                    CrossProfileDomainInfo xpDomainInfo = null;
4538                    final UserInfo parent = getProfileParent(userId);
4539                    if (parent != null) {
4540                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4541                                flags, userId, parent.id);
4542                    }
4543                    if (xpDomainInfo != null) {
4544                        if (xpResolveInfo != null) {
4545                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4546                            // in the result.
4547                            result.remove(xpResolveInfo);
4548                        }
4549                        if (result.size() == 0) {
4550                            result.add(xpDomainInfo.resolveInfo);
4551                            return result;
4552                        }
4553                    } else if (result.size() <= 1) {
4554                        return result;
4555                    }
4556                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4557                            xpDomainInfo, userId);
4558                    Collections.sort(result, mResolvePrioritySorter);
4559                }
4560                return result;
4561            }
4562            final PackageParser.Package pkg = mPackages.get(pkgName);
4563            if (pkg != null) {
4564                return filterIfNotPrimaryUser(
4565                        mActivities.queryIntentForPackage(
4566                                intent, resolvedType, flags, pkg.activities, userId),
4567                        userId);
4568            }
4569            return new ArrayList<ResolveInfo>();
4570        }
4571    }
4572
4573    private static class CrossProfileDomainInfo {
4574        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4575        ResolveInfo resolveInfo;
4576        /* Best domain verification status of the activities found in the other profile */
4577        int bestDomainVerificationStatus;
4578    }
4579
4580    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4581            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4582        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4583                sourceUserId)) {
4584            return null;
4585        }
4586        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4587                resolvedType, flags, parentUserId);
4588
4589        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4590            return null;
4591        }
4592        CrossProfileDomainInfo result = null;
4593        int size = resultTargetUser.size();
4594        for (int i = 0; i < size; i++) {
4595            ResolveInfo riTargetUser = resultTargetUser.get(i);
4596            // Intent filter verification is only for filters that specify a host. So don't return
4597            // those that handle all web uris.
4598            if (riTargetUser.handleAllWebDataURI) {
4599                continue;
4600            }
4601            String packageName = riTargetUser.activityInfo.packageName;
4602            PackageSetting ps = mSettings.mPackages.get(packageName);
4603            if (ps == null) {
4604                continue;
4605            }
4606            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4607            int status = (int)(verificationState >> 32);
4608            if (result == null) {
4609                result = new CrossProfileDomainInfo();
4610                result.resolveInfo =
4611                        createForwardingResolveInfo(null, sourceUserId, parentUserId);
4612                result.bestDomainVerificationStatus = status;
4613            } else {
4614                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4615                        result.bestDomainVerificationStatus);
4616            }
4617        }
4618        // Don't consider matches with status NEVER across profiles.
4619        if (result != null && result.bestDomainVerificationStatus
4620                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4621            return null;
4622        }
4623        return result;
4624    }
4625
4626    /**
4627     * Verification statuses are ordered from the worse to the best, except for
4628     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4629     */
4630    private int bestDomainVerificationStatus(int status1, int status2) {
4631        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4632            return status2;
4633        }
4634        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4635            return status1;
4636        }
4637        return (int) MathUtils.max(status1, status2);
4638    }
4639
4640    private boolean isUserEnabled(int userId) {
4641        long callingId = Binder.clearCallingIdentity();
4642        try {
4643            UserInfo userInfo = sUserManager.getUserInfo(userId);
4644            return userInfo != null && userInfo.isEnabled();
4645        } finally {
4646            Binder.restoreCallingIdentity(callingId);
4647        }
4648    }
4649
4650    /**
4651     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4652     *
4653     * @return filtered list
4654     */
4655    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4656        if (userId == UserHandle.USER_OWNER) {
4657            return resolveInfos;
4658        }
4659        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4660            ResolveInfo info = resolveInfos.get(i);
4661            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4662                resolveInfos.remove(i);
4663            }
4664        }
4665        return resolveInfos;
4666    }
4667
4668    private static boolean hasWebURI(Intent intent) {
4669        if (intent.getData() == null) {
4670            return false;
4671        }
4672        final String scheme = intent.getScheme();
4673        if (TextUtils.isEmpty(scheme)) {
4674            return false;
4675        }
4676        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4677    }
4678
4679    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
4680            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
4681            int userId) {
4682        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
4683
4684        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4685            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
4686                    candidates.size());
4687        }
4688
4689        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4690        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4691        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4692        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4693        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4694
4695        synchronized (mPackages) {
4696            final int count = candidates.size();
4697            // First, try to use linked apps. Partition the candidates into four lists:
4698            // one for the final results, one for the "do not use ever", one for "undefined status"
4699            // and finally one for "browser app type".
4700            for (int n=0; n<count; n++) {
4701                ResolveInfo info = candidates.get(n);
4702                String packageName = info.activityInfo.packageName;
4703                PackageSetting ps = mSettings.mPackages.get(packageName);
4704                if (ps != null) {
4705                    // Add to the special match all list (Browser use case)
4706                    if (info.handleAllWebDataURI) {
4707                        matchAllList.add(info);
4708                        continue;
4709                    }
4710                    // Try to get the status from User settings first
4711                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4712                    int status = (int)(packedStatus >> 32);
4713                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
4714                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4715                        if (DEBUG_DOMAIN_VERIFICATION) {
4716                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
4717                                    + " : linkgen=" + linkGeneration);
4718                        }
4719                        // Use link-enabled generation as preferredOrder, i.e.
4720                        // prefer newly-enabled over earlier-enabled.
4721                        info.preferredOrder = linkGeneration;
4722                        alwaysList.add(info);
4723                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4724                        if (DEBUG_DOMAIN_VERIFICATION) {
4725                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4726                        }
4727                        neverList.add(info);
4728                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4729                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4730                        if (DEBUG_DOMAIN_VERIFICATION) {
4731                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4732                        }
4733                        undefinedList.add(info);
4734                    }
4735                }
4736            }
4737            // First try to add the "always" resolution(s) for the current user, if any
4738            if (alwaysList.size() > 0) {
4739                result.addAll(alwaysList);
4740            // if there is an "always" for the parent user, add it.
4741            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4742                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4743                result.add(xpDomainInfo.resolveInfo);
4744            } else {
4745                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4746                result.addAll(undefinedList);
4747                if (xpDomainInfo != null && (
4748                        xpDomainInfo.bestDomainVerificationStatus
4749                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4750                        || xpDomainInfo.bestDomainVerificationStatus
4751                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4752                    result.add(xpDomainInfo.resolveInfo);
4753                }
4754                // Also add Browsers (all of them or only the default one)
4755                if ((matchFlags & MATCH_ALL) != 0) {
4756                    result.addAll(matchAllList);
4757                } else {
4758                    // Browser/generic handling case.  If there's a default browser, go straight
4759                    // to that (but only if there is no other higher-priority match).
4760                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
4761                    int maxMatchPrio = 0;
4762                    ResolveInfo defaultBrowserMatch = null;
4763                    final int numCandidates = matchAllList.size();
4764                    for (int n = 0; n < numCandidates; n++) {
4765                        ResolveInfo info = matchAllList.get(n);
4766                        // track the highest overall match priority...
4767                        if (info.priority > maxMatchPrio) {
4768                            maxMatchPrio = info.priority;
4769                        }
4770                        // ...and the highest-priority default browser match
4771                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4772                            if (defaultBrowserMatch == null
4773                                    || (defaultBrowserMatch.priority < info.priority)) {
4774                                if (debug) {
4775                                    Slog.v(TAG, "Considering default browser match " + info);
4776                                }
4777                                defaultBrowserMatch = info;
4778                            }
4779                        }
4780                    }
4781                    if (defaultBrowserMatch != null
4782                            && defaultBrowserMatch.priority >= maxMatchPrio
4783                            && !TextUtils.isEmpty(defaultBrowserPackageName))
4784                    {
4785                        if (debug) {
4786                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
4787                        }
4788                        result.add(defaultBrowserMatch);
4789                    } else {
4790                        result.addAll(matchAllList);
4791                    }
4792                }
4793
4794                // If there is nothing selected, add all candidates and remove the ones that the user
4795                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4796                if (result.size() == 0) {
4797                    result.addAll(candidates);
4798                    result.removeAll(neverList);
4799                }
4800            }
4801        }
4802        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4803            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4804                    result.size());
4805            for (ResolveInfo info : result) {
4806                Slog.v(TAG, "  + " + info.activityInfo);
4807            }
4808        }
4809        return result;
4810    }
4811
4812    // Returns a packed value as a long:
4813    //
4814    // high 'int'-sized word: link status: undefined/ask/never/always.
4815    // low 'int'-sized word: relative priority among 'always' results.
4816    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4817        long result = ps.getDomainVerificationStatusForUser(userId);
4818        // if none available, get the master status
4819        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4820            if (ps.getIntentFilterVerificationInfo() != null) {
4821                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
4822            }
4823        }
4824        return result;
4825    }
4826
4827    private ResolveInfo querySkipCurrentProfileIntents(
4828            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4829            int flags, int sourceUserId) {
4830        if (matchingFilters != null) {
4831            int size = matchingFilters.size();
4832            for (int i = 0; i < size; i ++) {
4833                CrossProfileIntentFilter filter = matchingFilters.get(i);
4834                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4835                    // Checking if there are activities in the target user that can handle the
4836                    // intent.
4837                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4838                            flags, sourceUserId);
4839                    if (resolveInfo != null) {
4840                        return resolveInfo;
4841                    }
4842                }
4843            }
4844        }
4845        return null;
4846    }
4847
4848    // Return matching ResolveInfo if any for skip current profile intent filters.
4849    private ResolveInfo queryCrossProfileIntents(
4850            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4851            int flags, int sourceUserId) {
4852        if (matchingFilters != null) {
4853            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4854            // match the same intent. For performance reasons, it is better not to
4855            // run queryIntent twice for the same userId
4856            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4857            int size = matchingFilters.size();
4858            for (int i = 0; i < size; i++) {
4859                CrossProfileIntentFilter filter = matchingFilters.get(i);
4860                int targetUserId = filter.getTargetUserId();
4861                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4862                        && !alreadyTriedUserIds.get(targetUserId)) {
4863                    // Checking if there are activities in the target user that can handle the
4864                    // intent.
4865                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4866                            flags, sourceUserId);
4867                    if (resolveInfo != null) return resolveInfo;
4868                    alreadyTriedUserIds.put(targetUserId, true);
4869                }
4870            }
4871        }
4872        return null;
4873    }
4874
4875    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4876            String resolvedType, int flags, int sourceUserId) {
4877        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4878                resolvedType, flags, filter.getTargetUserId());
4879        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4880            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4881        }
4882        return null;
4883    }
4884
4885    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4886            int sourceUserId, int targetUserId) {
4887        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4888        String className;
4889        if (targetUserId == UserHandle.USER_OWNER) {
4890            className = FORWARD_INTENT_TO_USER_OWNER;
4891        } else {
4892            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4893        }
4894        ComponentName forwardingActivityComponentName = new ComponentName(
4895                mAndroidApplication.packageName, className);
4896        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4897                sourceUserId);
4898        if (targetUserId == UserHandle.USER_OWNER) {
4899            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4900            forwardingResolveInfo.noResourceId = true;
4901        }
4902        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4903        forwardingResolveInfo.priority = 0;
4904        forwardingResolveInfo.preferredOrder = 0;
4905        forwardingResolveInfo.match = 0;
4906        forwardingResolveInfo.isDefault = true;
4907        forwardingResolveInfo.filter = filter;
4908        forwardingResolveInfo.targetUserId = targetUserId;
4909        return forwardingResolveInfo;
4910    }
4911
4912    @Override
4913    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4914            Intent[] specifics, String[] specificTypes, Intent intent,
4915            String resolvedType, int flags, int userId) {
4916        if (!sUserManager.exists(userId)) return Collections.emptyList();
4917        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4918                false, "query intent activity options");
4919        final String resultsAction = intent.getAction();
4920
4921        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4922                | PackageManager.GET_RESOLVED_FILTER, userId);
4923
4924        if (DEBUG_INTENT_MATCHING) {
4925            Log.v(TAG, "Query " + intent + ": " + results);
4926        }
4927
4928        int specificsPos = 0;
4929        int N;
4930
4931        // todo: note that the algorithm used here is O(N^2).  This
4932        // isn't a problem in our current environment, but if we start running
4933        // into situations where we have more than 5 or 10 matches then this
4934        // should probably be changed to something smarter...
4935
4936        // First we go through and resolve each of the specific items
4937        // that were supplied, taking care of removing any corresponding
4938        // duplicate items in the generic resolve list.
4939        if (specifics != null) {
4940            for (int i=0; i<specifics.length; i++) {
4941                final Intent sintent = specifics[i];
4942                if (sintent == null) {
4943                    continue;
4944                }
4945
4946                if (DEBUG_INTENT_MATCHING) {
4947                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4948                }
4949
4950                String action = sintent.getAction();
4951                if (resultsAction != null && resultsAction.equals(action)) {
4952                    // If this action was explicitly requested, then don't
4953                    // remove things that have it.
4954                    action = null;
4955                }
4956
4957                ResolveInfo ri = null;
4958                ActivityInfo ai = null;
4959
4960                ComponentName comp = sintent.getComponent();
4961                if (comp == null) {
4962                    ri = resolveIntent(
4963                        sintent,
4964                        specificTypes != null ? specificTypes[i] : null,
4965                            flags, userId);
4966                    if (ri == null) {
4967                        continue;
4968                    }
4969                    if (ri == mResolveInfo) {
4970                        // ACK!  Must do something better with this.
4971                    }
4972                    ai = ri.activityInfo;
4973                    comp = new ComponentName(ai.applicationInfo.packageName,
4974                            ai.name);
4975                } else {
4976                    ai = getActivityInfo(comp, flags, userId);
4977                    if (ai == null) {
4978                        continue;
4979                    }
4980                }
4981
4982                // Look for any generic query activities that are duplicates
4983                // of this specific one, and remove them from the results.
4984                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4985                N = results.size();
4986                int j;
4987                for (j=specificsPos; j<N; j++) {
4988                    ResolveInfo sri = results.get(j);
4989                    if ((sri.activityInfo.name.equals(comp.getClassName())
4990                            && sri.activityInfo.applicationInfo.packageName.equals(
4991                                    comp.getPackageName()))
4992                        || (action != null && sri.filter.matchAction(action))) {
4993                        results.remove(j);
4994                        if (DEBUG_INTENT_MATCHING) Log.v(
4995                            TAG, "Removing duplicate item from " + j
4996                            + " due to specific " + specificsPos);
4997                        if (ri == null) {
4998                            ri = sri;
4999                        }
5000                        j--;
5001                        N--;
5002                    }
5003                }
5004
5005                // Add this specific item to its proper place.
5006                if (ri == null) {
5007                    ri = new ResolveInfo();
5008                    ri.activityInfo = ai;
5009                }
5010                results.add(specificsPos, ri);
5011                ri.specificIndex = i;
5012                specificsPos++;
5013            }
5014        }
5015
5016        // Now we go through the remaining generic results and remove any
5017        // duplicate actions that are found here.
5018        N = results.size();
5019        for (int i=specificsPos; i<N-1; i++) {
5020            final ResolveInfo rii = results.get(i);
5021            if (rii.filter == null) {
5022                continue;
5023            }
5024
5025            // Iterate over all of the actions of this result's intent
5026            // filter...  typically this should be just one.
5027            final Iterator<String> it = rii.filter.actionsIterator();
5028            if (it == null) {
5029                continue;
5030            }
5031            while (it.hasNext()) {
5032                final String action = it.next();
5033                if (resultsAction != null && resultsAction.equals(action)) {
5034                    // If this action was explicitly requested, then don't
5035                    // remove things that have it.
5036                    continue;
5037                }
5038                for (int j=i+1; j<N; j++) {
5039                    final ResolveInfo rij = results.get(j);
5040                    if (rij.filter != null && rij.filter.hasAction(action)) {
5041                        results.remove(j);
5042                        if (DEBUG_INTENT_MATCHING) Log.v(
5043                            TAG, "Removing duplicate item from " + j
5044                            + " due to action " + action + " at " + i);
5045                        j--;
5046                        N--;
5047                    }
5048                }
5049            }
5050
5051            // If the caller didn't request filter information, drop it now
5052            // so we don't have to marshall/unmarshall it.
5053            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5054                rii.filter = null;
5055            }
5056        }
5057
5058        // Filter out the caller activity if so requested.
5059        if (caller != null) {
5060            N = results.size();
5061            for (int i=0; i<N; i++) {
5062                ActivityInfo ainfo = results.get(i).activityInfo;
5063                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5064                        && caller.getClassName().equals(ainfo.name)) {
5065                    results.remove(i);
5066                    break;
5067                }
5068            }
5069        }
5070
5071        // If the caller didn't request filter information,
5072        // drop them now so we don't have to
5073        // marshall/unmarshall it.
5074        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5075            N = results.size();
5076            for (int i=0; i<N; i++) {
5077                results.get(i).filter = null;
5078            }
5079        }
5080
5081        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5082        return results;
5083    }
5084
5085    @Override
5086    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5087            int userId) {
5088        if (!sUserManager.exists(userId)) return Collections.emptyList();
5089        ComponentName comp = intent.getComponent();
5090        if (comp == null) {
5091            if (intent.getSelector() != null) {
5092                intent = intent.getSelector();
5093                comp = intent.getComponent();
5094            }
5095        }
5096        if (comp != null) {
5097            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5098            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5099            if (ai != null) {
5100                ResolveInfo ri = new ResolveInfo();
5101                ri.activityInfo = ai;
5102                list.add(ri);
5103            }
5104            return list;
5105        }
5106
5107        // reader
5108        synchronized (mPackages) {
5109            String pkgName = intent.getPackage();
5110            if (pkgName == null) {
5111                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5112            }
5113            final PackageParser.Package pkg = mPackages.get(pkgName);
5114            if (pkg != null) {
5115                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5116                        userId);
5117            }
5118            return null;
5119        }
5120    }
5121
5122    @Override
5123    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5124        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5125        if (!sUserManager.exists(userId)) return null;
5126        if (query != null) {
5127            if (query.size() >= 1) {
5128                // If there is more than one service with the same priority,
5129                // just arbitrarily pick the first one.
5130                return query.get(0);
5131            }
5132        }
5133        return null;
5134    }
5135
5136    @Override
5137    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5138            int userId) {
5139        if (!sUserManager.exists(userId)) return Collections.emptyList();
5140        ComponentName comp = intent.getComponent();
5141        if (comp == null) {
5142            if (intent.getSelector() != null) {
5143                intent = intent.getSelector();
5144                comp = intent.getComponent();
5145            }
5146        }
5147        if (comp != null) {
5148            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5149            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5150            if (si != null) {
5151                final ResolveInfo ri = new ResolveInfo();
5152                ri.serviceInfo = si;
5153                list.add(ri);
5154            }
5155            return list;
5156        }
5157
5158        // reader
5159        synchronized (mPackages) {
5160            String pkgName = intent.getPackage();
5161            if (pkgName == null) {
5162                return mServices.queryIntent(intent, resolvedType, flags, userId);
5163            }
5164            final PackageParser.Package pkg = mPackages.get(pkgName);
5165            if (pkg != null) {
5166                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5167                        userId);
5168            }
5169            return null;
5170        }
5171    }
5172
5173    @Override
5174    public List<ResolveInfo> queryIntentContentProviders(
5175            Intent intent, String resolvedType, int flags, int userId) {
5176        if (!sUserManager.exists(userId)) return Collections.emptyList();
5177        ComponentName comp = intent.getComponent();
5178        if (comp == null) {
5179            if (intent.getSelector() != null) {
5180                intent = intent.getSelector();
5181                comp = intent.getComponent();
5182            }
5183        }
5184        if (comp != null) {
5185            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5186            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5187            if (pi != null) {
5188                final ResolveInfo ri = new ResolveInfo();
5189                ri.providerInfo = pi;
5190                list.add(ri);
5191            }
5192            return list;
5193        }
5194
5195        // reader
5196        synchronized (mPackages) {
5197            String pkgName = intent.getPackage();
5198            if (pkgName == null) {
5199                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5200            }
5201            final PackageParser.Package pkg = mPackages.get(pkgName);
5202            if (pkg != null) {
5203                return mProviders.queryIntentForPackage(
5204                        intent, resolvedType, flags, pkg.providers, userId);
5205            }
5206            return null;
5207        }
5208    }
5209
5210    @Override
5211    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5212        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5213
5214        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5215
5216        // writer
5217        synchronized (mPackages) {
5218            ArrayList<PackageInfo> list;
5219            if (listUninstalled) {
5220                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5221                for (PackageSetting ps : mSettings.mPackages.values()) {
5222                    PackageInfo pi;
5223                    if (ps.pkg != null) {
5224                        pi = generatePackageInfo(ps.pkg, flags, userId);
5225                    } else {
5226                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5227                    }
5228                    if (pi != null) {
5229                        list.add(pi);
5230                    }
5231                }
5232            } else {
5233                list = new ArrayList<PackageInfo>(mPackages.size());
5234                for (PackageParser.Package p : mPackages.values()) {
5235                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5236                    if (pi != null) {
5237                        list.add(pi);
5238                    }
5239                }
5240            }
5241
5242            return new ParceledListSlice<PackageInfo>(list);
5243        }
5244    }
5245
5246    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5247            String[] permissions, boolean[] tmp, int flags, int userId) {
5248        int numMatch = 0;
5249        final PermissionsState permissionsState = ps.getPermissionsState();
5250        for (int i=0; i<permissions.length; i++) {
5251            final String permission = permissions[i];
5252            if (permissionsState.hasPermission(permission, userId)) {
5253                tmp[i] = true;
5254                numMatch++;
5255            } else {
5256                tmp[i] = false;
5257            }
5258        }
5259        if (numMatch == 0) {
5260            return;
5261        }
5262        PackageInfo pi;
5263        if (ps.pkg != null) {
5264            pi = generatePackageInfo(ps.pkg, flags, userId);
5265        } else {
5266            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5267        }
5268        // The above might return null in cases of uninstalled apps or install-state
5269        // skew across users/profiles.
5270        if (pi != null) {
5271            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5272                if (numMatch == permissions.length) {
5273                    pi.requestedPermissions = permissions;
5274                } else {
5275                    pi.requestedPermissions = new String[numMatch];
5276                    numMatch = 0;
5277                    for (int i=0; i<permissions.length; i++) {
5278                        if (tmp[i]) {
5279                            pi.requestedPermissions[numMatch] = permissions[i];
5280                            numMatch++;
5281                        }
5282                    }
5283                }
5284            }
5285            list.add(pi);
5286        }
5287    }
5288
5289    @Override
5290    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5291            String[] permissions, int flags, int userId) {
5292        if (!sUserManager.exists(userId)) return null;
5293        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5294
5295        // writer
5296        synchronized (mPackages) {
5297            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5298            boolean[] tmpBools = new boolean[permissions.length];
5299            if (listUninstalled) {
5300                for (PackageSetting ps : mSettings.mPackages.values()) {
5301                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5302                }
5303            } else {
5304                for (PackageParser.Package pkg : mPackages.values()) {
5305                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5306                    if (ps != null) {
5307                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5308                                userId);
5309                    }
5310                }
5311            }
5312
5313            return new ParceledListSlice<PackageInfo>(list);
5314        }
5315    }
5316
5317    @Override
5318    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5319        if (!sUserManager.exists(userId)) return null;
5320        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5321
5322        // writer
5323        synchronized (mPackages) {
5324            ArrayList<ApplicationInfo> list;
5325            if (listUninstalled) {
5326                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5327                for (PackageSetting ps : mSettings.mPackages.values()) {
5328                    ApplicationInfo ai;
5329                    if (ps.pkg != null) {
5330                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5331                                ps.readUserState(userId), userId);
5332                    } else {
5333                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5334                    }
5335                    if (ai != null) {
5336                        list.add(ai);
5337                    }
5338                }
5339            } else {
5340                list = new ArrayList<ApplicationInfo>(mPackages.size());
5341                for (PackageParser.Package p : mPackages.values()) {
5342                    if (p.mExtras != null) {
5343                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5344                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5345                        if (ai != null) {
5346                            list.add(ai);
5347                        }
5348                    }
5349                }
5350            }
5351
5352            return new ParceledListSlice<ApplicationInfo>(list);
5353        }
5354    }
5355
5356    public List<ApplicationInfo> getPersistentApplications(int flags) {
5357        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5358
5359        // reader
5360        synchronized (mPackages) {
5361            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5362            final int userId = UserHandle.getCallingUserId();
5363            while (i.hasNext()) {
5364                final PackageParser.Package p = i.next();
5365                if (p.applicationInfo != null
5366                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5367                        && (!mSafeMode || isSystemApp(p))) {
5368                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5369                    if (ps != null) {
5370                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5371                                ps.readUserState(userId), userId);
5372                        if (ai != null) {
5373                            finalList.add(ai);
5374                        }
5375                    }
5376                }
5377            }
5378        }
5379
5380        return finalList;
5381    }
5382
5383    @Override
5384    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5385        if (!sUserManager.exists(userId)) return null;
5386        // reader
5387        synchronized (mPackages) {
5388            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5389            PackageSetting ps = provider != null
5390                    ? mSettings.mPackages.get(provider.owner.packageName)
5391                    : null;
5392            return ps != null
5393                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5394                    && (!mSafeMode || (provider.info.applicationInfo.flags
5395                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5396                    ? PackageParser.generateProviderInfo(provider, flags,
5397                            ps.readUserState(userId), userId)
5398                    : null;
5399        }
5400    }
5401
5402    /**
5403     * @deprecated
5404     */
5405    @Deprecated
5406    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5407        // reader
5408        synchronized (mPackages) {
5409            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5410                    .entrySet().iterator();
5411            final int userId = UserHandle.getCallingUserId();
5412            while (i.hasNext()) {
5413                Map.Entry<String, PackageParser.Provider> entry = i.next();
5414                PackageParser.Provider p = entry.getValue();
5415                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5416
5417                if (ps != null && p.syncable
5418                        && (!mSafeMode || (p.info.applicationInfo.flags
5419                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5420                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5421                            ps.readUserState(userId), userId);
5422                    if (info != null) {
5423                        outNames.add(entry.getKey());
5424                        outInfo.add(info);
5425                    }
5426                }
5427            }
5428        }
5429    }
5430
5431    @Override
5432    public List<ProviderInfo> queryContentProviders(String processName,
5433            int uid, int flags) {
5434        ArrayList<ProviderInfo> finalList = null;
5435        // reader
5436        synchronized (mPackages) {
5437            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5438            final int userId = processName != null ?
5439                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5440            while (i.hasNext()) {
5441                final PackageParser.Provider p = i.next();
5442                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5443                if (ps != null && p.info.authority != null
5444                        && (processName == null
5445                                || (p.info.processName.equals(processName)
5446                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5447                        && mSettings.isEnabledLPr(p.info, flags, userId)
5448                        && (!mSafeMode
5449                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5450                    if (finalList == null) {
5451                        finalList = new ArrayList<ProviderInfo>(3);
5452                    }
5453                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5454                            ps.readUserState(userId), userId);
5455                    if (info != null) {
5456                        finalList.add(info);
5457                    }
5458                }
5459            }
5460        }
5461
5462        if (finalList != null) {
5463            Collections.sort(finalList, mProviderInitOrderSorter);
5464        }
5465
5466        return finalList;
5467    }
5468
5469    @Override
5470    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5471            int flags) {
5472        // reader
5473        synchronized (mPackages) {
5474            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5475            return PackageParser.generateInstrumentationInfo(i, flags);
5476        }
5477    }
5478
5479    @Override
5480    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5481            int flags) {
5482        ArrayList<InstrumentationInfo> finalList =
5483            new ArrayList<InstrumentationInfo>();
5484
5485        // reader
5486        synchronized (mPackages) {
5487            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5488            while (i.hasNext()) {
5489                final PackageParser.Instrumentation p = i.next();
5490                if (targetPackage == null
5491                        || targetPackage.equals(p.info.targetPackage)) {
5492                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5493                            flags);
5494                    if (ii != null) {
5495                        finalList.add(ii);
5496                    }
5497                }
5498            }
5499        }
5500
5501        return finalList;
5502    }
5503
5504    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5505        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5506        if (overlays == null) {
5507            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5508            return;
5509        }
5510        for (PackageParser.Package opkg : overlays.values()) {
5511            // Not much to do if idmap fails: we already logged the error
5512            // and we certainly don't want to abort installation of pkg simply
5513            // because an overlay didn't fit properly. For these reasons,
5514            // ignore the return value of createIdmapForPackagePairLI.
5515            createIdmapForPackagePairLI(pkg, opkg);
5516        }
5517    }
5518
5519    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5520            PackageParser.Package opkg) {
5521        if (!opkg.mTrustedOverlay) {
5522            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5523                    opkg.baseCodePath + ": overlay not trusted");
5524            return false;
5525        }
5526        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5527        if (overlaySet == null) {
5528            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5529                    opkg.baseCodePath + " but target package has no known overlays");
5530            return false;
5531        }
5532        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5533        // TODO: generate idmap for split APKs
5534        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5535            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5536                    + opkg.baseCodePath);
5537            return false;
5538        }
5539        PackageParser.Package[] overlayArray =
5540            overlaySet.values().toArray(new PackageParser.Package[0]);
5541        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5542            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5543                return p1.mOverlayPriority - p2.mOverlayPriority;
5544            }
5545        };
5546        Arrays.sort(overlayArray, cmp);
5547
5548        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5549        int i = 0;
5550        for (PackageParser.Package p : overlayArray) {
5551            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5552        }
5553        return true;
5554    }
5555
5556    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5557        final File[] files = dir.listFiles();
5558        if (ArrayUtils.isEmpty(files)) {
5559            Log.d(TAG, "No files in app dir " + dir);
5560            return;
5561        }
5562
5563        if (DEBUG_PACKAGE_SCANNING) {
5564            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5565                    + " flags=0x" + Integer.toHexString(parseFlags));
5566        }
5567
5568        for (File file : files) {
5569            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5570                    && !PackageInstallerService.isStageName(file.getName());
5571            if (!isPackage) {
5572                // Ignore entries which are not packages
5573                continue;
5574            }
5575            try {
5576                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5577                        scanFlags, currentTime, null);
5578            } catch (PackageManagerException e) {
5579                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5580
5581                // Delete invalid userdata apps
5582                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5583                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5584                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5585                    if (file.isDirectory()) {
5586                        mInstaller.rmPackageDir(file.getAbsolutePath());
5587                    } else {
5588                        file.delete();
5589                    }
5590                }
5591            }
5592        }
5593    }
5594
5595    private static File getSettingsProblemFile() {
5596        File dataDir = Environment.getDataDirectory();
5597        File systemDir = new File(dataDir, "system");
5598        File fname = new File(systemDir, "uiderrors.txt");
5599        return fname;
5600    }
5601
5602    static void reportSettingsProblem(int priority, String msg) {
5603        logCriticalInfo(priority, msg);
5604    }
5605
5606    static void logCriticalInfo(int priority, String msg) {
5607        Slog.println(priority, TAG, msg);
5608        EventLogTags.writePmCriticalInfo(msg);
5609        try {
5610            File fname = getSettingsProblemFile();
5611            FileOutputStream out = new FileOutputStream(fname, true);
5612            PrintWriter pw = new FastPrintWriter(out);
5613            SimpleDateFormat formatter = new SimpleDateFormat();
5614            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5615            pw.println(dateString + ": " + msg);
5616            pw.close();
5617            FileUtils.setPermissions(
5618                    fname.toString(),
5619                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5620                    -1, -1);
5621        } catch (java.io.IOException e) {
5622        }
5623    }
5624
5625    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5626            PackageParser.Package pkg, File srcFile, int parseFlags)
5627            throws PackageManagerException {
5628        if (ps != null
5629                && ps.codePath.equals(srcFile)
5630                && ps.timeStamp == srcFile.lastModified()
5631                && !isCompatSignatureUpdateNeeded(pkg)
5632                && !isRecoverSignatureUpdateNeeded(pkg)) {
5633            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5634            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5635            ArraySet<PublicKey> signingKs;
5636            synchronized (mPackages) {
5637                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5638            }
5639            if (ps.signatures.mSignatures != null
5640                    && ps.signatures.mSignatures.length != 0
5641                    && signingKs != null) {
5642                // Optimization: reuse the existing cached certificates
5643                // if the package appears to be unchanged.
5644                pkg.mSignatures = ps.signatures.mSignatures;
5645                pkg.mSigningKeys = signingKs;
5646                return;
5647            }
5648
5649            Slog.w(TAG, "PackageSetting for " + ps.name
5650                    + " is missing signatures.  Collecting certs again to recover them.");
5651        } else {
5652            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5653        }
5654
5655        try {
5656            pp.collectCertificates(pkg, parseFlags);
5657            pp.collectManifestDigest(pkg);
5658        } catch (PackageParserException e) {
5659            throw PackageManagerException.from(e);
5660        }
5661    }
5662
5663    /*
5664     *  Scan a package and return the newly parsed package.
5665     *  Returns null in case of errors and the error code is stored in mLastScanError
5666     */
5667    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5668            long currentTime, UserHandle user) throws PackageManagerException {
5669        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5670        parseFlags |= mDefParseFlags;
5671        PackageParser pp = new PackageParser();
5672        pp.setSeparateProcesses(mSeparateProcesses);
5673        pp.setOnlyCoreApps(mOnlyCore);
5674        pp.setDisplayMetrics(mMetrics);
5675
5676        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5677            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5678        }
5679
5680        final PackageParser.Package pkg;
5681        try {
5682            pkg = pp.parsePackage(scanFile, parseFlags);
5683        } catch (PackageParserException e) {
5684            throw PackageManagerException.from(e);
5685        }
5686
5687        PackageSetting ps = null;
5688        PackageSetting updatedPkg;
5689        // reader
5690        synchronized (mPackages) {
5691            // Look to see if we already know about this package.
5692            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5693            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5694                // This package has been renamed to its original name.  Let's
5695                // use that.
5696                ps = mSettings.peekPackageLPr(oldName);
5697            }
5698            // If there was no original package, see one for the real package name.
5699            if (ps == null) {
5700                ps = mSettings.peekPackageLPr(pkg.packageName);
5701            }
5702            // Check to see if this package could be hiding/updating a system
5703            // package.  Must look for it either under the original or real
5704            // package name depending on our state.
5705            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5706            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5707        }
5708        boolean updatedPkgBetter = false;
5709        // First check if this is a system package that may involve an update
5710        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5711            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5712            // it needs to drop FLAG_PRIVILEGED.
5713            if (locationIsPrivileged(scanFile)) {
5714                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5715            } else {
5716                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5717            }
5718
5719            if (ps != null && !ps.codePath.equals(scanFile)) {
5720                // The path has changed from what was last scanned...  check the
5721                // version of the new path against what we have stored to determine
5722                // what to do.
5723                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5724                if (pkg.mVersionCode <= ps.versionCode) {
5725                    // The system package has been updated and the code path does not match
5726                    // Ignore entry. Skip it.
5727                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5728                            + " ignored: updated version " + ps.versionCode
5729                            + " better than this " + pkg.mVersionCode);
5730                    if (!updatedPkg.codePath.equals(scanFile)) {
5731                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5732                                + ps.name + " changing from " + updatedPkg.codePathString
5733                                + " to " + scanFile);
5734                        updatedPkg.codePath = scanFile;
5735                        updatedPkg.codePathString = scanFile.toString();
5736                        updatedPkg.resourcePath = scanFile;
5737                        updatedPkg.resourcePathString = scanFile.toString();
5738                    }
5739                    updatedPkg.pkg = pkg;
5740                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5741                            "Package " + ps.name + " at " + scanFile
5742                                    + " ignored: updated version " + ps.versionCode
5743                                    + " better than this " + pkg.mVersionCode);
5744                } else {
5745                    // The current app on the system partition is better than
5746                    // what we have updated to on the data partition; switch
5747                    // back to the system partition version.
5748                    // At this point, its safely assumed that package installation for
5749                    // apps in system partition will go through. If not there won't be a working
5750                    // version of the app
5751                    // writer
5752                    synchronized (mPackages) {
5753                        // Just remove the loaded entries from package lists.
5754                        mPackages.remove(ps.name);
5755                    }
5756
5757                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5758                            + " reverting from " + ps.codePathString
5759                            + ": new version " + pkg.mVersionCode
5760                            + " better than installed " + ps.versionCode);
5761
5762                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5763                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5764                    synchronized (mInstallLock) {
5765                        args.cleanUpResourcesLI();
5766                    }
5767                    synchronized (mPackages) {
5768                        mSettings.enableSystemPackageLPw(ps.name);
5769                    }
5770                    updatedPkgBetter = true;
5771                }
5772            }
5773        }
5774
5775        if (updatedPkg != null) {
5776            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5777            // initially
5778            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5779
5780            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5781            // flag set initially
5782            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5783                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5784            }
5785        }
5786
5787        // Verify certificates against what was last scanned
5788        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5789
5790        /*
5791         * A new system app appeared, but we already had a non-system one of the
5792         * same name installed earlier.
5793         */
5794        boolean shouldHideSystemApp = false;
5795        if (updatedPkg == null && ps != null
5796                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5797            /*
5798             * Check to make sure the signatures match first. If they don't,
5799             * wipe the installed application and its data.
5800             */
5801            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5802                    != PackageManager.SIGNATURE_MATCH) {
5803                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5804                        + " signatures don't match existing userdata copy; removing");
5805                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5806                ps = null;
5807            } else {
5808                /*
5809                 * If the newly-added system app is an older version than the
5810                 * already installed version, hide it. It will be scanned later
5811                 * and re-added like an update.
5812                 */
5813                if (pkg.mVersionCode <= ps.versionCode) {
5814                    shouldHideSystemApp = true;
5815                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5816                            + " but new version " + pkg.mVersionCode + " better than installed "
5817                            + ps.versionCode + "; hiding system");
5818                } else {
5819                    /*
5820                     * The newly found system app is a newer version that the
5821                     * one previously installed. Simply remove the
5822                     * already-installed application and replace it with our own
5823                     * while keeping the application data.
5824                     */
5825                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5826                            + " reverting from " + ps.codePathString + ": new version "
5827                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5828                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5829                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5830                    synchronized (mInstallLock) {
5831                        args.cleanUpResourcesLI();
5832                    }
5833                }
5834            }
5835        }
5836
5837        // The apk is forward locked (not public) if its code and resources
5838        // are kept in different files. (except for app in either system or
5839        // vendor path).
5840        // TODO grab this value from PackageSettings
5841        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5842            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5843                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5844            }
5845        }
5846
5847        // TODO: extend to support forward-locked splits
5848        String resourcePath = null;
5849        String baseResourcePath = null;
5850        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5851            if (ps != null && ps.resourcePathString != null) {
5852                resourcePath = ps.resourcePathString;
5853                baseResourcePath = ps.resourcePathString;
5854            } else {
5855                // Should not happen at all. Just log an error.
5856                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5857            }
5858        } else {
5859            resourcePath = pkg.codePath;
5860            baseResourcePath = pkg.baseCodePath;
5861        }
5862
5863        // Set application objects path explicitly.
5864        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5865        pkg.applicationInfo.setCodePath(pkg.codePath);
5866        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5867        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5868        pkg.applicationInfo.setResourcePath(resourcePath);
5869        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5870        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5871
5872        // Note that we invoke the following method only if we are about to unpack an application
5873        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5874                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5875
5876        /*
5877         * If the system app should be overridden by a previously installed
5878         * data, hide the system app now and let the /data/app scan pick it up
5879         * again.
5880         */
5881        if (shouldHideSystemApp) {
5882            synchronized (mPackages) {
5883                /*
5884                 * We have to grant systems permissions before we hide, because
5885                 * grantPermissions will assume the package update is trying to
5886                 * expand its permissions.
5887                 */
5888                grantPermissionsLPw(pkg, true, pkg.packageName);
5889                mSettings.disableSystemPackageLPw(pkg.packageName);
5890            }
5891        }
5892
5893        return scannedPkg;
5894    }
5895
5896    private static String fixProcessName(String defProcessName,
5897            String processName, int uid) {
5898        if (processName == null) {
5899            return defProcessName;
5900        }
5901        return processName;
5902    }
5903
5904    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5905            throws PackageManagerException {
5906        if (pkgSetting.signatures.mSignatures != null) {
5907            // Already existing package. Make sure signatures match
5908            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5909                    == PackageManager.SIGNATURE_MATCH;
5910            if (!match) {
5911                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5912                        == PackageManager.SIGNATURE_MATCH;
5913            }
5914            if (!match) {
5915                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5916                        == PackageManager.SIGNATURE_MATCH;
5917            }
5918            if (!match) {
5919                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5920                        + pkg.packageName + " signatures do not match the "
5921                        + "previously installed version; ignoring!");
5922            }
5923        }
5924
5925        // Check for shared user signatures
5926        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5927            // Already existing package. Make sure signatures match
5928            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5929                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5930            if (!match) {
5931                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5932                        == PackageManager.SIGNATURE_MATCH;
5933            }
5934            if (!match) {
5935                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5936                        == PackageManager.SIGNATURE_MATCH;
5937            }
5938            if (!match) {
5939                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5940                        "Package " + pkg.packageName
5941                        + " has no signatures that match those in shared user "
5942                        + pkgSetting.sharedUser.name + "; ignoring!");
5943            }
5944        }
5945    }
5946
5947    /**
5948     * Enforces that only the system UID or root's UID can call a method exposed
5949     * via Binder.
5950     *
5951     * @param message used as message if SecurityException is thrown
5952     * @throws SecurityException if the caller is not system or root
5953     */
5954    private static final void enforceSystemOrRoot(String message) {
5955        final int uid = Binder.getCallingUid();
5956        if (uid != Process.SYSTEM_UID && uid != 0) {
5957            throw new SecurityException(message);
5958        }
5959    }
5960
5961    @Override
5962    public void performBootDexOpt() {
5963        enforceSystemOrRoot("Only the system can request dexopt be performed");
5964
5965        // Before everything else, see whether we need to fstrim.
5966        try {
5967            IMountService ms = PackageHelper.getMountService();
5968            if (ms != null) {
5969                final boolean isUpgrade = isUpgrade();
5970                boolean doTrim = isUpgrade;
5971                if (doTrim) {
5972                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5973                } else {
5974                    final long interval = android.provider.Settings.Global.getLong(
5975                            mContext.getContentResolver(),
5976                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5977                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5978                    if (interval > 0) {
5979                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5980                        if (timeSinceLast > interval) {
5981                            doTrim = true;
5982                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5983                                    + "; running immediately");
5984                        }
5985                    }
5986                }
5987                if (doTrim) {
5988                    if (!isFirstBoot()) {
5989                        try {
5990                            ActivityManagerNative.getDefault().showBootMessage(
5991                                    mContext.getResources().getString(
5992                                            R.string.android_upgrading_fstrim), true);
5993                        } catch (RemoteException e) {
5994                        }
5995                    }
5996                    ms.runMaintenance();
5997                }
5998            } else {
5999                Slog.e(TAG, "Mount service unavailable!");
6000            }
6001        } catch (RemoteException e) {
6002            // Can't happen; MountService is local
6003        }
6004
6005        final ArraySet<PackageParser.Package> pkgs;
6006        synchronized (mPackages) {
6007            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
6008        }
6009
6010        if (pkgs != null) {
6011            // Sort apps by importance for dexopt ordering. Important apps are given more priority
6012            // in case the device runs out of space.
6013            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
6014            // Give priority to core apps.
6015            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6016                PackageParser.Package pkg = it.next();
6017                if (pkg.coreApp) {
6018                    if (DEBUG_DEXOPT) {
6019                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
6020                    }
6021                    sortedPkgs.add(pkg);
6022                    it.remove();
6023                }
6024            }
6025            // Give priority to system apps that listen for pre boot complete.
6026            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
6027            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
6028            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6029                PackageParser.Package pkg = it.next();
6030                if (pkgNames.contains(pkg.packageName)) {
6031                    if (DEBUG_DEXOPT) {
6032                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
6033                    }
6034                    sortedPkgs.add(pkg);
6035                    it.remove();
6036                }
6037            }
6038            // Give priority to system apps.
6039            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6040                PackageParser.Package pkg = it.next();
6041                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
6042                    if (DEBUG_DEXOPT) {
6043                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
6044                    }
6045                    sortedPkgs.add(pkg);
6046                    it.remove();
6047                }
6048            }
6049            // Give priority to updated system apps.
6050            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6051                PackageParser.Package pkg = it.next();
6052                if (pkg.isUpdatedSystemApp()) {
6053                    if (DEBUG_DEXOPT) {
6054                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
6055                    }
6056                    sortedPkgs.add(pkg);
6057                    it.remove();
6058                }
6059            }
6060            // Give priority to apps that listen for boot complete.
6061            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
6062            pkgNames = getPackageNamesForIntent(intent);
6063            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6064                PackageParser.Package pkg = it.next();
6065                if (pkgNames.contains(pkg.packageName)) {
6066                    if (DEBUG_DEXOPT) {
6067                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
6068                    }
6069                    sortedPkgs.add(pkg);
6070                    it.remove();
6071                }
6072            }
6073            // Filter out packages that aren't recently used.
6074            filterRecentlyUsedApps(pkgs);
6075            // Add all remaining apps.
6076            for (PackageParser.Package pkg : pkgs) {
6077                if (DEBUG_DEXOPT) {
6078                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
6079                }
6080                sortedPkgs.add(pkg);
6081            }
6082
6083            // If we want to be lazy, filter everything that wasn't recently used.
6084            if (mLazyDexOpt) {
6085                filterRecentlyUsedApps(sortedPkgs);
6086            }
6087
6088            int i = 0;
6089            int total = sortedPkgs.size();
6090            File dataDir = Environment.getDataDirectory();
6091            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
6092            if (lowThreshold == 0) {
6093                throw new IllegalStateException("Invalid low memory threshold");
6094            }
6095            for (PackageParser.Package pkg : sortedPkgs) {
6096                long usableSpace = dataDir.getUsableSpace();
6097                if (usableSpace < lowThreshold) {
6098                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
6099                    break;
6100                }
6101                performBootDexOpt(pkg, ++i, total);
6102            }
6103        }
6104    }
6105
6106    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
6107        // Filter out packages that aren't recently used.
6108        //
6109        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
6110        // should do a full dexopt.
6111        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
6112            int total = pkgs.size();
6113            int skipped = 0;
6114            long now = System.currentTimeMillis();
6115            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
6116                PackageParser.Package pkg = i.next();
6117                long then = pkg.mLastPackageUsageTimeInMills;
6118                if (then + mDexOptLRUThresholdInMills < now) {
6119                    if (DEBUG_DEXOPT) {
6120                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
6121                              ((then == 0) ? "never" : new Date(then)));
6122                    }
6123                    i.remove();
6124                    skipped++;
6125                }
6126            }
6127            if (DEBUG_DEXOPT) {
6128                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
6129            }
6130        }
6131    }
6132
6133    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
6134        List<ResolveInfo> ris = null;
6135        try {
6136            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6137                    intent, null, 0, UserHandle.USER_OWNER);
6138        } catch (RemoteException e) {
6139        }
6140        ArraySet<String> pkgNames = new ArraySet<String>();
6141        if (ris != null) {
6142            for (ResolveInfo ri : ris) {
6143                pkgNames.add(ri.activityInfo.packageName);
6144            }
6145        }
6146        return pkgNames;
6147    }
6148
6149    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6150        if (DEBUG_DEXOPT) {
6151            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6152        }
6153        if (!isFirstBoot()) {
6154            try {
6155                ActivityManagerNative.getDefault().showBootMessage(
6156                        mContext.getResources().getString(R.string.android_upgrading_apk,
6157                                curr, total), true);
6158            } catch (RemoteException e) {
6159            }
6160        }
6161        PackageParser.Package p = pkg;
6162        synchronized (mInstallLock) {
6163            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6164                    false /* force dex */, false /* defer */, true /* include dependencies */);
6165        }
6166    }
6167
6168    @Override
6169    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6170        return performDexOpt(packageName, instructionSet, false);
6171    }
6172
6173    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
6174        boolean dexopt = mLazyDexOpt || backgroundDexopt;
6175        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6176        if (!dexopt && !updateUsage) {
6177            // We aren't going to dexopt or update usage, so bail early.
6178            return false;
6179        }
6180        PackageParser.Package p;
6181        final String targetInstructionSet;
6182        synchronized (mPackages) {
6183            p = mPackages.get(packageName);
6184            if (p == null) {
6185                return false;
6186            }
6187            if (updateUsage) {
6188                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6189            }
6190            mPackageUsage.write(false);
6191            if (!dexopt) {
6192                // We aren't going to dexopt, so bail early.
6193                return false;
6194            }
6195
6196            targetInstructionSet = instructionSet != null ? instructionSet :
6197                    getPrimaryInstructionSet(p.applicationInfo);
6198            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6199                return false;
6200            }
6201        }
6202        long callingId = Binder.clearCallingIdentity();
6203        try {
6204            synchronized (mInstallLock) {
6205                final String[] instructionSets = new String[] { targetInstructionSet };
6206                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6207                        false /* forceDex */, false /* defer */, true /* inclDependencies */);
6208                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6209            }
6210        } finally {
6211            Binder.restoreCallingIdentity(callingId);
6212        }
6213    }
6214
6215    public ArraySet<String> getPackagesThatNeedDexOpt() {
6216        ArraySet<String> pkgs = null;
6217        synchronized (mPackages) {
6218            for (PackageParser.Package p : mPackages.values()) {
6219                if (DEBUG_DEXOPT) {
6220                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6221                }
6222                if (!p.mDexOptPerformed.isEmpty()) {
6223                    continue;
6224                }
6225                if (pkgs == null) {
6226                    pkgs = new ArraySet<String>();
6227                }
6228                pkgs.add(p.packageName);
6229            }
6230        }
6231        return pkgs;
6232    }
6233
6234    public void shutdown() {
6235        mPackageUsage.write(true);
6236    }
6237
6238    @Override
6239    public void forceDexOpt(String packageName) {
6240        enforceSystemOrRoot("forceDexOpt");
6241
6242        PackageParser.Package pkg;
6243        synchronized (mPackages) {
6244            pkg = mPackages.get(packageName);
6245            if (pkg == null) {
6246                throw new IllegalArgumentException("Missing package: " + packageName);
6247            }
6248        }
6249
6250        synchronized (mInstallLock) {
6251            final String[] instructionSets = new String[] {
6252                    getPrimaryInstructionSet(pkg.applicationInfo) };
6253            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6254                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
6255            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6256                throw new IllegalStateException("Failed to dexopt: " + res);
6257            }
6258        }
6259    }
6260
6261    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6262        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6263            Slog.w(TAG, "Unable to update from " + oldPkg.name
6264                    + " to " + newPkg.packageName
6265                    + ": old package not in system partition");
6266            return false;
6267        } else if (mPackages.get(oldPkg.name) != null) {
6268            Slog.w(TAG, "Unable to update from " + oldPkg.name
6269                    + " to " + newPkg.packageName
6270                    + ": old package still exists");
6271            return false;
6272        }
6273        return true;
6274    }
6275
6276    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6277        int[] users = sUserManager.getUserIds();
6278        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6279        if (res < 0) {
6280            return res;
6281        }
6282        for (int user : users) {
6283            if (user != 0) {
6284                res = mInstaller.createUserData(volumeUuid, packageName,
6285                        UserHandle.getUid(user, uid), user, seinfo);
6286                if (res < 0) {
6287                    return res;
6288                }
6289            }
6290        }
6291        return res;
6292    }
6293
6294    private int removeDataDirsLI(String volumeUuid, String packageName) {
6295        int[] users = sUserManager.getUserIds();
6296        int res = 0;
6297        for (int user : users) {
6298            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6299            if (resInner < 0) {
6300                res = resInner;
6301            }
6302        }
6303
6304        return res;
6305    }
6306
6307    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6308        int[] users = sUserManager.getUserIds();
6309        int res = 0;
6310        for (int user : users) {
6311            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6312            if (resInner < 0) {
6313                res = resInner;
6314            }
6315        }
6316        return res;
6317    }
6318
6319    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6320            PackageParser.Package changingLib) {
6321        if (file.path != null) {
6322            usesLibraryFiles.add(file.path);
6323            return;
6324        }
6325        PackageParser.Package p = mPackages.get(file.apk);
6326        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6327            // If we are doing this while in the middle of updating a library apk,
6328            // then we need to make sure to use that new apk for determining the
6329            // dependencies here.  (We haven't yet finished committing the new apk
6330            // to the package manager state.)
6331            if (p == null || p.packageName.equals(changingLib.packageName)) {
6332                p = changingLib;
6333            }
6334        }
6335        if (p != null) {
6336            usesLibraryFiles.addAll(p.getAllCodePaths());
6337        }
6338    }
6339
6340    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6341            PackageParser.Package changingLib) throws PackageManagerException {
6342        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6343            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6344            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6345            for (int i=0; i<N; i++) {
6346                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6347                if (file == null) {
6348                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6349                            "Package " + pkg.packageName + " requires unavailable shared library "
6350                            + pkg.usesLibraries.get(i) + "; failing!");
6351                }
6352                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6353            }
6354            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6355            for (int i=0; i<N; i++) {
6356                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6357                if (file == null) {
6358                    Slog.w(TAG, "Package " + pkg.packageName
6359                            + " desires unavailable shared library "
6360                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6361                } else {
6362                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6363                }
6364            }
6365            N = usesLibraryFiles.size();
6366            if (N > 0) {
6367                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6368            } else {
6369                pkg.usesLibraryFiles = null;
6370            }
6371        }
6372    }
6373
6374    private static boolean hasString(List<String> list, List<String> which) {
6375        if (list == null) {
6376            return false;
6377        }
6378        for (int i=list.size()-1; i>=0; i--) {
6379            for (int j=which.size()-1; j>=0; j--) {
6380                if (which.get(j).equals(list.get(i))) {
6381                    return true;
6382                }
6383            }
6384        }
6385        return false;
6386    }
6387
6388    private void updateAllSharedLibrariesLPw() {
6389        for (PackageParser.Package pkg : mPackages.values()) {
6390            try {
6391                updateSharedLibrariesLPw(pkg, null);
6392            } catch (PackageManagerException e) {
6393                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6394            }
6395        }
6396    }
6397
6398    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6399            PackageParser.Package changingPkg) {
6400        ArrayList<PackageParser.Package> res = null;
6401        for (PackageParser.Package pkg : mPackages.values()) {
6402            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6403                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6404                if (res == null) {
6405                    res = new ArrayList<PackageParser.Package>();
6406                }
6407                res.add(pkg);
6408                try {
6409                    updateSharedLibrariesLPw(pkg, changingPkg);
6410                } catch (PackageManagerException e) {
6411                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6412                }
6413            }
6414        }
6415        return res;
6416    }
6417
6418    /**
6419     * Derive the value of the {@code cpuAbiOverride} based on the provided
6420     * value and an optional stored value from the package settings.
6421     */
6422    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6423        String cpuAbiOverride = null;
6424
6425        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6426            cpuAbiOverride = null;
6427        } else if (abiOverride != null) {
6428            cpuAbiOverride = abiOverride;
6429        } else if (settings != null) {
6430            cpuAbiOverride = settings.cpuAbiOverrideString;
6431        }
6432
6433        return cpuAbiOverride;
6434    }
6435
6436    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6437            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6438        boolean success = false;
6439        try {
6440            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6441                    currentTime, user);
6442            success = true;
6443            return res;
6444        } finally {
6445            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6446                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6447            }
6448        }
6449    }
6450
6451    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6452            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6453        final File scanFile = new File(pkg.codePath);
6454        if (pkg.applicationInfo.getCodePath() == null ||
6455                pkg.applicationInfo.getResourcePath() == null) {
6456            // Bail out. The resource and code paths haven't been set.
6457            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6458                    "Code and resource paths haven't been set correctly");
6459        }
6460
6461        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6462            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6463        } else {
6464            // Only allow system apps to be flagged as core apps.
6465            pkg.coreApp = false;
6466        }
6467
6468        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6469            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6470        }
6471
6472        if (mCustomResolverComponentName != null &&
6473                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6474            setUpCustomResolverActivity(pkg);
6475        }
6476
6477        if (pkg.packageName.equals("android")) {
6478            synchronized (mPackages) {
6479                if (mAndroidApplication != null) {
6480                    Slog.w(TAG, "*************************************************");
6481                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6482                    Slog.w(TAG, " file=" + scanFile);
6483                    Slog.w(TAG, "*************************************************");
6484                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6485                            "Core android package being redefined.  Skipping.");
6486                }
6487
6488                // Set up information for our fall-back user intent resolution activity.
6489                mPlatformPackage = pkg;
6490                pkg.mVersionCode = mSdkVersion;
6491                mAndroidApplication = pkg.applicationInfo;
6492
6493                if (!mResolverReplaced) {
6494                    mResolveActivity.applicationInfo = mAndroidApplication;
6495                    mResolveActivity.name = ResolverActivity.class.getName();
6496                    mResolveActivity.packageName = mAndroidApplication.packageName;
6497                    mResolveActivity.processName = "system:ui";
6498                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6499                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6500                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6501                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6502                    mResolveActivity.exported = true;
6503                    mResolveActivity.enabled = true;
6504                    mResolveInfo.activityInfo = mResolveActivity;
6505                    mResolveInfo.priority = 0;
6506                    mResolveInfo.preferredOrder = 0;
6507                    mResolveInfo.match = 0;
6508                    mResolveComponentName = new ComponentName(
6509                            mAndroidApplication.packageName, mResolveActivity.name);
6510                }
6511            }
6512        }
6513
6514        if (DEBUG_PACKAGE_SCANNING) {
6515            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6516                Log.d(TAG, "Scanning package " + pkg.packageName);
6517        }
6518
6519        if (mPackages.containsKey(pkg.packageName)
6520                || mSharedLibraries.containsKey(pkg.packageName)) {
6521            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6522                    "Application package " + pkg.packageName
6523                    + " already installed.  Skipping duplicate.");
6524        }
6525
6526        // If we're only installing presumed-existing packages, require that the
6527        // scanned APK is both already known and at the path previously established
6528        // for it.  Previously unknown packages we pick up normally, but if we have an
6529        // a priori expectation about this package's install presence, enforce it.
6530        // With a singular exception for new system packages. When an OTA contains
6531        // a new system package, we allow the codepath to change from a system location
6532        // to the user-installed location. If we don't allow this change, any newer,
6533        // user-installed version of the application will be ignored.
6534        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6535            if (mExpectingBetter.containsKey(pkg.packageName)) {
6536                logCriticalInfo(Log.WARN,
6537                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6538            } else {
6539                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6540                if (known != null) {
6541                    if (DEBUG_PACKAGE_SCANNING) {
6542                        Log.d(TAG, "Examining " + pkg.codePath
6543                                + " and requiring known paths " + known.codePathString
6544                                + " & " + known.resourcePathString);
6545                    }
6546                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6547                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6548                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6549                                "Application package " + pkg.packageName
6550                                + " found at " + pkg.applicationInfo.getCodePath()
6551                                + " but expected at " + known.codePathString + "; ignoring.");
6552                    }
6553                }
6554            }
6555        }
6556
6557        // Initialize package source and resource directories
6558        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6559        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6560
6561        SharedUserSetting suid = null;
6562        PackageSetting pkgSetting = null;
6563
6564        if (!isSystemApp(pkg)) {
6565            // Only system apps can use these features.
6566            pkg.mOriginalPackages = null;
6567            pkg.mRealPackage = null;
6568            pkg.mAdoptPermissions = null;
6569        }
6570
6571        // writer
6572        synchronized (mPackages) {
6573            if (pkg.mSharedUserId != null) {
6574                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6575                if (suid == null) {
6576                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6577                            "Creating application package " + pkg.packageName
6578                            + " for shared user failed");
6579                }
6580                if (DEBUG_PACKAGE_SCANNING) {
6581                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6582                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6583                                + "): packages=" + suid.packages);
6584                }
6585            }
6586
6587            // Check if we are renaming from an original package name.
6588            PackageSetting origPackage = null;
6589            String realName = null;
6590            if (pkg.mOriginalPackages != null) {
6591                // This package may need to be renamed to a previously
6592                // installed name.  Let's check on that...
6593                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6594                if (pkg.mOriginalPackages.contains(renamed)) {
6595                    // This package had originally been installed as the
6596                    // original name, and we have already taken care of
6597                    // transitioning to the new one.  Just update the new
6598                    // one to continue using the old name.
6599                    realName = pkg.mRealPackage;
6600                    if (!pkg.packageName.equals(renamed)) {
6601                        // Callers into this function may have already taken
6602                        // care of renaming the package; only do it here if
6603                        // it is not already done.
6604                        pkg.setPackageName(renamed);
6605                    }
6606
6607                } else {
6608                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6609                        if ((origPackage = mSettings.peekPackageLPr(
6610                                pkg.mOriginalPackages.get(i))) != null) {
6611                            // We do have the package already installed under its
6612                            // original name...  should we use it?
6613                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6614                                // New package is not compatible with original.
6615                                origPackage = null;
6616                                continue;
6617                            } else if (origPackage.sharedUser != null) {
6618                                // Make sure uid is compatible between packages.
6619                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6620                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6621                                            + " to " + pkg.packageName + ": old uid "
6622                                            + origPackage.sharedUser.name
6623                                            + " differs from " + pkg.mSharedUserId);
6624                                    origPackage = null;
6625                                    continue;
6626                                }
6627                            } else {
6628                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6629                                        + pkg.packageName + " to old name " + origPackage.name);
6630                            }
6631                            break;
6632                        }
6633                    }
6634                }
6635            }
6636
6637            if (mTransferedPackages.contains(pkg.packageName)) {
6638                Slog.w(TAG, "Package " + pkg.packageName
6639                        + " was transferred to another, but its .apk remains");
6640            }
6641
6642            // Just create the setting, don't add it yet. For already existing packages
6643            // the PkgSetting exists already and doesn't have to be created.
6644            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6645                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6646                    pkg.applicationInfo.primaryCpuAbi,
6647                    pkg.applicationInfo.secondaryCpuAbi,
6648                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6649                    user, false);
6650            if (pkgSetting == null) {
6651                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6652                        "Creating application package " + pkg.packageName + " failed");
6653            }
6654
6655            if (pkgSetting.origPackage != null) {
6656                // If we are first transitioning from an original package,
6657                // fix up the new package's name now.  We need to do this after
6658                // looking up the package under its new name, so getPackageLP
6659                // can take care of fiddling things correctly.
6660                pkg.setPackageName(origPackage.name);
6661
6662                // File a report about this.
6663                String msg = "New package " + pkgSetting.realName
6664                        + " renamed to replace old package " + pkgSetting.name;
6665                reportSettingsProblem(Log.WARN, msg);
6666
6667                // Make a note of it.
6668                mTransferedPackages.add(origPackage.name);
6669
6670                // No longer need to retain this.
6671                pkgSetting.origPackage = null;
6672            }
6673
6674            if (realName != null) {
6675                // Make a note of it.
6676                mTransferedPackages.add(pkg.packageName);
6677            }
6678
6679            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6680                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6681            }
6682
6683            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6684                // Check all shared libraries and map to their actual file path.
6685                // We only do this here for apps not on a system dir, because those
6686                // are the only ones that can fail an install due to this.  We
6687                // will take care of the system apps by updating all of their
6688                // library paths after the scan is done.
6689                updateSharedLibrariesLPw(pkg, null);
6690            }
6691
6692            if (mFoundPolicyFile) {
6693                SELinuxMMAC.assignSeinfoValue(pkg);
6694            }
6695
6696            pkg.applicationInfo.uid = pkgSetting.appId;
6697            pkg.mExtras = pkgSetting;
6698            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6699                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6700                    // We just determined the app is signed correctly, so bring
6701                    // over the latest parsed certs.
6702                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6703                } else {
6704                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6705                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6706                                "Package " + pkg.packageName + " upgrade keys do not match the "
6707                                + "previously installed version");
6708                    } else {
6709                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6710                        String msg = "System package " + pkg.packageName
6711                            + " signature changed; retaining data.";
6712                        reportSettingsProblem(Log.WARN, msg);
6713                    }
6714                }
6715            } else {
6716                try {
6717                    verifySignaturesLP(pkgSetting, pkg);
6718                    // We just determined the app is signed correctly, so bring
6719                    // over the latest parsed certs.
6720                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6721                } catch (PackageManagerException e) {
6722                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6723                        throw e;
6724                    }
6725                    // The signature has changed, but this package is in the system
6726                    // image...  let's recover!
6727                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6728                    // However...  if this package is part of a shared user, but it
6729                    // doesn't match the signature of the shared user, let's fail.
6730                    // What this means is that you can't change the signatures
6731                    // associated with an overall shared user, which doesn't seem all
6732                    // that unreasonable.
6733                    if (pkgSetting.sharedUser != null) {
6734                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6735                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6736                            throw new PackageManagerException(
6737                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6738                                            "Signature mismatch for shared user : "
6739                                            + pkgSetting.sharedUser);
6740                        }
6741                    }
6742                    // File a report about this.
6743                    String msg = "System package " + pkg.packageName
6744                        + " signature changed; retaining data.";
6745                    reportSettingsProblem(Log.WARN, msg);
6746                }
6747            }
6748            // Verify that this new package doesn't have any content providers
6749            // that conflict with existing packages.  Only do this if the
6750            // package isn't already installed, since we don't want to break
6751            // things that are installed.
6752            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6753                final int N = pkg.providers.size();
6754                int i;
6755                for (i=0; i<N; i++) {
6756                    PackageParser.Provider p = pkg.providers.get(i);
6757                    if (p.info.authority != null) {
6758                        String names[] = p.info.authority.split(";");
6759                        for (int j = 0; j < names.length; j++) {
6760                            if (mProvidersByAuthority.containsKey(names[j])) {
6761                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6762                                final String otherPackageName =
6763                                        ((other != null && other.getComponentName() != null) ?
6764                                                other.getComponentName().getPackageName() : "?");
6765                                throw new PackageManagerException(
6766                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6767                                                "Can't install because provider name " + names[j]
6768                                                + " (in package " + pkg.applicationInfo.packageName
6769                                                + ") is already used by " + otherPackageName);
6770                            }
6771                        }
6772                    }
6773                }
6774            }
6775
6776            if (pkg.mAdoptPermissions != null) {
6777                // This package wants to adopt ownership of permissions from
6778                // another package.
6779                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6780                    final String origName = pkg.mAdoptPermissions.get(i);
6781                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6782                    if (orig != null) {
6783                        if (verifyPackageUpdateLPr(orig, pkg)) {
6784                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6785                                    + pkg.packageName);
6786                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6787                        }
6788                    }
6789                }
6790            }
6791        }
6792
6793        final String pkgName = pkg.packageName;
6794
6795        final long scanFileTime = scanFile.lastModified();
6796        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6797        pkg.applicationInfo.processName = fixProcessName(
6798                pkg.applicationInfo.packageName,
6799                pkg.applicationInfo.processName,
6800                pkg.applicationInfo.uid);
6801
6802        File dataPath;
6803        if (mPlatformPackage == pkg) {
6804            // The system package is special.
6805            dataPath = new File(Environment.getDataDirectory(), "system");
6806
6807            pkg.applicationInfo.dataDir = dataPath.getPath();
6808
6809        } else {
6810            // This is a normal package, need to make its data directory.
6811            dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid,
6812                    UserHandle.USER_OWNER, pkg.packageName);
6813
6814            boolean uidError = false;
6815            if (dataPath.exists()) {
6816                int currentUid = 0;
6817                try {
6818                    StructStat stat = Os.stat(dataPath.getPath());
6819                    currentUid = stat.st_uid;
6820                } catch (ErrnoException e) {
6821                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6822                }
6823
6824                // If we have mismatched owners for the data path, we have a problem.
6825                if (currentUid != pkg.applicationInfo.uid) {
6826                    boolean recovered = false;
6827                    if (currentUid == 0) {
6828                        // The directory somehow became owned by root.  Wow.
6829                        // This is probably because the system was stopped while
6830                        // installd was in the middle of messing with its libs
6831                        // directory.  Ask installd to fix that.
6832                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6833                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6834                        if (ret >= 0) {
6835                            recovered = true;
6836                            String msg = "Package " + pkg.packageName
6837                                    + " unexpectedly changed to uid 0; recovered to " +
6838                                    + pkg.applicationInfo.uid;
6839                            reportSettingsProblem(Log.WARN, msg);
6840                        }
6841                    }
6842                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6843                            || (scanFlags&SCAN_BOOTING) != 0)) {
6844                        // If this is a system app, we can at least delete its
6845                        // current data so the application will still work.
6846                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6847                        if (ret >= 0) {
6848                            // TODO: Kill the processes first
6849                            // Old data gone!
6850                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6851                                    ? "System package " : "Third party package ";
6852                            String msg = prefix + pkg.packageName
6853                                    + " has changed from uid: "
6854                                    + currentUid + " to "
6855                                    + pkg.applicationInfo.uid + "; old data erased";
6856                            reportSettingsProblem(Log.WARN, msg);
6857                            recovered = true;
6858
6859                            // And now re-install the app.
6860                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6861                                    pkg.applicationInfo.seinfo);
6862                            if (ret == -1) {
6863                                // Ack should not happen!
6864                                msg = prefix + pkg.packageName
6865                                        + " could not have data directory re-created after delete.";
6866                                reportSettingsProblem(Log.WARN, msg);
6867                                throw new PackageManagerException(
6868                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6869                            }
6870                        }
6871                        if (!recovered) {
6872                            mHasSystemUidErrors = true;
6873                        }
6874                    } else if (!recovered) {
6875                        // If we allow this install to proceed, we will be broken.
6876                        // Abort, abort!
6877                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6878                                "scanPackageLI");
6879                    }
6880                    if (!recovered) {
6881                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6882                            + pkg.applicationInfo.uid + "/fs_"
6883                            + currentUid;
6884                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6885                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6886                        String msg = "Package " + pkg.packageName
6887                                + " has mismatched uid: "
6888                                + currentUid + " on disk, "
6889                                + pkg.applicationInfo.uid + " in settings";
6890                        // writer
6891                        synchronized (mPackages) {
6892                            mSettings.mReadMessages.append(msg);
6893                            mSettings.mReadMessages.append('\n');
6894                            uidError = true;
6895                            if (!pkgSetting.uidError) {
6896                                reportSettingsProblem(Log.ERROR, msg);
6897                            }
6898                        }
6899                    }
6900                }
6901                pkg.applicationInfo.dataDir = dataPath.getPath();
6902                if (mShouldRestoreconData) {
6903                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6904                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6905                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6906                }
6907            } else {
6908                if (DEBUG_PACKAGE_SCANNING) {
6909                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6910                        Log.v(TAG, "Want this data dir: " + dataPath);
6911                }
6912                //invoke installer to do the actual installation
6913                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6914                        pkg.applicationInfo.seinfo);
6915                if (ret < 0) {
6916                    // Error from installer
6917                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6918                            "Unable to create data dirs [errorCode=" + ret + "]");
6919                }
6920
6921                if (dataPath.exists()) {
6922                    pkg.applicationInfo.dataDir = dataPath.getPath();
6923                } else {
6924                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6925                    pkg.applicationInfo.dataDir = null;
6926                }
6927            }
6928
6929            pkgSetting.uidError = uidError;
6930        }
6931
6932        final String path = scanFile.getPath();
6933        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6934
6935        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6936            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6937
6938            // Some system apps still use directory structure for native libraries
6939            // in which case we might end up not detecting abi solely based on apk
6940            // structure. Try to detect abi based on directory structure.
6941            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6942                    pkg.applicationInfo.primaryCpuAbi == null) {
6943                setBundledAppAbisAndRoots(pkg, pkgSetting);
6944                setNativeLibraryPaths(pkg);
6945            }
6946
6947        } else {
6948            if ((scanFlags & SCAN_MOVE) != 0) {
6949                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6950                // but we already have this packages package info in the PackageSetting. We just
6951                // use that and derive the native library path based on the new codepath.
6952                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6953                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6954            }
6955
6956            // Set native library paths again. For moves, the path will be updated based on the
6957            // ABIs we've determined above. For non-moves, the path will be updated based on the
6958            // ABIs we determined during compilation, but the path will depend on the final
6959            // package path (after the rename away from the stage path).
6960            setNativeLibraryPaths(pkg);
6961        }
6962
6963        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6964        final int[] userIds = sUserManager.getUserIds();
6965        synchronized (mInstallLock) {
6966            // Make sure all user data directories are ready to roll; we're okay
6967            // if they already exist
6968            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
6969                for (int userId : userIds) {
6970                    if (userId != 0) {
6971                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
6972                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
6973                                pkg.applicationInfo.seinfo);
6974                    }
6975                }
6976            }
6977
6978            // Create a native library symlink only if we have native libraries
6979            // and if the native libraries are 32 bit libraries. We do not provide
6980            // this symlink for 64 bit libraries.
6981            if (pkg.applicationInfo.primaryCpuAbi != null &&
6982                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6983                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6984                for (int userId : userIds) {
6985                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6986                            nativeLibPath, userId) < 0) {
6987                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6988                                "Failed linking native library dir (user=" + userId + ")");
6989                    }
6990                }
6991            }
6992        }
6993
6994        // This is a special case for the "system" package, where the ABI is
6995        // dictated by the zygote configuration (and init.rc). We should keep track
6996        // of this ABI so that we can deal with "normal" applications that run under
6997        // the same UID correctly.
6998        if (mPlatformPackage == pkg) {
6999            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7000                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7001        }
7002
7003        // If there's a mismatch between the abi-override in the package setting
7004        // and the abiOverride specified for the install. Warn about this because we
7005        // would've already compiled the app without taking the package setting into
7006        // account.
7007        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7008            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7009                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7010                        " for package: " + pkg.packageName);
7011            }
7012        }
7013
7014        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7015        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7016        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7017
7018        // Copy the derived override back to the parsed package, so that we can
7019        // update the package settings accordingly.
7020        pkg.cpuAbiOverride = cpuAbiOverride;
7021
7022        if (DEBUG_ABI_SELECTION) {
7023            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7024                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7025                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7026        }
7027
7028        // Push the derived path down into PackageSettings so we know what to
7029        // clean up at uninstall time.
7030        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7031
7032        if (DEBUG_ABI_SELECTION) {
7033            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7034                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7035                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7036        }
7037
7038        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7039            // We don't do this here during boot because we can do it all
7040            // at once after scanning all existing packages.
7041            //
7042            // We also do this *before* we perform dexopt on this package, so that
7043            // we can avoid redundant dexopts, and also to make sure we've got the
7044            // code and package path correct.
7045            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7046                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
7047        }
7048
7049        if ((scanFlags & SCAN_NO_DEX) == 0) {
7050            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
7051                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
7052            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7053                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
7054            }
7055        }
7056        if (mFactoryTest && pkg.requestedPermissions.contains(
7057                android.Manifest.permission.FACTORY_TEST)) {
7058            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7059        }
7060
7061        ArrayList<PackageParser.Package> clientLibPkgs = null;
7062
7063        // writer
7064        synchronized (mPackages) {
7065            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7066                // Only system apps can add new shared libraries.
7067                if (pkg.libraryNames != null) {
7068                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7069                        String name = pkg.libraryNames.get(i);
7070                        boolean allowed = false;
7071                        if (pkg.isUpdatedSystemApp()) {
7072                            // New library entries can only be added through the
7073                            // system image.  This is important to get rid of a lot
7074                            // of nasty edge cases: for example if we allowed a non-
7075                            // system update of the app to add a library, then uninstalling
7076                            // the update would make the library go away, and assumptions
7077                            // we made such as through app install filtering would now
7078                            // have allowed apps on the device which aren't compatible
7079                            // with it.  Better to just have the restriction here, be
7080                            // conservative, and create many fewer cases that can negatively
7081                            // impact the user experience.
7082                            final PackageSetting sysPs = mSettings
7083                                    .getDisabledSystemPkgLPr(pkg.packageName);
7084                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7085                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7086                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7087                                        allowed = true;
7088                                        allowed = true;
7089                                        break;
7090                                    }
7091                                }
7092                            }
7093                        } else {
7094                            allowed = true;
7095                        }
7096                        if (allowed) {
7097                            if (!mSharedLibraries.containsKey(name)) {
7098                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7099                            } else if (!name.equals(pkg.packageName)) {
7100                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7101                                        + name + " already exists; skipping");
7102                            }
7103                        } else {
7104                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7105                                    + name + " that is not declared on system image; skipping");
7106                        }
7107                    }
7108                    if ((scanFlags&SCAN_BOOTING) == 0) {
7109                        // If we are not booting, we need to update any applications
7110                        // that are clients of our shared library.  If we are booting,
7111                        // this will all be done once the scan is complete.
7112                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7113                    }
7114                }
7115            }
7116        }
7117
7118        // We also need to dexopt any apps that are dependent on this library.  Note that
7119        // if these fail, we should abort the install since installing the library will
7120        // result in some apps being broken.
7121        if (clientLibPkgs != null) {
7122            if ((scanFlags & SCAN_NO_DEX) == 0) {
7123                for (int i = 0; i < clientLibPkgs.size(); i++) {
7124                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
7125                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
7126                            null /* instruction sets */, forceDex,
7127                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
7128                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7129                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
7130                                "scanPackageLI failed to dexopt clientLibPkgs");
7131                    }
7132                }
7133            }
7134        }
7135
7136        // Also need to kill any apps that are dependent on the library.
7137        if (clientLibPkgs != null) {
7138            for (int i=0; i<clientLibPkgs.size(); i++) {
7139                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7140                killApplication(clientPkg.applicationInfo.packageName,
7141                        clientPkg.applicationInfo.uid, "update lib");
7142            }
7143        }
7144
7145        // Make sure we're not adding any bogus keyset info
7146        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7147        ksms.assertScannedPackageValid(pkg);
7148
7149        // writer
7150        synchronized (mPackages) {
7151            // We don't expect installation to fail beyond this point
7152
7153            // Add the new setting to mSettings
7154            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7155            // Add the new setting to mPackages
7156            mPackages.put(pkg.applicationInfo.packageName, pkg);
7157            // Make sure we don't accidentally delete its data.
7158            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7159            while (iter.hasNext()) {
7160                PackageCleanItem item = iter.next();
7161                if (pkgName.equals(item.packageName)) {
7162                    iter.remove();
7163                }
7164            }
7165
7166            // Take care of first install / last update times.
7167            if (currentTime != 0) {
7168                if (pkgSetting.firstInstallTime == 0) {
7169                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7170                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7171                    pkgSetting.lastUpdateTime = currentTime;
7172                }
7173            } else if (pkgSetting.firstInstallTime == 0) {
7174                // We need *something*.  Take time time stamp of the file.
7175                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7176            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7177                if (scanFileTime != pkgSetting.timeStamp) {
7178                    // A package on the system image has changed; consider this
7179                    // to be an update.
7180                    pkgSetting.lastUpdateTime = scanFileTime;
7181                }
7182            }
7183
7184            // Add the package's KeySets to the global KeySetManagerService
7185            ksms.addScannedPackageLPw(pkg);
7186
7187            int N = pkg.providers.size();
7188            StringBuilder r = null;
7189            int i;
7190            for (i=0; i<N; i++) {
7191                PackageParser.Provider p = pkg.providers.get(i);
7192                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7193                        p.info.processName, pkg.applicationInfo.uid);
7194                mProviders.addProvider(p);
7195                p.syncable = p.info.isSyncable;
7196                if (p.info.authority != null) {
7197                    String names[] = p.info.authority.split(";");
7198                    p.info.authority = null;
7199                    for (int j = 0; j < names.length; j++) {
7200                        if (j == 1 && p.syncable) {
7201                            // We only want the first authority for a provider to possibly be
7202                            // syncable, so if we already added this provider using a different
7203                            // authority clear the syncable flag. We copy the provider before
7204                            // changing it because the mProviders object contains a reference
7205                            // to a provider that we don't want to change.
7206                            // Only do this for the second authority since the resulting provider
7207                            // object can be the same for all future authorities for this provider.
7208                            p = new PackageParser.Provider(p);
7209                            p.syncable = false;
7210                        }
7211                        if (!mProvidersByAuthority.containsKey(names[j])) {
7212                            mProvidersByAuthority.put(names[j], p);
7213                            if (p.info.authority == null) {
7214                                p.info.authority = names[j];
7215                            } else {
7216                                p.info.authority = p.info.authority + ";" + names[j];
7217                            }
7218                            if (DEBUG_PACKAGE_SCANNING) {
7219                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7220                                    Log.d(TAG, "Registered content provider: " + names[j]
7221                                            + ", className = " + p.info.name + ", isSyncable = "
7222                                            + p.info.isSyncable);
7223                            }
7224                        } else {
7225                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7226                            Slog.w(TAG, "Skipping provider name " + names[j] +
7227                                    " (in package " + pkg.applicationInfo.packageName +
7228                                    "): name already used by "
7229                                    + ((other != null && other.getComponentName() != null)
7230                                            ? other.getComponentName().getPackageName() : "?"));
7231                        }
7232                    }
7233                }
7234                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7235                    if (r == null) {
7236                        r = new StringBuilder(256);
7237                    } else {
7238                        r.append(' ');
7239                    }
7240                    r.append(p.info.name);
7241                }
7242            }
7243            if (r != null) {
7244                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7245            }
7246
7247            N = pkg.services.size();
7248            r = null;
7249            for (i=0; i<N; i++) {
7250                PackageParser.Service s = pkg.services.get(i);
7251                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7252                        s.info.processName, pkg.applicationInfo.uid);
7253                mServices.addService(s);
7254                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7255                    if (r == null) {
7256                        r = new StringBuilder(256);
7257                    } else {
7258                        r.append(' ');
7259                    }
7260                    r.append(s.info.name);
7261                }
7262            }
7263            if (r != null) {
7264                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7265            }
7266
7267            N = pkg.receivers.size();
7268            r = null;
7269            for (i=0; i<N; i++) {
7270                PackageParser.Activity a = pkg.receivers.get(i);
7271                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7272                        a.info.processName, pkg.applicationInfo.uid);
7273                mReceivers.addActivity(a, "receiver");
7274                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7275                    if (r == null) {
7276                        r = new StringBuilder(256);
7277                    } else {
7278                        r.append(' ');
7279                    }
7280                    r.append(a.info.name);
7281                }
7282            }
7283            if (r != null) {
7284                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7285            }
7286
7287            N = pkg.activities.size();
7288            r = null;
7289            for (i=0; i<N; i++) {
7290                PackageParser.Activity a = pkg.activities.get(i);
7291                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7292                        a.info.processName, pkg.applicationInfo.uid);
7293                mActivities.addActivity(a, "activity");
7294                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7295                    if (r == null) {
7296                        r = new StringBuilder(256);
7297                    } else {
7298                        r.append(' ');
7299                    }
7300                    r.append(a.info.name);
7301                }
7302            }
7303            if (r != null) {
7304                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7305            }
7306
7307            N = pkg.permissionGroups.size();
7308            r = null;
7309            for (i=0; i<N; i++) {
7310                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7311                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7312                if (cur == null) {
7313                    mPermissionGroups.put(pg.info.name, pg);
7314                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7315                        if (r == null) {
7316                            r = new StringBuilder(256);
7317                        } else {
7318                            r.append(' ');
7319                        }
7320                        r.append(pg.info.name);
7321                    }
7322                } else {
7323                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7324                            + pg.info.packageName + " ignored: original from "
7325                            + cur.info.packageName);
7326                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7327                        if (r == null) {
7328                            r = new StringBuilder(256);
7329                        } else {
7330                            r.append(' ');
7331                        }
7332                        r.append("DUP:");
7333                        r.append(pg.info.name);
7334                    }
7335                }
7336            }
7337            if (r != null) {
7338                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7339            }
7340
7341            N = pkg.permissions.size();
7342            r = null;
7343            for (i=0; i<N; i++) {
7344                PackageParser.Permission p = pkg.permissions.get(i);
7345
7346                // Assume by default that we did not install this permission into the system.
7347                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7348
7349                // Now that permission groups have a special meaning, we ignore permission
7350                // groups for legacy apps to prevent unexpected behavior. In particular,
7351                // permissions for one app being granted to someone just becuase they happen
7352                // to be in a group defined by another app (before this had no implications).
7353                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7354                    p.group = mPermissionGroups.get(p.info.group);
7355                    // Warn for a permission in an unknown group.
7356                    if (p.info.group != null && p.group == null) {
7357                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7358                                + p.info.packageName + " in an unknown group " + p.info.group);
7359                    }
7360                }
7361
7362                ArrayMap<String, BasePermission> permissionMap =
7363                        p.tree ? mSettings.mPermissionTrees
7364                                : mSettings.mPermissions;
7365                BasePermission bp = permissionMap.get(p.info.name);
7366
7367                // Allow system apps to redefine non-system permissions
7368                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7369                    final boolean currentOwnerIsSystem = (bp.perm != null
7370                            && isSystemApp(bp.perm.owner));
7371                    if (isSystemApp(p.owner)) {
7372                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7373                            // It's a built-in permission and no owner, take ownership now
7374                            bp.packageSetting = pkgSetting;
7375                            bp.perm = p;
7376                            bp.uid = pkg.applicationInfo.uid;
7377                            bp.sourcePackage = p.info.packageName;
7378                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7379                        } else if (!currentOwnerIsSystem) {
7380                            String msg = "New decl " + p.owner + " of permission  "
7381                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7382                            reportSettingsProblem(Log.WARN, msg);
7383                            bp = null;
7384                        }
7385                    }
7386                }
7387
7388                if (bp == null) {
7389                    bp = new BasePermission(p.info.name, p.info.packageName,
7390                            BasePermission.TYPE_NORMAL);
7391                    permissionMap.put(p.info.name, bp);
7392                }
7393
7394                if (bp.perm == null) {
7395                    if (bp.sourcePackage == null
7396                            || bp.sourcePackage.equals(p.info.packageName)) {
7397                        BasePermission tree = findPermissionTreeLP(p.info.name);
7398                        if (tree == null
7399                                || tree.sourcePackage.equals(p.info.packageName)) {
7400                            bp.packageSetting = pkgSetting;
7401                            bp.perm = p;
7402                            bp.uid = pkg.applicationInfo.uid;
7403                            bp.sourcePackage = p.info.packageName;
7404                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7405                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7406                                if (r == null) {
7407                                    r = new StringBuilder(256);
7408                                } else {
7409                                    r.append(' ');
7410                                }
7411                                r.append(p.info.name);
7412                            }
7413                        } else {
7414                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7415                                    + p.info.packageName + " ignored: base tree "
7416                                    + tree.name + " is from package "
7417                                    + tree.sourcePackage);
7418                        }
7419                    } else {
7420                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7421                                + p.info.packageName + " ignored: original from "
7422                                + bp.sourcePackage);
7423                    }
7424                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7425                    if (r == null) {
7426                        r = new StringBuilder(256);
7427                    } else {
7428                        r.append(' ');
7429                    }
7430                    r.append("DUP:");
7431                    r.append(p.info.name);
7432                }
7433                if (bp.perm == p) {
7434                    bp.protectionLevel = p.info.protectionLevel;
7435                }
7436            }
7437
7438            if (r != null) {
7439                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7440            }
7441
7442            N = pkg.instrumentation.size();
7443            r = null;
7444            for (i=0; i<N; i++) {
7445                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7446                a.info.packageName = pkg.applicationInfo.packageName;
7447                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7448                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7449                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7450                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7451                a.info.dataDir = pkg.applicationInfo.dataDir;
7452
7453                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7454                // need other information about the application, like the ABI and what not ?
7455                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7456                mInstrumentation.put(a.getComponentName(), a);
7457                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7458                    if (r == null) {
7459                        r = new StringBuilder(256);
7460                    } else {
7461                        r.append(' ');
7462                    }
7463                    r.append(a.info.name);
7464                }
7465            }
7466            if (r != null) {
7467                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7468            }
7469
7470            if (pkg.protectedBroadcasts != null) {
7471                N = pkg.protectedBroadcasts.size();
7472                for (i=0; i<N; i++) {
7473                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7474                }
7475            }
7476
7477            pkgSetting.setTimeStamp(scanFileTime);
7478
7479            // Create idmap files for pairs of (packages, overlay packages).
7480            // Note: "android", ie framework-res.apk, is handled by native layers.
7481            if (pkg.mOverlayTarget != null) {
7482                // This is an overlay package.
7483                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7484                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7485                        mOverlays.put(pkg.mOverlayTarget,
7486                                new ArrayMap<String, PackageParser.Package>());
7487                    }
7488                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7489                    map.put(pkg.packageName, pkg);
7490                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7491                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7492                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7493                                "scanPackageLI failed to createIdmap");
7494                    }
7495                }
7496            } else if (mOverlays.containsKey(pkg.packageName) &&
7497                    !pkg.packageName.equals("android")) {
7498                // This is a regular package, with one or more known overlay packages.
7499                createIdmapsForPackageLI(pkg);
7500            }
7501        }
7502
7503        return pkg;
7504    }
7505
7506    /**
7507     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7508     * is derived purely on the basis of the contents of {@code scanFile} and
7509     * {@code cpuAbiOverride}.
7510     *
7511     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7512     */
7513    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7514                                 String cpuAbiOverride, boolean extractLibs)
7515            throws PackageManagerException {
7516        // TODO: We can probably be smarter about this stuff. For installed apps,
7517        // we can calculate this information at install time once and for all. For
7518        // system apps, we can probably assume that this information doesn't change
7519        // after the first boot scan. As things stand, we do lots of unnecessary work.
7520
7521        // Give ourselves some initial paths; we'll come back for another
7522        // pass once we've determined ABI below.
7523        setNativeLibraryPaths(pkg);
7524
7525        // We would never need to extract libs for forward-locked and external packages,
7526        // since the container service will do it for us. We shouldn't attempt to
7527        // extract libs from system app when it was not updated.
7528        if (pkg.isForwardLocked() || isExternal(pkg) ||
7529            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7530            extractLibs = false;
7531        }
7532
7533        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7534        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7535
7536        NativeLibraryHelper.Handle handle = null;
7537        try {
7538            handle = NativeLibraryHelper.Handle.create(scanFile);
7539            // TODO(multiArch): This can be null for apps that didn't go through the
7540            // usual installation process. We can calculate it again, like we
7541            // do during install time.
7542            //
7543            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7544            // unnecessary.
7545            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7546
7547            // Null out the abis so that they can be recalculated.
7548            pkg.applicationInfo.primaryCpuAbi = null;
7549            pkg.applicationInfo.secondaryCpuAbi = null;
7550            if (isMultiArch(pkg.applicationInfo)) {
7551                // Warn if we've set an abiOverride for multi-lib packages..
7552                // By definition, we need to copy both 32 and 64 bit libraries for
7553                // such packages.
7554                if (pkg.cpuAbiOverride != null
7555                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7556                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7557                }
7558
7559                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7560                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7561                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7562                    if (extractLibs) {
7563                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7564                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7565                                useIsaSpecificSubdirs);
7566                    } else {
7567                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7568                    }
7569                }
7570
7571                maybeThrowExceptionForMultiArchCopy(
7572                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7573
7574                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7575                    if (extractLibs) {
7576                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7577                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7578                                useIsaSpecificSubdirs);
7579                    } else {
7580                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7581                    }
7582                }
7583
7584                maybeThrowExceptionForMultiArchCopy(
7585                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7586
7587                if (abi64 >= 0) {
7588                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7589                }
7590
7591                if (abi32 >= 0) {
7592                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7593                    if (abi64 >= 0) {
7594                        pkg.applicationInfo.secondaryCpuAbi = abi;
7595                    } else {
7596                        pkg.applicationInfo.primaryCpuAbi = abi;
7597                    }
7598                }
7599            } else {
7600                String[] abiList = (cpuAbiOverride != null) ?
7601                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7602
7603                // Enable gross and lame hacks for apps that are built with old
7604                // SDK tools. We must scan their APKs for renderscript bitcode and
7605                // not launch them if it's present. Don't bother checking on devices
7606                // that don't have 64 bit support.
7607                boolean needsRenderScriptOverride = false;
7608                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7609                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7610                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7611                    needsRenderScriptOverride = true;
7612                }
7613
7614                final int copyRet;
7615                if (extractLibs) {
7616                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7617                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7618                } else {
7619                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7620                }
7621
7622                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7623                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7624                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7625                }
7626
7627                if (copyRet >= 0) {
7628                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7629                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7630                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7631                } else if (needsRenderScriptOverride) {
7632                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7633                }
7634            }
7635        } catch (IOException ioe) {
7636            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7637        } finally {
7638            IoUtils.closeQuietly(handle);
7639        }
7640
7641        // Now that we've calculated the ABIs and determined if it's an internal app,
7642        // we will go ahead and populate the nativeLibraryPath.
7643        setNativeLibraryPaths(pkg);
7644    }
7645
7646    /**
7647     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7648     * i.e, so that all packages can be run inside a single process if required.
7649     *
7650     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7651     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7652     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7653     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7654     * updating a package that belongs to a shared user.
7655     *
7656     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7657     * adds unnecessary complexity.
7658     */
7659    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7660            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7661        String requiredInstructionSet = null;
7662        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7663            requiredInstructionSet = VMRuntime.getInstructionSet(
7664                     scannedPackage.applicationInfo.primaryCpuAbi);
7665        }
7666
7667        PackageSetting requirer = null;
7668        for (PackageSetting ps : packagesForUser) {
7669            // If packagesForUser contains scannedPackage, we skip it. This will happen
7670            // when scannedPackage is an update of an existing package. Without this check,
7671            // we will never be able to change the ABI of any package belonging to a shared
7672            // user, even if it's compatible with other packages.
7673            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7674                if (ps.primaryCpuAbiString == null) {
7675                    continue;
7676                }
7677
7678                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7679                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7680                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7681                    // this but there's not much we can do.
7682                    String errorMessage = "Instruction set mismatch, "
7683                            + ((requirer == null) ? "[caller]" : requirer)
7684                            + " requires " + requiredInstructionSet + " whereas " + ps
7685                            + " requires " + instructionSet;
7686                    Slog.w(TAG, errorMessage);
7687                }
7688
7689                if (requiredInstructionSet == null) {
7690                    requiredInstructionSet = instructionSet;
7691                    requirer = ps;
7692                }
7693            }
7694        }
7695
7696        if (requiredInstructionSet != null) {
7697            String adjustedAbi;
7698            if (requirer != null) {
7699                // requirer != null implies that either scannedPackage was null or that scannedPackage
7700                // did not require an ABI, in which case we have to adjust scannedPackage to match
7701                // the ABI of the set (which is the same as requirer's ABI)
7702                adjustedAbi = requirer.primaryCpuAbiString;
7703                if (scannedPackage != null) {
7704                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7705                }
7706            } else {
7707                // requirer == null implies that we're updating all ABIs in the set to
7708                // match scannedPackage.
7709                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7710            }
7711
7712            for (PackageSetting ps : packagesForUser) {
7713                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7714                    if (ps.primaryCpuAbiString != null) {
7715                        continue;
7716                    }
7717
7718                    ps.primaryCpuAbiString = adjustedAbi;
7719                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7720                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7721                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7722
7723                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7724                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7725                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7726                            ps.primaryCpuAbiString = null;
7727                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7728                            return;
7729                        } else {
7730                            mInstaller.rmdex(ps.codePathString,
7731                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7732                        }
7733                    }
7734                }
7735            }
7736        }
7737    }
7738
7739    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7740        synchronized (mPackages) {
7741            mResolverReplaced = true;
7742            // Set up information for custom user intent resolution activity.
7743            mResolveActivity.applicationInfo = pkg.applicationInfo;
7744            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7745            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7746            mResolveActivity.processName = pkg.applicationInfo.packageName;
7747            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7748            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7749                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7750            mResolveActivity.theme = 0;
7751            mResolveActivity.exported = true;
7752            mResolveActivity.enabled = true;
7753            mResolveInfo.activityInfo = mResolveActivity;
7754            mResolveInfo.priority = 0;
7755            mResolveInfo.preferredOrder = 0;
7756            mResolveInfo.match = 0;
7757            mResolveComponentName = mCustomResolverComponentName;
7758            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7759                    mResolveComponentName);
7760        }
7761    }
7762
7763    private static String calculateBundledApkRoot(final String codePathString) {
7764        final File codePath = new File(codePathString);
7765        final File codeRoot;
7766        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7767            codeRoot = Environment.getRootDirectory();
7768        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7769            codeRoot = Environment.getOemDirectory();
7770        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7771            codeRoot = Environment.getVendorDirectory();
7772        } else {
7773            // Unrecognized code path; take its top real segment as the apk root:
7774            // e.g. /something/app/blah.apk => /something
7775            try {
7776                File f = codePath.getCanonicalFile();
7777                File parent = f.getParentFile();    // non-null because codePath is a file
7778                File tmp;
7779                while ((tmp = parent.getParentFile()) != null) {
7780                    f = parent;
7781                    parent = tmp;
7782                }
7783                codeRoot = f;
7784                Slog.w(TAG, "Unrecognized code path "
7785                        + codePath + " - using " + codeRoot);
7786            } catch (IOException e) {
7787                // Can't canonicalize the code path -- shenanigans?
7788                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7789                return Environment.getRootDirectory().getPath();
7790            }
7791        }
7792        return codeRoot.getPath();
7793    }
7794
7795    /**
7796     * Derive and set the location of native libraries for the given package,
7797     * which varies depending on where and how the package was installed.
7798     */
7799    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7800        final ApplicationInfo info = pkg.applicationInfo;
7801        final String codePath = pkg.codePath;
7802        final File codeFile = new File(codePath);
7803        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7804        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7805
7806        info.nativeLibraryRootDir = null;
7807        info.nativeLibraryRootRequiresIsa = false;
7808        info.nativeLibraryDir = null;
7809        info.secondaryNativeLibraryDir = null;
7810
7811        if (isApkFile(codeFile)) {
7812            // Monolithic install
7813            if (bundledApp) {
7814                // If "/system/lib64/apkname" exists, assume that is the per-package
7815                // native library directory to use; otherwise use "/system/lib/apkname".
7816                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7817                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7818                        getPrimaryInstructionSet(info));
7819
7820                // This is a bundled system app so choose the path based on the ABI.
7821                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7822                // is just the default path.
7823                final String apkName = deriveCodePathName(codePath);
7824                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7825                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7826                        apkName).getAbsolutePath();
7827
7828                if (info.secondaryCpuAbi != null) {
7829                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7830                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7831                            secondaryLibDir, apkName).getAbsolutePath();
7832                }
7833            } else if (asecApp) {
7834                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7835                        .getAbsolutePath();
7836            } else {
7837                final String apkName = deriveCodePathName(codePath);
7838                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7839                        .getAbsolutePath();
7840            }
7841
7842            info.nativeLibraryRootRequiresIsa = false;
7843            info.nativeLibraryDir = info.nativeLibraryRootDir;
7844        } else {
7845            // Cluster install
7846            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7847            info.nativeLibraryRootRequiresIsa = true;
7848
7849            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7850                    getPrimaryInstructionSet(info)).getAbsolutePath();
7851
7852            if (info.secondaryCpuAbi != null) {
7853                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7854                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7855            }
7856        }
7857    }
7858
7859    /**
7860     * Calculate the abis and roots for a bundled app. These can uniquely
7861     * be determined from the contents of the system partition, i.e whether
7862     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7863     * of this information, and instead assume that the system was built
7864     * sensibly.
7865     */
7866    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7867                                           PackageSetting pkgSetting) {
7868        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7869
7870        // If "/system/lib64/apkname" exists, assume that is the per-package
7871        // native library directory to use; otherwise use "/system/lib/apkname".
7872        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7873        setBundledAppAbi(pkg, apkRoot, apkName);
7874        // pkgSetting might be null during rescan following uninstall of updates
7875        // to a bundled app, so accommodate that possibility.  The settings in
7876        // that case will be established later from the parsed package.
7877        //
7878        // If the settings aren't null, sync them up with what we've just derived.
7879        // note that apkRoot isn't stored in the package settings.
7880        if (pkgSetting != null) {
7881            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7882            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7883        }
7884    }
7885
7886    /**
7887     * Deduces the ABI of a bundled app and sets the relevant fields on the
7888     * parsed pkg object.
7889     *
7890     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7891     *        under which system libraries are installed.
7892     * @param apkName the name of the installed package.
7893     */
7894    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7895        final File codeFile = new File(pkg.codePath);
7896
7897        final boolean has64BitLibs;
7898        final boolean has32BitLibs;
7899        if (isApkFile(codeFile)) {
7900            // Monolithic install
7901            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7902            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7903        } else {
7904            // Cluster install
7905            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7906            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7907                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7908                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7909                has64BitLibs = (new File(rootDir, isa)).exists();
7910            } else {
7911                has64BitLibs = false;
7912            }
7913            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7914                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7915                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7916                has32BitLibs = (new File(rootDir, isa)).exists();
7917            } else {
7918                has32BitLibs = false;
7919            }
7920        }
7921
7922        if (has64BitLibs && !has32BitLibs) {
7923            // The package has 64 bit libs, but not 32 bit libs. Its primary
7924            // ABI should be 64 bit. We can safely assume here that the bundled
7925            // native libraries correspond to the most preferred ABI in the list.
7926
7927            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7928            pkg.applicationInfo.secondaryCpuAbi = null;
7929        } else if (has32BitLibs && !has64BitLibs) {
7930            // The package has 32 bit libs but not 64 bit libs. Its primary
7931            // ABI should be 32 bit.
7932
7933            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7934            pkg.applicationInfo.secondaryCpuAbi = null;
7935        } else if (has32BitLibs && has64BitLibs) {
7936            // The application has both 64 and 32 bit bundled libraries. We check
7937            // here that the app declares multiArch support, and warn if it doesn't.
7938            //
7939            // We will be lenient here and record both ABIs. The primary will be the
7940            // ABI that's higher on the list, i.e, a device that's configured to prefer
7941            // 64 bit apps will see a 64 bit primary ABI,
7942
7943            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7944                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7945            }
7946
7947            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7948                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7949                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7950            } else {
7951                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7952                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7953            }
7954        } else {
7955            pkg.applicationInfo.primaryCpuAbi = null;
7956            pkg.applicationInfo.secondaryCpuAbi = null;
7957        }
7958    }
7959
7960    private void killApplication(String pkgName, int appId, String reason) {
7961        // Request the ActivityManager to kill the process(only for existing packages)
7962        // so that we do not end up in a confused state while the user is still using the older
7963        // version of the application while the new one gets installed.
7964        IActivityManager am = ActivityManagerNative.getDefault();
7965        if (am != null) {
7966            try {
7967                am.killApplicationWithAppId(pkgName, appId, reason);
7968            } catch (RemoteException e) {
7969            }
7970        }
7971    }
7972
7973    void removePackageLI(PackageSetting ps, boolean chatty) {
7974        if (DEBUG_INSTALL) {
7975            if (chatty)
7976                Log.d(TAG, "Removing package " + ps.name);
7977        }
7978
7979        // writer
7980        synchronized (mPackages) {
7981            mPackages.remove(ps.name);
7982            final PackageParser.Package pkg = ps.pkg;
7983            if (pkg != null) {
7984                cleanPackageDataStructuresLILPw(pkg, chatty);
7985            }
7986        }
7987    }
7988
7989    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7990        if (DEBUG_INSTALL) {
7991            if (chatty)
7992                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7993        }
7994
7995        // writer
7996        synchronized (mPackages) {
7997            mPackages.remove(pkg.applicationInfo.packageName);
7998            cleanPackageDataStructuresLILPw(pkg, chatty);
7999        }
8000    }
8001
8002    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8003        int N = pkg.providers.size();
8004        StringBuilder r = null;
8005        int i;
8006        for (i=0; i<N; i++) {
8007            PackageParser.Provider p = pkg.providers.get(i);
8008            mProviders.removeProvider(p);
8009            if (p.info.authority == null) {
8010
8011                /* There was another ContentProvider with this authority when
8012                 * this app was installed so this authority is null,
8013                 * Ignore it as we don't have to unregister the provider.
8014                 */
8015                continue;
8016            }
8017            String names[] = p.info.authority.split(";");
8018            for (int j = 0; j < names.length; j++) {
8019                if (mProvidersByAuthority.get(names[j]) == p) {
8020                    mProvidersByAuthority.remove(names[j]);
8021                    if (DEBUG_REMOVE) {
8022                        if (chatty)
8023                            Log.d(TAG, "Unregistered content provider: " + names[j]
8024                                    + ", className = " + p.info.name + ", isSyncable = "
8025                                    + p.info.isSyncable);
8026                    }
8027                }
8028            }
8029            if (DEBUG_REMOVE && chatty) {
8030                if (r == null) {
8031                    r = new StringBuilder(256);
8032                } else {
8033                    r.append(' ');
8034                }
8035                r.append(p.info.name);
8036            }
8037        }
8038        if (r != null) {
8039            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8040        }
8041
8042        N = pkg.services.size();
8043        r = null;
8044        for (i=0; i<N; i++) {
8045            PackageParser.Service s = pkg.services.get(i);
8046            mServices.removeService(s);
8047            if (chatty) {
8048                if (r == null) {
8049                    r = new StringBuilder(256);
8050                } else {
8051                    r.append(' ');
8052                }
8053                r.append(s.info.name);
8054            }
8055        }
8056        if (r != null) {
8057            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8058        }
8059
8060        N = pkg.receivers.size();
8061        r = null;
8062        for (i=0; i<N; i++) {
8063            PackageParser.Activity a = pkg.receivers.get(i);
8064            mReceivers.removeActivity(a, "receiver");
8065            if (DEBUG_REMOVE && chatty) {
8066                if (r == null) {
8067                    r = new StringBuilder(256);
8068                } else {
8069                    r.append(' ');
8070                }
8071                r.append(a.info.name);
8072            }
8073        }
8074        if (r != null) {
8075            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8076        }
8077
8078        N = pkg.activities.size();
8079        r = null;
8080        for (i=0; i<N; i++) {
8081            PackageParser.Activity a = pkg.activities.get(i);
8082            mActivities.removeActivity(a, "activity");
8083            if (DEBUG_REMOVE && chatty) {
8084                if (r == null) {
8085                    r = new StringBuilder(256);
8086                } else {
8087                    r.append(' ');
8088                }
8089                r.append(a.info.name);
8090            }
8091        }
8092        if (r != null) {
8093            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8094        }
8095
8096        N = pkg.permissions.size();
8097        r = null;
8098        for (i=0; i<N; i++) {
8099            PackageParser.Permission p = pkg.permissions.get(i);
8100            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8101            if (bp == null) {
8102                bp = mSettings.mPermissionTrees.get(p.info.name);
8103            }
8104            if (bp != null && bp.perm == p) {
8105                bp.perm = null;
8106                if (DEBUG_REMOVE && chatty) {
8107                    if (r == null) {
8108                        r = new StringBuilder(256);
8109                    } else {
8110                        r.append(' ');
8111                    }
8112                    r.append(p.info.name);
8113                }
8114            }
8115            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8116                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8117                if (appOpPerms != null) {
8118                    appOpPerms.remove(pkg.packageName);
8119                }
8120            }
8121        }
8122        if (r != null) {
8123            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8124        }
8125
8126        N = pkg.requestedPermissions.size();
8127        r = null;
8128        for (i=0; i<N; i++) {
8129            String perm = pkg.requestedPermissions.get(i);
8130            BasePermission bp = mSettings.mPermissions.get(perm);
8131            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8132                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8133                if (appOpPerms != null) {
8134                    appOpPerms.remove(pkg.packageName);
8135                    if (appOpPerms.isEmpty()) {
8136                        mAppOpPermissionPackages.remove(perm);
8137                    }
8138                }
8139            }
8140        }
8141        if (r != null) {
8142            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8143        }
8144
8145        N = pkg.instrumentation.size();
8146        r = null;
8147        for (i=0; i<N; i++) {
8148            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8149            mInstrumentation.remove(a.getComponentName());
8150            if (DEBUG_REMOVE && chatty) {
8151                if (r == null) {
8152                    r = new StringBuilder(256);
8153                } else {
8154                    r.append(' ');
8155                }
8156                r.append(a.info.name);
8157            }
8158        }
8159        if (r != null) {
8160            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8161        }
8162
8163        r = null;
8164        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8165            // Only system apps can hold shared libraries.
8166            if (pkg.libraryNames != null) {
8167                for (i=0; i<pkg.libraryNames.size(); i++) {
8168                    String name = pkg.libraryNames.get(i);
8169                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8170                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8171                        mSharedLibraries.remove(name);
8172                        if (DEBUG_REMOVE && chatty) {
8173                            if (r == null) {
8174                                r = new StringBuilder(256);
8175                            } else {
8176                                r.append(' ');
8177                            }
8178                            r.append(name);
8179                        }
8180                    }
8181                }
8182            }
8183        }
8184        if (r != null) {
8185            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8186        }
8187    }
8188
8189    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8190        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8191            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8192                return true;
8193            }
8194        }
8195        return false;
8196    }
8197
8198    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8199    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8200    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8201
8202    private void updatePermissionsLPw(String changingPkg,
8203            PackageParser.Package pkgInfo, int flags) {
8204        // Make sure there are no dangling permission trees.
8205        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8206        while (it.hasNext()) {
8207            final BasePermission bp = it.next();
8208            if (bp.packageSetting == null) {
8209                // We may not yet have parsed the package, so just see if
8210                // we still know about its settings.
8211                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8212            }
8213            if (bp.packageSetting == null) {
8214                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8215                        + " from package " + bp.sourcePackage);
8216                it.remove();
8217            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8218                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8219                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8220                            + " from package " + bp.sourcePackage);
8221                    flags |= UPDATE_PERMISSIONS_ALL;
8222                    it.remove();
8223                }
8224            }
8225        }
8226
8227        // Make sure all dynamic permissions have been assigned to a package,
8228        // and make sure there are no dangling permissions.
8229        it = mSettings.mPermissions.values().iterator();
8230        while (it.hasNext()) {
8231            final BasePermission bp = it.next();
8232            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8233                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8234                        + bp.name + " pkg=" + bp.sourcePackage
8235                        + " info=" + bp.pendingInfo);
8236                if (bp.packageSetting == null && bp.pendingInfo != null) {
8237                    final BasePermission tree = findPermissionTreeLP(bp.name);
8238                    if (tree != null && tree.perm != null) {
8239                        bp.packageSetting = tree.packageSetting;
8240                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8241                                new PermissionInfo(bp.pendingInfo));
8242                        bp.perm.info.packageName = tree.perm.info.packageName;
8243                        bp.perm.info.name = bp.name;
8244                        bp.uid = tree.uid;
8245                    }
8246                }
8247            }
8248            if (bp.packageSetting == null) {
8249                // We may not yet have parsed the package, so just see if
8250                // we still know about its settings.
8251                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8252            }
8253            if (bp.packageSetting == null) {
8254                Slog.w(TAG, "Removing dangling permission: " + bp.name
8255                        + " from package " + bp.sourcePackage);
8256                it.remove();
8257            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8258                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8259                    Slog.i(TAG, "Removing old permission: " + bp.name
8260                            + " from package " + bp.sourcePackage);
8261                    flags |= UPDATE_PERMISSIONS_ALL;
8262                    it.remove();
8263                }
8264            }
8265        }
8266
8267        // Now update the permissions for all packages, in particular
8268        // replace the granted permissions of the system packages.
8269        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8270            for (PackageParser.Package pkg : mPackages.values()) {
8271                if (pkg != pkgInfo) {
8272                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8273                            changingPkg);
8274                }
8275            }
8276        }
8277
8278        if (pkgInfo != null) {
8279            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8280        }
8281    }
8282
8283    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8284            String packageOfInterest) {
8285        // IMPORTANT: There are two types of permissions: install and runtime.
8286        // Install time permissions are granted when the app is installed to
8287        // all device users and users added in the future. Runtime permissions
8288        // are granted at runtime explicitly to specific users. Normal and signature
8289        // protected permissions are install time permissions. Dangerous permissions
8290        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8291        // otherwise they are runtime permissions. This function does not manage
8292        // runtime permissions except for the case an app targeting Lollipop MR1
8293        // being upgraded to target a newer SDK, in which case dangerous permissions
8294        // are transformed from install time to runtime ones.
8295
8296        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8297        if (ps == null) {
8298            return;
8299        }
8300
8301        PermissionsState permissionsState = ps.getPermissionsState();
8302        PermissionsState origPermissions = permissionsState;
8303
8304        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8305
8306        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8307
8308        boolean changedInstallPermission = false;
8309
8310        if (replace) {
8311            ps.installPermissionsFixed = false;
8312            if (!ps.isSharedUser()) {
8313                origPermissions = new PermissionsState(permissionsState);
8314                permissionsState.reset();
8315            }
8316        }
8317
8318        permissionsState.setGlobalGids(mGlobalGids);
8319
8320        final int N = pkg.requestedPermissions.size();
8321        for (int i=0; i<N; i++) {
8322            final String name = pkg.requestedPermissions.get(i);
8323            final BasePermission bp = mSettings.mPermissions.get(name);
8324
8325            if (DEBUG_INSTALL) {
8326                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8327            }
8328
8329            if (bp == null || bp.packageSetting == null) {
8330                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8331                    Slog.w(TAG, "Unknown permission " + name
8332                            + " in package " + pkg.packageName);
8333                }
8334                continue;
8335            }
8336
8337            final String perm = bp.name;
8338            boolean allowedSig = false;
8339            int grant = GRANT_DENIED;
8340
8341            // Keep track of app op permissions.
8342            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8343                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8344                if (pkgs == null) {
8345                    pkgs = new ArraySet<>();
8346                    mAppOpPermissionPackages.put(bp.name, pkgs);
8347                }
8348                pkgs.add(pkg.packageName);
8349            }
8350
8351            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8352            switch (level) {
8353                case PermissionInfo.PROTECTION_NORMAL: {
8354                    // For all apps normal permissions are install time ones.
8355                    grant = GRANT_INSTALL;
8356                } break;
8357
8358                case PermissionInfo.PROTECTION_DANGEROUS: {
8359                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8360                        // For legacy apps dangerous permissions are install time ones.
8361                        grant = GRANT_INSTALL_LEGACY;
8362                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8363                        // For legacy apps that became modern, install becomes runtime.
8364                        grant = GRANT_UPGRADE;
8365                    } else {
8366                        // For modern apps keep runtime permissions unchanged.
8367                        grant = GRANT_RUNTIME;
8368                    }
8369                } break;
8370
8371                case PermissionInfo.PROTECTION_SIGNATURE: {
8372                    // For all apps signature permissions are install time ones.
8373                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8374                    if (allowedSig) {
8375                        grant = GRANT_INSTALL;
8376                    }
8377                } break;
8378            }
8379
8380            if (DEBUG_INSTALL) {
8381                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8382            }
8383
8384            if (grant != GRANT_DENIED) {
8385                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8386                    // If this is an existing, non-system package, then
8387                    // we can't add any new permissions to it.
8388                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8389                        // Except...  if this is a permission that was added
8390                        // to the platform (note: need to only do this when
8391                        // updating the platform).
8392                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8393                            grant = GRANT_DENIED;
8394                        }
8395                    }
8396                }
8397
8398                switch (grant) {
8399                    case GRANT_INSTALL: {
8400                        // Revoke this as runtime permission to handle the case of
8401                        // a runtime permission being downgraded to an install one.
8402                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8403                            if (origPermissions.getRuntimePermissionState(
8404                                    bp.name, userId) != null) {
8405                                // Revoke the runtime permission and clear the flags.
8406                                origPermissions.revokeRuntimePermission(bp, userId);
8407                                origPermissions.updatePermissionFlags(bp, userId,
8408                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8409                                // If we revoked a permission permission, we have to write.
8410                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8411                                        changedRuntimePermissionUserIds, userId);
8412                            }
8413                        }
8414                        // Grant an install permission.
8415                        if (permissionsState.grantInstallPermission(bp) !=
8416                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8417                            changedInstallPermission = true;
8418                        }
8419                    } break;
8420
8421                    case GRANT_INSTALL_LEGACY: {
8422                        // Grant an install permission.
8423                        if (permissionsState.grantInstallPermission(bp) !=
8424                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8425                            changedInstallPermission = true;
8426                        }
8427                    } break;
8428
8429                    case GRANT_RUNTIME: {
8430                        // Grant previously granted runtime permissions.
8431                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8432                            PermissionState permissionState = origPermissions
8433                                    .getRuntimePermissionState(bp.name, userId);
8434                            final int flags = permissionState != null
8435                                    ? permissionState.getFlags() : 0;
8436                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8437                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8438                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8439                                    // If we cannot put the permission as it was, we have to write.
8440                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8441                                            changedRuntimePermissionUserIds, userId);
8442                                }
8443                            }
8444                            // Propagate the permission flags.
8445                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8446                        }
8447                    } break;
8448
8449                    case GRANT_UPGRADE: {
8450                        // Grant runtime permissions for a previously held install permission.
8451                        PermissionState permissionState = origPermissions
8452                                .getInstallPermissionState(bp.name);
8453                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8454
8455                        if (origPermissions.revokeInstallPermission(bp)
8456                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8457                            // We will be transferring the permission flags, so clear them.
8458                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8459                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8460                            changedInstallPermission = true;
8461                        }
8462
8463                        // If the permission is not to be promoted to runtime we ignore it and
8464                        // also its other flags as they are not applicable to install permissions.
8465                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8466                            for (int userId : currentUserIds) {
8467                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8468                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8469                                    // Transfer the permission flags.
8470                                    permissionsState.updatePermissionFlags(bp, userId,
8471                                            flags, flags);
8472                                    // If we granted the permission, we have to write.
8473                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8474                                            changedRuntimePermissionUserIds, userId);
8475                                }
8476                            }
8477                        }
8478                    } break;
8479
8480                    default: {
8481                        if (packageOfInterest == null
8482                                || packageOfInterest.equals(pkg.packageName)) {
8483                            Slog.w(TAG, "Not granting permission " + perm
8484                                    + " to package " + pkg.packageName
8485                                    + " because it was previously installed without");
8486                        }
8487                    } break;
8488                }
8489            } else {
8490                if (permissionsState.revokeInstallPermission(bp) !=
8491                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8492                    // Also drop the permission flags.
8493                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8494                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8495                    changedInstallPermission = true;
8496                    Slog.i(TAG, "Un-granting permission " + perm
8497                            + " from package " + pkg.packageName
8498                            + " (protectionLevel=" + bp.protectionLevel
8499                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8500                            + ")");
8501                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8502                    // Don't print warning for app op permissions, since it is fine for them
8503                    // not to be granted, there is a UI for the user to decide.
8504                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8505                        Slog.w(TAG, "Not granting permission " + perm
8506                                + " to package " + pkg.packageName
8507                                + " (protectionLevel=" + bp.protectionLevel
8508                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8509                                + ")");
8510                    }
8511                }
8512            }
8513        }
8514
8515        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8516                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8517            // This is the first that we have heard about this package, so the
8518            // permissions we have now selected are fixed until explicitly
8519            // changed.
8520            ps.installPermissionsFixed = true;
8521        }
8522
8523        // Persist the runtime permissions state for users with changes.
8524        for (int userId : changedRuntimePermissionUserIds) {
8525            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8526        }
8527    }
8528
8529    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8530        boolean allowed = false;
8531        final int NP = PackageParser.NEW_PERMISSIONS.length;
8532        for (int ip=0; ip<NP; ip++) {
8533            final PackageParser.NewPermissionInfo npi
8534                    = PackageParser.NEW_PERMISSIONS[ip];
8535            if (npi.name.equals(perm)
8536                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8537                allowed = true;
8538                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8539                        + pkg.packageName);
8540                break;
8541            }
8542        }
8543        return allowed;
8544    }
8545
8546    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8547            BasePermission bp, PermissionsState origPermissions) {
8548        boolean allowed;
8549        allowed = (compareSignatures(
8550                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8551                        == PackageManager.SIGNATURE_MATCH)
8552                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8553                        == PackageManager.SIGNATURE_MATCH);
8554        if (!allowed && (bp.protectionLevel
8555                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8556            if (isSystemApp(pkg)) {
8557                // For updated system applications, a system permission
8558                // is granted only if it had been defined by the original application.
8559                if (pkg.isUpdatedSystemApp()) {
8560                    final PackageSetting sysPs = mSettings
8561                            .getDisabledSystemPkgLPr(pkg.packageName);
8562                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8563                        // If the original was granted this permission, we take
8564                        // that grant decision as read and propagate it to the
8565                        // update.
8566                        if (sysPs.isPrivileged()) {
8567                            allowed = true;
8568                        }
8569                    } else {
8570                        // The system apk may have been updated with an older
8571                        // version of the one on the data partition, but which
8572                        // granted a new system permission that it didn't have
8573                        // before.  In this case we do want to allow the app to
8574                        // now get the new permission if the ancestral apk is
8575                        // privileged to get it.
8576                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8577                            for (int j=0;
8578                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8579                                if (perm.equals(
8580                                        sysPs.pkg.requestedPermissions.get(j))) {
8581                                    allowed = true;
8582                                    break;
8583                                }
8584                            }
8585                        }
8586                    }
8587                } else {
8588                    allowed = isPrivilegedApp(pkg);
8589                }
8590            }
8591        }
8592        if (!allowed) {
8593            if (!allowed && (bp.protectionLevel
8594                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8595                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) {
8596                // If this was a previously normal/dangerous permission that got moved
8597                // to a system permission as part of the runtime permission redesign, then
8598                // we still want to blindly grant it to old apps.
8599                allowed = true;
8600            }
8601            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8602                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8603                // If this permission is to be granted to the system installer and
8604                // this app is an installer, then it gets the permission.
8605                allowed = true;
8606            }
8607            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8608                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8609                // If this permission is to be granted to the system verifier and
8610                // this app is a verifier, then it gets the permission.
8611                allowed = true;
8612            }
8613            if (!allowed && (bp.protectionLevel
8614                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8615                    && isSystemApp(pkg)) {
8616                // Any pre-installed system app is allowed to get this permission.
8617                allowed = true;
8618            }
8619            if (!allowed && (bp.protectionLevel
8620                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8621                // For development permissions, a development permission
8622                // is granted only if it was already granted.
8623                allowed = origPermissions.hasInstallPermission(perm);
8624            }
8625        }
8626        return allowed;
8627    }
8628
8629    final class ActivityIntentResolver
8630            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8631        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8632                boolean defaultOnly, int userId) {
8633            if (!sUserManager.exists(userId)) return null;
8634            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8635            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8636        }
8637
8638        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8639                int userId) {
8640            if (!sUserManager.exists(userId)) return null;
8641            mFlags = flags;
8642            return super.queryIntent(intent, resolvedType,
8643                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8644        }
8645
8646        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8647                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8648            if (!sUserManager.exists(userId)) return null;
8649            if (packageActivities == null) {
8650                return null;
8651            }
8652            mFlags = flags;
8653            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8654            final int N = packageActivities.size();
8655            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8656                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8657
8658            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8659            for (int i = 0; i < N; ++i) {
8660                intentFilters = packageActivities.get(i).intents;
8661                if (intentFilters != null && intentFilters.size() > 0) {
8662                    PackageParser.ActivityIntentInfo[] array =
8663                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8664                    intentFilters.toArray(array);
8665                    listCut.add(array);
8666                }
8667            }
8668            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8669        }
8670
8671        public final void addActivity(PackageParser.Activity a, String type) {
8672            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8673            mActivities.put(a.getComponentName(), a);
8674            if (DEBUG_SHOW_INFO)
8675                Log.v(
8676                TAG, "  " + type + " " +
8677                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8678            if (DEBUG_SHOW_INFO)
8679                Log.v(TAG, "    Class=" + a.info.name);
8680            final int NI = a.intents.size();
8681            for (int j=0; j<NI; j++) {
8682                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8683                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8684                    intent.setPriority(0);
8685                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8686                            + a.className + " with priority > 0, forcing to 0");
8687                }
8688                if (DEBUG_SHOW_INFO) {
8689                    Log.v(TAG, "    IntentFilter:");
8690                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8691                }
8692                if (!intent.debugCheck()) {
8693                    Log.w(TAG, "==> For Activity " + a.info.name);
8694                }
8695                addFilter(intent);
8696            }
8697        }
8698
8699        public final void removeActivity(PackageParser.Activity a, String type) {
8700            mActivities.remove(a.getComponentName());
8701            if (DEBUG_SHOW_INFO) {
8702                Log.v(TAG, "  " + type + " "
8703                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8704                                : a.info.name) + ":");
8705                Log.v(TAG, "    Class=" + a.info.name);
8706            }
8707            final int NI = a.intents.size();
8708            for (int j=0; j<NI; j++) {
8709                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8710                if (DEBUG_SHOW_INFO) {
8711                    Log.v(TAG, "    IntentFilter:");
8712                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8713                }
8714                removeFilter(intent);
8715            }
8716        }
8717
8718        @Override
8719        protected boolean allowFilterResult(
8720                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8721            ActivityInfo filterAi = filter.activity.info;
8722            for (int i=dest.size()-1; i>=0; i--) {
8723                ActivityInfo destAi = dest.get(i).activityInfo;
8724                if (destAi.name == filterAi.name
8725                        && destAi.packageName == filterAi.packageName) {
8726                    return false;
8727                }
8728            }
8729            return true;
8730        }
8731
8732        @Override
8733        protected ActivityIntentInfo[] newArray(int size) {
8734            return new ActivityIntentInfo[size];
8735        }
8736
8737        @Override
8738        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8739            if (!sUserManager.exists(userId)) return true;
8740            PackageParser.Package p = filter.activity.owner;
8741            if (p != null) {
8742                PackageSetting ps = (PackageSetting)p.mExtras;
8743                if (ps != null) {
8744                    // System apps are never considered stopped for purposes of
8745                    // filtering, because there may be no way for the user to
8746                    // actually re-launch them.
8747                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8748                            && ps.getStopped(userId);
8749                }
8750            }
8751            return false;
8752        }
8753
8754        @Override
8755        protected boolean isPackageForFilter(String packageName,
8756                PackageParser.ActivityIntentInfo info) {
8757            return packageName.equals(info.activity.owner.packageName);
8758        }
8759
8760        @Override
8761        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8762                int match, int userId) {
8763            if (!sUserManager.exists(userId)) return null;
8764            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8765                return null;
8766            }
8767            final PackageParser.Activity activity = info.activity;
8768            if (mSafeMode && (activity.info.applicationInfo.flags
8769                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8770                return null;
8771            }
8772            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8773            if (ps == null) {
8774                return null;
8775            }
8776            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8777                    ps.readUserState(userId), userId);
8778            if (ai == null) {
8779                return null;
8780            }
8781            final ResolveInfo res = new ResolveInfo();
8782            res.activityInfo = ai;
8783            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8784                res.filter = info;
8785            }
8786            if (info != null) {
8787                res.handleAllWebDataURI = info.handleAllWebDataURI();
8788            }
8789            res.priority = info.getPriority();
8790            res.preferredOrder = activity.owner.mPreferredOrder;
8791            //System.out.println("Result: " + res.activityInfo.className +
8792            //                   " = " + res.priority);
8793            res.match = match;
8794            res.isDefault = info.hasDefault;
8795            res.labelRes = info.labelRes;
8796            res.nonLocalizedLabel = info.nonLocalizedLabel;
8797            if (userNeedsBadging(userId)) {
8798                res.noResourceId = true;
8799            } else {
8800                res.icon = info.icon;
8801            }
8802            res.iconResourceId = info.icon;
8803            res.system = res.activityInfo.applicationInfo.isSystemApp();
8804            return res;
8805        }
8806
8807        @Override
8808        protected void sortResults(List<ResolveInfo> results) {
8809            Collections.sort(results, mResolvePrioritySorter);
8810        }
8811
8812        @Override
8813        protected void dumpFilter(PrintWriter out, String prefix,
8814                PackageParser.ActivityIntentInfo filter) {
8815            out.print(prefix); out.print(
8816                    Integer.toHexString(System.identityHashCode(filter.activity)));
8817                    out.print(' ');
8818                    filter.activity.printComponentShortName(out);
8819                    out.print(" filter ");
8820                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8821        }
8822
8823        @Override
8824        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8825            return filter.activity;
8826        }
8827
8828        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8829            PackageParser.Activity activity = (PackageParser.Activity)label;
8830            out.print(prefix); out.print(
8831                    Integer.toHexString(System.identityHashCode(activity)));
8832                    out.print(' ');
8833                    activity.printComponentShortName(out);
8834            if (count > 1) {
8835                out.print(" ("); out.print(count); out.print(" filters)");
8836            }
8837            out.println();
8838        }
8839
8840//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8841//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8842//            final List<ResolveInfo> retList = Lists.newArrayList();
8843//            while (i.hasNext()) {
8844//                final ResolveInfo resolveInfo = i.next();
8845//                if (isEnabledLP(resolveInfo.activityInfo)) {
8846//                    retList.add(resolveInfo);
8847//                }
8848//            }
8849//            return retList;
8850//        }
8851
8852        // Keys are String (activity class name), values are Activity.
8853        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8854                = new ArrayMap<ComponentName, PackageParser.Activity>();
8855        private int mFlags;
8856    }
8857
8858    private final class ServiceIntentResolver
8859            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8860        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8861                boolean defaultOnly, int userId) {
8862            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8863            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8864        }
8865
8866        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8867                int userId) {
8868            if (!sUserManager.exists(userId)) return null;
8869            mFlags = flags;
8870            return super.queryIntent(intent, resolvedType,
8871                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8872        }
8873
8874        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8875                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8876            if (!sUserManager.exists(userId)) return null;
8877            if (packageServices == null) {
8878                return null;
8879            }
8880            mFlags = flags;
8881            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8882            final int N = packageServices.size();
8883            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8884                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8885
8886            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8887            for (int i = 0; i < N; ++i) {
8888                intentFilters = packageServices.get(i).intents;
8889                if (intentFilters != null && intentFilters.size() > 0) {
8890                    PackageParser.ServiceIntentInfo[] array =
8891                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8892                    intentFilters.toArray(array);
8893                    listCut.add(array);
8894                }
8895            }
8896            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8897        }
8898
8899        public final void addService(PackageParser.Service s) {
8900            mServices.put(s.getComponentName(), s);
8901            if (DEBUG_SHOW_INFO) {
8902                Log.v(TAG, "  "
8903                        + (s.info.nonLocalizedLabel != null
8904                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8905                Log.v(TAG, "    Class=" + s.info.name);
8906            }
8907            final int NI = s.intents.size();
8908            int j;
8909            for (j=0; j<NI; j++) {
8910                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8911                if (DEBUG_SHOW_INFO) {
8912                    Log.v(TAG, "    IntentFilter:");
8913                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8914                }
8915                if (!intent.debugCheck()) {
8916                    Log.w(TAG, "==> For Service " + s.info.name);
8917                }
8918                addFilter(intent);
8919            }
8920        }
8921
8922        public final void removeService(PackageParser.Service s) {
8923            mServices.remove(s.getComponentName());
8924            if (DEBUG_SHOW_INFO) {
8925                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8926                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8927                Log.v(TAG, "    Class=" + s.info.name);
8928            }
8929            final int NI = s.intents.size();
8930            int j;
8931            for (j=0; j<NI; j++) {
8932                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8933                if (DEBUG_SHOW_INFO) {
8934                    Log.v(TAG, "    IntentFilter:");
8935                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8936                }
8937                removeFilter(intent);
8938            }
8939        }
8940
8941        @Override
8942        protected boolean allowFilterResult(
8943                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8944            ServiceInfo filterSi = filter.service.info;
8945            for (int i=dest.size()-1; i>=0; i--) {
8946                ServiceInfo destAi = dest.get(i).serviceInfo;
8947                if (destAi.name == filterSi.name
8948                        && destAi.packageName == filterSi.packageName) {
8949                    return false;
8950                }
8951            }
8952            return true;
8953        }
8954
8955        @Override
8956        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8957            return new PackageParser.ServiceIntentInfo[size];
8958        }
8959
8960        @Override
8961        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8962            if (!sUserManager.exists(userId)) return true;
8963            PackageParser.Package p = filter.service.owner;
8964            if (p != null) {
8965                PackageSetting ps = (PackageSetting)p.mExtras;
8966                if (ps != null) {
8967                    // System apps are never considered stopped for purposes of
8968                    // filtering, because there may be no way for the user to
8969                    // actually re-launch them.
8970                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8971                            && ps.getStopped(userId);
8972                }
8973            }
8974            return false;
8975        }
8976
8977        @Override
8978        protected boolean isPackageForFilter(String packageName,
8979                PackageParser.ServiceIntentInfo info) {
8980            return packageName.equals(info.service.owner.packageName);
8981        }
8982
8983        @Override
8984        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8985                int match, int userId) {
8986            if (!sUserManager.exists(userId)) return null;
8987            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8988            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8989                return null;
8990            }
8991            final PackageParser.Service service = info.service;
8992            if (mSafeMode && (service.info.applicationInfo.flags
8993                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8994                return null;
8995            }
8996            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8997            if (ps == null) {
8998                return null;
8999            }
9000            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9001                    ps.readUserState(userId), userId);
9002            if (si == null) {
9003                return null;
9004            }
9005            final ResolveInfo res = new ResolveInfo();
9006            res.serviceInfo = si;
9007            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9008                res.filter = filter;
9009            }
9010            res.priority = info.getPriority();
9011            res.preferredOrder = service.owner.mPreferredOrder;
9012            res.match = match;
9013            res.isDefault = info.hasDefault;
9014            res.labelRes = info.labelRes;
9015            res.nonLocalizedLabel = info.nonLocalizedLabel;
9016            res.icon = info.icon;
9017            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9018            return res;
9019        }
9020
9021        @Override
9022        protected void sortResults(List<ResolveInfo> results) {
9023            Collections.sort(results, mResolvePrioritySorter);
9024        }
9025
9026        @Override
9027        protected void dumpFilter(PrintWriter out, String prefix,
9028                PackageParser.ServiceIntentInfo filter) {
9029            out.print(prefix); out.print(
9030                    Integer.toHexString(System.identityHashCode(filter.service)));
9031                    out.print(' ');
9032                    filter.service.printComponentShortName(out);
9033                    out.print(" filter ");
9034                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9035        }
9036
9037        @Override
9038        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9039            return filter.service;
9040        }
9041
9042        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9043            PackageParser.Service service = (PackageParser.Service)label;
9044            out.print(prefix); out.print(
9045                    Integer.toHexString(System.identityHashCode(service)));
9046                    out.print(' ');
9047                    service.printComponentShortName(out);
9048            if (count > 1) {
9049                out.print(" ("); out.print(count); out.print(" filters)");
9050            }
9051            out.println();
9052        }
9053
9054//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9055//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9056//            final List<ResolveInfo> retList = Lists.newArrayList();
9057//            while (i.hasNext()) {
9058//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9059//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9060//                    retList.add(resolveInfo);
9061//                }
9062//            }
9063//            return retList;
9064//        }
9065
9066        // Keys are String (activity class name), values are Activity.
9067        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9068                = new ArrayMap<ComponentName, PackageParser.Service>();
9069        private int mFlags;
9070    };
9071
9072    private final class ProviderIntentResolver
9073            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9074        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9075                boolean defaultOnly, int userId) {
9076            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9077            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9078        }
9079
9080        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9081                int userId) {
9082            if (!sUserManager.exists(userId))
9083                return null;
9084            mFlags = flags;
9085            return super.queryIntent(intent, resolvedType,
9086                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9087        }
9088
9089        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9090                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9091            if (!sUserManager.exists(userId))
9092                return null;
9093            if (packageProviders == null) {
9094                return null;
9095            }
9096            mFlags = flags;
9097            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9098            final int N = packageProviders.size();
9099            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9100                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9101
9102            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9103            for (int i = 0; i < N; ++i) {
9104                intentFilters = packageProviders.get(i).intents;
9105                if (intentFilters != null && intentFilters.size() > 0) {
9106                    PackageParser.ProviderIntentInfo[] array =
9107                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9108                    intentFilters.toArray(array);
9109                    listCut.add(array);
9110                }
9111            }
9112            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9113        }
9114
9115        public final void addProvider(PackageParser.Provider p) {
9116            if (mProviders.containsKey(p.getComponentName())) {
9117                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9118                return;
9119            }
9120
9121            mProviders.put(p.getComponentName(), p);
9122            if (DEBUG_SHOW_INFO) {
9123                Log.v(TAG, "  "
9124                        + (p.info.nonLocalizedLabel != null
9125                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9126                Log.v(TAG, "    Class=" + p.info.name);
9127            }
9128            final int NI = p.intents.size();
9129            int j;
9130            for (j = 0; j < NI; j++) {
9131                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9132                if (DEBUG_SHOW_INFO) {
9133                    Log.v(TAG, "    IntentFilter:");
9134                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9135                }
9136                if (!intent.debugCheck()) {
9137                    Log.w(TAG, "==> For Provider " + p.info.name);
9138                }
9139                addFilter(intent);
9140            }
9141        }
9142
9143        public final void removeProvider(PackageParser.Provider p) {
9144            mProviders.remove(p.getComponentName());
9145            if (DEBUG_SHOW_INFO) {
9146                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9147                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9148                Log.v(TAG, "    Class=" + p.info.name);
9149            }
9150            final int NI = p.intents.size();
9151            int j;
9152            for (j = 0; j < NI; j++) {
9153                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9154                if (DEBUG_SHOW_INFO) {
9155                    Log.v(TAG, "    IntentFilter:");
9156                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9157                }
9158                removeFilter(intent);
9159            }
9160        }
9161
9162        @Override
9163        protected boolean allowFilterResult(
9164                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9165            ProviderInfo filterPi = filter.provider.info;
9166            for (int i = dest.size() - 1; i >= 0; i--) {
9167                ProviderInfo destPi = dest.get(i).providerInfo;
9168                if (destPi.name == filterPi.name
9169                        && destPi.packageName == filterPi.packageName) {
9170                    return false;
9171                }
9172            }
9173            return true;
9174        }
9175
9176        @Override
9177        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9178            return new PackageParser.ProviderIntentInfo[size];
9179        }
9180
9181        @Override
9182        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9183            if (!sUserManager.exists(userId))
9184                return true;
9185            PackageParser.Package p = filter.provider.owner;
9186            if (p != null) {
9187                PackageSetting ps = (PackageSetting) p.mExtras;
9188                if (ps != null) {
9189                    // System apps are never considered stopped for purposes of
9190                    // filtering, because there may be no way for the user to
9191                    // actually re-launch them.
9192                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9193                            && ps.getStopped(userId);
9194                }
9195            }
9196            return false;
9197        }
9198
9199        @Override
9200        protected boolean isPackageForFilter(String packageName,
9201                PackageParser.ProviderIntentInfo info) {
9202            return packageName.equals(info.provider.owner.packageName);
9203        }
9204
9205        @Override
9206        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9207                int match, int userId) {
9208            if (!sUserManager.exists(userId))
9209                return null;
9210            final PackageParser.ProviderIntentInfo info = filter;
9211            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9212                return null;
9213            }
9214            final PackageParser.Provider provider = info.provider;
9215            if (mSafeMode && (provider.info.applicationInfo.flags
9216                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9217                return null;
9218            }
9219            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9220            if (ps == null) {
9221                return null;
9222            }
9223            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9224                    ps.readUserState(userId), userId);
9225            if (pi == null) {
9226                return null;
9227            }
9228            final ResolveInfo res = new ResolveInfo();
9229            res.providerInfo = pi;
9230            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9231                res.filter = filter;
9232            }
9233            res.priority = info.getPriority();
9234            res.preferredOrder = provider.owner.mPreferredOrder;
9235            res.match = match;
9236            res.isDefault = info.hasDefault;
9237            res.labelRes = info.labelRes;
9238            res.nonLocalizedLabel = info.nonLocalizedLabel;
9239            res.icon = info.icon;
9240            res.system = res.providerInfo.applicationInfo.isSystemApp();
9241            return res;
9242        }
9243
9244        @Override
9245        protected void sortResults(List<ResolveInfo> results) {
9246            Collections.sort(results, mResolvePrioritySorter);
9247        }
9248
9249        @Override
9250        protected void dumpFilter(PrintWriter out, String prefix,
9251                PackageParser.ProviderIntentInfo filter) {
9252            out.print(prefix);
9253            out.print(
9254                    Integer.toHexString(System.identityHashCode(filter.provider)));
9255            out.print(' ');
9256            filter.provider.printComponentShortName(out);
9257            out.print(" filter ");
9258            out.println(Integer.toHexString(System.identityHashCode(filter)));
9259        }
9260
9261        @Override
9262        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9263            return filter.provider;
9264        }
9265
9266        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9267            PackageParser.Provider provider = (PackageParser.Provider)label;
9268            out.print(prefix); out.print(
9269                    Integer.toHexString(System.identityHashCode(provider)));
9270                    out.print(' ');
9271                    provider.printComponentShortName(out);
9272            if (count > 1) {
9273                out.print(" ("); out.print(count); out.print(" filters)");
9274            }
9275            out.println();
9276        }
9277
9278        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9279                = new ArrayMap<ComponentName, PackageParser.Provider>();
9280        private int mFlags;
9281    };
9282
9283    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9284            new Comparator<ResolveInfo>() {
9285        public int compare(ResolveInfo r1, ResolveInfo r2) {
9286            int v1 = r1.priority;
9287            int v2 = r2.priority;
9288            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9289            if (v1 != v2) {
9290                return (v1 > v2) ? -1 : 1;
9291            }
9292            v1 = r1.preferredOrder;
9293            v2 = r2.preferredOrder;
9294            if (v1 != v2) {
9295                return (v1 > v2) ? -1 : 1;
9296            }
9297            if (r1.isDefault != r2.isDefault) {
9298                return r1.isDefault ? -1 : 1;
9299            }
9300            v1 = r1.match;
9301            v2 = r2.match;
9302            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9303            if (v1 != v2) {
9304                return (v1 > v2) ? -1 : 1;
9305            }
9306            if (r1.system != r2.system) {
9307                return r1.system ? -1 : 1;
9308            }
9309            return 0;
9310        }
9311    };
9312
9313    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9314            new Comparator<ProviderInfo>() {
9315        public int compare(ProviderInfo p1, ProviderInfo p2) {
9316            final int v1 = p1.initOrder;
9317            final int v2 = p2.initOrder;
9318            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9319        }
9320    };
9321
9322    final void sendPackageBroadcast(final String action, final String pkg,
9323            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9324            final int[] userIds) {
9325        mHandler.post(new Runnable() {
9326            @Override
9327            public void run() {
9328                try {
9329                    final IActivityManager am = ActivityManagerNative.getDefault();
9330                    if (am == null) return;
9331                    final int[] resolvedUserIds;
9332                    if (userIds == null) {
9333                        resolvedUserIds = am.getRunningUserIds();
9334                    } else {
9335                        resolvedUserIds = userIds;
9336                    }
9337                    for (int id : resolvedUserIds) {
9338                        final Intent intent = new Intent(action,
9339                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9340                        if (extras != null) {
9341                            intent.putExtras(extras);
9342                        }
9343                        if (targetPkg != null) {
9344                            intent.setPackage(targetPkg);
9345                        }
9346                        // Modify the UID when posting to other users
9347                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9348                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9349                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9350                            intent.putExtra(Intent.EXTRA_UID, uid);
9351                        }
9352                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9353                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9354                        if (DEBUG_BROADCASTS) {
9355                            RuntimeException here = new RuntimeException("here");
9356                            here.fillInStackTrace();
9357                            Slog.d(TAG, "Sending to user " + id + ": "
9358                                    + intent.toShortString(false, true, false, false)
9359                                    + " " + intent.getExtras(), here);
9360                        }
9361                        am.broadcastIntent(null, intent, null, finishedReceiver,
9362                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9363                                null, finishedReceiver != null, false, id);
9364                    }
9365                } catch (RemoteException ex) {
9366                }
9367            }
9368        });
9369    }
9370
9371    /**
9372     * Check if the external storage media is available. This is true if there
9373     * is a mounted external storage medium or if the external storage is
9374     * emulated.
9375     */
9376    private boolean isExternalMediaAvailable() {
9377        return mMediaMounted || Environment.isExternalStorageEmulated();
9378    }
9379
9380    @Override
9381    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9382        // writer
9383        synchronized (mPackages) {
9384            if (!isExternalMediaAvailable()) {
9385                // If the external storage is no longer mounted at this point,
9386                // the caller may not have been able to delete all of this
9387                // packages files and can not delete any more.  Bail.
9388                return null;
9389            }
9390            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9391            if (lastPackage != null) {
9392                pkgs.remove(lastPackage);
9393            }
9394            if (pkgs.size() > 0) {
9395                return pkgs.get(0);
9396            }
9397        }
9398        return null;
9399    }
9400
9401    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9402        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9403                userId, andCode ? 1 : 0, packageName);
9404        if (mSystemReady) {
9405            msg.sendToTarget();
9406        } else {
9407            if (mPostSystemReadyMessages == null) {
9408                mPostSystemReadyMessages = new ArrayList<>();
9409            }
9410            mPostSystemReadyMessages.add(msg);
9411        }
9412    }
9413
9414    void startCleaningPackages() {
9415        // reader
9416        synchronized (mPackages) {
9417            if (!isExternalMediaAvailable()) {
9418                return;
9419            }
9420            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9421                return;
9422            }
9423        }
9424        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9425        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9426        IActivityManager am = ActivityManagerNative.getDefault();
9427        if (am != null) {
9428            try {
9429                am.startService(null, intent, null, mContext.getOpPackageName(),
9430                        UserHandle.USER_OWNER);
9431            } catch (RemoteException e) {
9432            }
9433        }
9434    }
9435
9436    @Override
9437    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9438            int installFlags, String installerPackageName, VerificationParams verificationParams,
9439            String packageAbiOverride) {
9440        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9441                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9442    }
9443
9444    @Override
9445    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9446            int installFlags, String installerPackageName, VerificationParams verificationParams,
9447            String packageAbiOverride, int userId) {
9448        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9449
9450        final int callingUid = Binder.getCallingUid();
9451        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9452
9453        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9454            try {
9455                if (observer != null) {
9456                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9457                }
9458            } catch (RemoteException re) {
9459            }
9460            return;
9461        }
9462
9463        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9464            installFlags |= PackageManager.INSTALL_FROM_ADB;
9465
9466        } else {
9467            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9468            // about installerPackageName.
9469
9470            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9471            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9472        }
9473
9474        UserHandle user;
9475        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9476            user = UserHandle.ALL;
9477        } else {
9478            user = new UserHandle(userId);
9479        }
9480
9481        // Only system components can circumvent runtime permissions when installing.
9482        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9483                && mContext.checkCallingOrSelfPermission(Manifest.permission
9484                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9485            throw new SecurityException("You need the "
9486                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9487                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9488        }
9489
9490        verificationParams.setInstallerUid(callingUid);
9491
9492        final File originFile = new File(originPath);
9493        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9494
9495        final Message msg = mHandler.obtainMessage(INIT_COPY);
9496        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9497                null, verificationParams, user, packageAbiOverride, null);
9498        mHandler.sendMessage(msg);
9499    }
9500
9501    void installStage(String packageName, File stagedDir, String stagedCid,
9502            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9503            String installerPackageName, int installerUid, UserHandle user) {
9504        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9505                params.referrerUri, installerUid, null);
9506        verifParams.setInstallerUid(installerUid);
9507
9508        final OriginInfo origin;
9509        if (stagedDir != null) {
9510            origin = OriginInfo.fromStagedFile(stagedDir);
9511        } else {
9512            origin = OriginInfo.fromStagedContainer(stagedCid);
9513        }
9514
9515        final Message msg = mHandler.obtainMessage(INIT_COPY);
9516        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9517                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride,
9518                params.grantedRuntimePermissions);
9519        mHandler.sendMessage(msg);
9520    }
9521
9522    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9523        Bundle extras = new Bundle(1);
9524        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9525
9526        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9527                packageName, extras, null, null, new int[] {userId});
9528        try {
9529            IActivityManager am = ActivityManagerNative.getDefault();
9530            final boolean isSystem =
9531                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9532            if (isSystem && am.isUserRunning(userId, false)) {
9533                // The just-installed/enabled app is bundled on the system, so presumed
9534                // to be able to run automatically without needing an explicit launch.
9535                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9536                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9537                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9538                        .setPackage(packageName);
9539                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9540                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9541            }
9542        } catch (RemoteException e) {
9543            // shouldn't happen
9544            Slog.w(TAG, "Unable to bootstrap installed package", e);
9545        }
9546    }
9547
9548    @Override
9549    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9550            int userId) {
9551        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9552        PackageSetting pkgSetting;
9553        final int uid = Binder.getCallingUid();
9554        enforceCrossUserPermission(uid, userId, true, true,
9555                "setApplicationHiddenSetting for user " + userId);
9556
9557        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9558            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9559            return false;
9560        }
9561
9562        long callingId = Binder.clearCallingIdentity();
9563        try {
9564            boolean sendAdded = false;
9565            boolean sendRemoved = false;
9566            // writer
9567            synchronized (mPackages) {
9568                pkgSetting = mSettings.mPackages.get(packageName);
9569                if (pkgSetting == null) {
9570                    return false;
9571                }
9572                if (pkgSetting.getHidden(userId) != hidden) {
9573                    pkgSetting.setHidden(hidden, userId);
9574                    mSettings.writePackageRestrictionsLPr(userId);
9575                    if (hidden) {
9576                        sendRemoved = true;
9577                    } else {
9578                        sendAdded = true;
9579                    }
9580                }
9581            }
9582            if (sendAdded) {
9583                sendPackageAddedForUser(packageName, pkgSetting, userId);
9584                return true;
9585            }
9586            if (sendRemoved) {
9587                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9588                        "hiding pkg");
9589                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9590                return true;
9591            }
9592        } finally {
9593            Binder.restoreCallingIdentity(callingId);
9594        }
9595        return false;
9596    }
9597
9598    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9599            int userId) {
9600        final PackageRemovedInfo info = new PackageRemovedInfo();
9601        info.removedPackage = packageName;
9602        info.removedUsers = new int[] {userId};
9603        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9604        info.sendBroadcast(false, false, false);
9605    }
9606
9607    /**
9608     * Returns true if application is not found or there was an error. Otherwise it returns
9609     * the hidden state of the package for the given user.
9610     */
9611    @Override
9612    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9613        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9614        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9615                false, "getApplicationHidden for user " + userId);
9616        PackageSetting pkgSetting;
9617        long callingId = Binder.clearCallingIdentity();
9618        try {
9619            // writer
9620            synchronized (mPackages) {
9621                pkgSetting = mSettings.mPackages.get(packageName);
9622                if (pkgSetting == null) {
9623                    return true;
9624                }
9625                return pkgSetting.getHidden(userId);
9626            }
9627        } finally {
9628            Binder.restoreCallingIdentity(callingId);
9629        }
9630    }
9631
9632    /**
9633     * @hide
9634     */
9635    @Override
9636    public int installExistingPackageAsUser(String packageName, int userId) {
9637        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9638                null);
9639        PackageSetting pkgSetting;
9640        final int uid = Binder.getCallingUid();
9641        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9642                + userId);
9643        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9644            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9645        }
9646
9647        long callingId = Binder.clearCallingIdentity();
9648        try {
9649            boolean sendAdded = false;
9650
9651            // writer
9652            synchronized (mPackages) {
9653                pkgSetting = mSettings.mPackages.get(packageName);
9654                if (pkgSetting == null) {
9655                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9656                }
9657                if (!pkgSetting.getInstalled(userId)) {
9658                    pkgSetting.setInstalled(true, userId);
9659                    pkgSetting.setHidden(false, userId);
9660                    mSettings.writePackageRestrictionsLPr(userId);
9661                    sendAdded = true;
9662                }
9663            }
9664
9665            if (sendAdded) {
9666                sendPackageAddedForUser(packageName, pkgSetting, userId);
9667            }
9668        } finally {
9669            Binder.restoreCallingIdentity(callingId);
9670        }
9671
9672        return PackageManager.INSTALL_SUCCEEDED;
9673    }
9674
9675    boolean isUserRestricted(int userId, String restrictionKey) {
9676        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9677        if (restrictions.getBoolean(restrictionKey, false)) {
9678            Log.w(TAG, "User is restricted: " + restrictionKey);
9679            return true;
9680        }
9681        return false;
9682    }
9683
9684    @Override
9685    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9686        mContext.enforceCallingOrSelfPermission(
9687                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9688                "Only package verification agents can verify applications");
9689
9690        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9691        final PackageVerificationResponse response = new PackageVerificationResponse(
9692                verificationCode, Binder.getCallingUid());
9693        msg.arg1 = id;
9694        msg.obj = response;
9695        mHandler.sendMessage(msg);
9696    }
9697
9698    @Override
9699    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9700            long millisecondsToDelay) {
9701        mContext.enforceCallingOrSelfPermission(
9702                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9703                "Only package verification agents can extend verification timeouts");
9704
9705        final PackageVerificationState state = mPendingVerification.get(id);
9706        final PackageVerificationResponse response = new PackageVerificationResponse(
9707                verificationCodeAtTimeout, Binder.getCallingUid());
9708
9709        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9710            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9711        }
9712        if (millisecondsToDelay < 0) {
9713            millisecondsToDelay = 0;
9714        }
9715        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9716                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9717            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9718        }
9719
9720        if ((state != null) && !state.timeoutExtended()) {
9721            state.extendTimeout();
9722
9723            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9724            msg.arg1 = id;
9725            msg.obj = response;
9726            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9727        }
9728    }
9729
9730    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9731            int verificationCode, UserHandle user) {
9732        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9733        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9734        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9735        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9736        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9737
9738        mContext.sendBroadcastAsUser(intent, user,
9739                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9740    }
9741
9742    private ComponentName matchComponentForVerifier(String packageName,
9743            List<ResolveInfo> receivers) {
9744        ActivityInfo targetReceiver = null;
9745
9746        final int NR = receivers.size();
9747        for (int i = 0; i < NR; i++) {
9748            final ResolveInfo info = receivers.get(i);
9749            if (info.activityInfo == null) {
9750                continue;
9751            }
9752
9753            if (packageName.equals(info.activityInfo.packageName)) {
9754                targetReceiver = info.activityInfo;
9755                break;
9756            }
9757        }
9758
9759        if (targetReceiver == null) {
9760            return null;
9761        }
9762
9763        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9764    }
9765
9766    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9767            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9768        if (pkgInfo.verifiers.length == 0) {
9769            return null;
9770        }
9771
9772        final int N = pkgInfo.verifiers.length;
9773        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9774        for (int i = 0; i < N; i++) {
9775            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9776
9777            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9778                    receivers);
9779            if (comp == null) {
9780                continue;
9781            }
9782
9783            final int verifierUid = getUidForVerifier(verifierInfo);
9784            if (verifierUid == -1) {
9785                continue;
9786            }
9787
9788            if (DEBUG_VERIFY) {
9789                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9790                        + " with the correct signature");
9791            }
9792            sufficientVerifiers.add(comp);
9793            verificationState.addSufficientVerifier(verifierUid);
9794        }
9795
9796        return sufficientVerifiers;
9797    }
9798
9799    private int getUidForVerifier(VerifierInfo verifierInfo) {
9800        synchronized (mPackages) {
9801            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9802            if (pkg == null) {
9803                return -1;
9804            } else if (pkg.mSignatures.length != 1) {
9805                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9806                        + " has more than one signature; ignoring");
9807                return -1;
9808            }
9809
9810            /*
9811             * If the public key of the package's signature does not match
9812             * our expected public key, then this is a different package and
9813             * we should skip.
9814             */
9815
9816            final byte[] expectedPublicKey;
9817            try {
9818                final Signature verifierSig = pkg.mSignatures[0];
9819                final PublicKey publicKey = verifierSig.getPublicKey();
9820                expectedPublicKey = publicKey.getEncoded();
9821            } catch (CertificateException e) {
9822                return -1;
9823            }
9824
9825            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9826
9827            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9828                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9829                        + " does not have the expected public key; ignoring");
9830                return -1;
9831            }
9832
9833            return pkg.applicationInfo.uid;
9834        }
9835    }
9836
9837    @Override
9838    public void finishPackageInstall(int token) {
9839        enforceSystemOrRoot("Only the system is allowed to finish installs");
9840
9841        if (DEBUG_INSTALL) {
9842            Slog.v(TAG, "BM finishing package install for " + token);
9843        }
9844
9845        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9846        mHandler.sendMessage(msg);
9847    }
9848
9849    /**
9850     * Get the verification agent timeout.
9851     *
9852     * @return verification timeout in milliseconds
9853     */
9854    private long getVerificationTimeout() {
9855        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9856                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9857                DEFAULT_VERIFICATION_TIMEOUT);
9858    }
9859
9860    /**
9861     * Get the default verification agent response code.
9862     *
9863     * @return default verification response code
9864     */
9865    private int getDefaultVerificationResponse() {
9866        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9867                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9868                DEFAULT_VERIFICATION_RESPONSE);
9869    }
9870
9871    /**
9872     * Check whether or not package verification has been enabled.
9873     *
9874     * @return true if verification should be performed
9875     */
9876    private boolean isVerificationEnabled(int userId, int installFlags) {
9877        if (!DEFAULT_VERIFY_ENABLE) {
9878            return false;
9879        }
9880
9881        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9882
9883        // Check if installing from ADB
9884        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9885            // Do not run verification in a test harness environment
9886            if (ActivityManager.isRunningInTestHarness()) {
9887                return false;
9888            }
9889            if (ensureVerifyAppsEnabled) {
9890                return true;
9891            }
9892            // Check if the developer does not want package verification for ADB installs
9893            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9894                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9895                return false;
9896            }
9897        }
9898
9899        if (ensureVerifyAppsEnabled) {
9900            return true;
9901        }
9902
9903        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9904                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9905    }
9906
9907    @Override
9908    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9909            throws RemoteException {
9910        mContext.enforceCallingOrSelfPermission(
9911                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9912                "Only intentfilter verification agents can verify applications");
9913
9914        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9915        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9916                Binder.getCallingUid(), verificationCode, failedDomains);
9917        msg.arg1 = id;
9918        msg.obj = response;
9919        mHandler.sendMessage(msg);
9920    }
9921
9922    @Override
9923    public int getIntentVerificationStatus(String packageName, int userId) {
9924        synchronized (mPackages) {
9925            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9926        }
9927    }
9928
9929    @Override
9930    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9931        mContext.enforceCallingOrSelfPermission(
9932                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9933
9934        boolean result = false;
9935        synchronized (mPackages) {
9936            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9937        }
9938        if (result) {
9939            scheduleWritePackageRestrictionsLocked(userId);
9940        }
9941        return result;
9942    }
9943
9944    @Override
9945    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9946        synchronized (mPackages) {
9947            return mSettings.getIntentFilterVerificationsLPr(packageName);
9948        }
9949    }
9950
9951    @Override
9952    public List<IntentFilter> getAllIntentFilters(String packageName) {
9953        if (TextUtils.isEmpty(packageName)) {
9954            return Collections.<IntentFilter>emptyList();
9955        }
9956        synchronized (mPackages) {
9957            PackageParser.Package pkg = mPackages.get(packageName);
9958            if (pkg == null || pkg.activities == null) {
9959                return Collections.<IntentFilter>emptyList();
9960            }
9961            final int count = pkg.activities.size();
9962            ArrayList<IntentFilter> result = new ArrayList<>();
9963            for (int n=0; n<count; n++) {
9964                PackageParser.Activity activity = pkg.activities.get(n);
9965                if (activity.intents != null || activity.intents.size() > 0) {
9966                    result.addAll(activity.intents);
9967                }
9968            }
9969            return result;
9970        }
9971    }
9972
9973    @Override
9974    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9975        mContext.enforceCallingOrSelfPermission(
9976                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9977
9978        synchronized (mPackages) {
9979            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
9980            if (packageName != null) {
9981                result |= updateIntentVerificationStatus(packageName,
9982                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9983                        userId);
9984                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
9985                        packageName, userId);
9986            }
9987            return result;
9988        }
9989    }
9990
9991    @Override
9992    public String getDefaultBrowserPackageName(int userId) {
9993        synchronized (mPackages) {
9994            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9995        }
9996    }
9997
9998    /**
9999     * Get the "allow unknown sources" setting.
10000     *
10001     * @return the current "allow unknown sources" setting
10002     */
10003    private int getUnknownSourcesSettings() {
10004        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10005                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10006                -1);
10007    }
10008
10009    @Override
10010    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10011        final int uid = Binder.getCallingUid();
10012        // writer
10013        synchronized (mPackages) {
10014            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10015            if (targetPackageSetting == null) {
10016                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10017            }
10018
10019            PackageSetting installerPackageSetting;
10020            if (installerPackageName != null) {
10021                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10022                if (installerPackageSetting == null) {
10023                    throw new IllegalArgumentException("Unknown installer package: "
10024                            + installerPackageName);
10025                }
10026            } else {
10027                installerPackageSetting = null;
10028            }
10029
10030            Signature[] callerSignature;
10031            Object obj = mSettings.getUserIdLPr(uid);
10032            if (obj != null) {
10033                if (obj instanceof SharedUserSetting) {
10034                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10035                } else if (obj instanceof PackageSetting) {
10036                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10037                } else {
10038                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10039                }
10040            } else {
10041                throw new SecurityException("Unknown calling uid " + uid);
10042            }
10043
10044            // Verify: can't set installerPackageName to a package that is
10045            // not signed with the same cert as the caller.
10046            if (installerPackageSetting != null) {
10047                if (compareSignatures(callerSignature,
10048                        installerPackageSetting.signatures.mSignatures)
10049                        != PackageManager.SIGNATURE_MATCH) {
10050                    throw new SecurityException(
10051                            "Caller does not have same cert as new installer package "
10052                            + installerPackageName);
10053                }
10054            }
10055
10056            // Verify: if target already has an installer package, it must
10057            // be signed with the same cert as the caller.
10058            if (targetPackageSetting.installerPackageName != null) {
10059                PackageSetting setting = mSettings.mPackages.get(
10060                        targetPackageSetting.installerPackageName);
10061                // If the currently set package isn't valid, then it's always
10062                // okay to change it.
10063                if (setting != null) {
10064                    if (compareSignatures(callerSignature,
10065                            setting.signatures.mSignatures)
10066                            != PackageManager.SIGNATURE_MATCH) {
10067                        throw new SecurityException(
10068                                "Caller does not have same cert as old installer package "
10069                                + targetPackageSetting.installerPackageName);
10070                    }
10071                }
10072            }
10073
10074            // Okay!
10075            targetPackageSetting.installerPackageName = installerPackageName;
10076            scheduleWriteSettingsLocked();
10077        }
10078    }
10079
10080    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10081        // Queue up an async operation since the package installation may take a little while.
10082        mHandler.post(new Runnable() {
10083            public void run() {
10084                mHandler.removeCallbacks(this);
10085                 // Result object to be returned
10086                PackageInstalledInfo res = new PackageInstalledInfo();
10087                res.returnCode = currentStatus;
10088                res.uid = -1;
10089                res.pkg = null;
10090                res.removedInfo = new PackageRemovedInfo();
10091                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10092                    args.doPreInstall(res.returnCode);
10093                    synchronized (mInstallLock) {
10094                        installPackageLI(args, res);
10095                    }
10096                    args.doPostInstall(res.returnCode, res.uid);
10097                }
10098
10099                // A restore should be performed at this point if (a) the install
10100                // succeeded, (b) the operation is not an update, and (c) the new
10101                // package has not opted out of backup participation.
10102                final boolean update = res.removedInfo.removedPackage != null;
10103                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10104                boolean doRestore = !update
10105                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10106
10107                // Set up the post-install work request bookkeeping.  This will be used
10108                // and cleaned up by the post-install event handling regardless of whether
10109                // there's a restore pass performed.  Token values are >= 1.
10110                int token;
10111                if (mNextInstallToken < 0) mNextInstallToken = 1;
10112                token = mNextInstallToken++;
10113
10114                PostInstallData data = new PostInstallData(args, res);
10115                mRunningInstalls.put(token, data);
10116                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10117
10118                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10119                    // Pass responsibility to the Backup Manager.  It will perform a
10120                    // restore if appropriate, then pass responsibility back to the
10121                    // Package Manager to run the post-install observer callbacks
10122                    // and broadcasts.
10123                    IBackupManager bm = IBackupManager.Stub.asInterface(
10124                            ServiceManager.getService(Context.BACKUP_SERVICE));
10125                    if (bm != null) {
10126                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10127                                + " to BM for possible restore");
10128                        try {
10129                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
10130                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10131                            } else {
10132                                doRestore = false;
10133                            }
10134                        } catch (RemoteException e) {
10135                            // can't happen; the backup manager is local
10136                        } catch (Exception e) {
10137                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10138                            doRestore = false;
10139                        }
10140                    } else {
10141                        Slog.e(TAG, "Backup Manager not found!");
10142                        doRestore = false;
10143                    }
10144                }
10145
10146                if (!doRestore) {
10147                    // No restore possible, or the Backup Manager was mysteriously not
10148                    // available -- just fire the post-install work request directly.
10149                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10150                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10151                    mHandler.sendMessage(msg);
10152                }
10153            }
10154        });
10155    }
10156
10157    private abstract class HandlerParams {
10158        private static final int MAX_RETRIES = 4;
10159
10160        /**
10161         * Number of times startCopy() has been attempted and had a non-fatal
10162         * error.
10163         */
10164        private int mRetries = 0;
10165
10166        /** User handle for the user requesting the information or installation. */
10167        private final UserHandle mUser;
10168
10169        HandlerParams(UserHandle user) {
10170            mUser = user;
10171        }
10172
10173        UserHandle getUser() {
10174            return mUser;
10175        }
10176
10177        final boolean startCopy() {
10178            boolean res;
10179            try {
10180                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10181
10182                if (++mRetries > MAX_RETRIES) {
10183                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10184                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10185                    handleServiceError();
10186                    return false;
10187                } else {
10188                    handleStartCopy();
10189                    res = true;
10190                }
10191            } catch (RemoteException e) {
10192                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10193                mHandler.sendEmptyMessage(MCS_RECONNECT);
10194                res = false;
10195            }
10196            handleReturnCode();
10197            return res;
10198        }
10199
10200        final void serviceError() {
10201            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10202            handleServiceError();
10203            handleReturnCode();
10204        }
10205
10206        abstract void handleStartCopy() throws RemoteException;
10207        abstract void handleServiceError();
10208        abstract void handleReturnCode();
10209    }
10210
10211    class MeasureParams extends HandlerParams {
10212        private final PackageStats mStats;
10213        private boolean mSuccess;
10214
10215        private final IPackageStatsObserver mObserver;
10216
10217        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10218            super(new UserHandle(stats.userHandle));
10219            mObserver = observer;
10220            mStats = stats;
10221        }
10222
10223        @Override
10224        public String toString() {
10225            return "MeasureParams{"
10226                + Integer.toHexString(System.identityHashCode(this))
10227                + " " + mStats.packageName + "}";
10228        }
10229
10230        @Override
10231        void handleStartCopy() throws RemoteException {
10232            synchronized (mInstallLock) {
10233                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10234            }
10235
10236            if (mSuccess) {
10237                final boolean mounted;
10238                if (Environment.isExternalStorageEmulated()) {
10239                    mounted = true;
10240                } else {
10241                    final String status = Environment.getExternalStorageState();
10242                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10243                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10244                }
10245
10246                if (mounted) {
10247                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10248
10249                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10250                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10251
10252                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10253                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10254
10255                    // Always subtract cache size, since it's a subdirectory
10256                    mStats.externalDataSize -= mStats.externalCacheSize;
10257
10258                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10259                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10260
10261                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10262                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10263                }
10264            }
10265        }
10266
10267        @Override
10268        void handleReturnCode() {
10269            if (mObserver != null) {
10270                try {
10271                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10272                } catch (RemoteException e) {
10273                    Slog.i(TAG, "Observer no longer exists.");
10274                }
10275            }
10276        }
10277
10278        @Override
10279        void handleServiceError() {
10280            Slog.e(TAG, "Could not measure application " + mStats.packageName
10281                            + " external storage");
10282        }
10283    }
10284
10285    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10286            throws RemoteException {
10287        long result = 0;
10288        for (File path : paths) {
10289            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10290        }
10291        return result;
10292    }
10293
10294    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10295        for (File path : paths) {
10296            try {
10297                mcs.clearDirectory(path.getAbsolutePath());
10298            } catch (RemoteException e) {
10299            }
10300        }
10301    }
10302
10303    static class OriginInfo {
10304        /**
10305         * Location where install is coming from, before it has been
10306         * copied/renamed into place. This could be a single monolithic APK
10307         * file, or a cluster directory. This location may be untrusted.
10308         */
10309        final File file;
10310        final String cid;
10311
10312        /**
10313         * Flag indicating that {@link #file} or {@link #cid} has already been
10314         * staged, meaning downstream users don't need to defensively copy the
10315         * contents.
10316         */
10317        final boolean staged;
10318
10319        /**
10320         * Flag indicating that {@link #file} or {@link #cid} is an already
10321         * installed app that is being moved.
10322         */
10323        final boolean existing;
10324
10325        final String resolvedPath;
10326        final File resolvedFile;
10327
10328        static OriginInfo fromNothing() {
10329            return new OriginInfo(null, null, false, false);
10330        }
10331
10332        static OriginInfo fromUntrustedFile(File file) {
10333            return new OriginInfo(file, null, false, false);
10334        }
10335
10336        static OriginInfo fromExistingFile(File file) {
10337            return new OriginInfo(file, null, false, true);
10338        }
10339
10340        static OriginInfo fromStagedFile(File file) {
10341            return new OriginInfo(file, null, true, false);
10342        }
10343
10344        static OriginInfo fromStagedContainer(String cid) {
10345            return new OriginInfo(null, cid, true, false);
10346        }
10347
10348        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10349            this.file = file;
10350            this.cid = cid;
10351            this.staged = staged;
10352            this.existing = existing;
10353
10354            if (cid != null) {
10355                resolvedPath = PackageHelper.getSdDir(cid);
10356                resolvedFile = new File(resolvedPath);
10357            } else if (file != null) {
10358                resolvedPath = file.getAbsolutePath();
10359                resolvedFile = file;
10360            } else {
10361                resolvedPath = null;
10362                resolvedFile = null;
10363            }
10364        }
10365    }
10366
10367    class MoveInfo {
10368        final int moveId;
10369        final String fromUuid;
10370        final String toUuid;
10371        final String packageName;
10372        final String dataAppName;
10373        final int appId;
10374        final String seinfo;
10375
10376        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10377                String dataAppName, int appId, String seinfo) {
10378            this.moveId = moveId;
10379            this.fromUuid = fromUuid;
10380            this.toUuid = toUuid;
10381            this.packageName = packageName;
10382            this.dataAppName = dataAppName;
10383            this.appId = appId;
10384            this.seinfo = seinfo;
10385        }
10386    }
10387
10388    class InstallParams extends HandlerParams {
10389        final OriginInfo origin;
10390        final MoveInfo move;
10391        final IPackageInstallObserver2 observer;
10392        int installFlags;
10393        final String installerPackageName;
10394        final String volumeUuid;
10395        final VerificationParams verificationParams;
10396        private InstallArgs mArgs;
10397        private int mRet;
10398        final String packageAbiOverride;
10399        final String[] grantedRuntimePermissions;
10400
10401
10402        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10403                int installFlags, String installerPackageName, String volumeUuid,
10404                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10405                String[] grantedPermissions) {
10406            super(user);
10407            this.origin = origin;
10408            this.move = move;
10409            this.observer = observer;
10410            this.installFlags = installFlags;
10411            this.installerPackageName = installerPackageName;
10412            this.volumeUuid = volumeUuid;
10413            this.verificationParams = verificationParams;
10414            this.packageAbiOverride = packageAbiOverride;
10415            this.grantedRuntimePermissions = grantedPermissions;
10416        }
10417
10418        @Override
10419        public String toString() {
10420            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10421                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10422        }
10423
10424        public ManifestDigest getManifestDigest() {
10425            if (verificationParams == null) {
10426                return null;
10427            }
10428            return verificationParams.getManifestDigest();
10429        }
10430
10431        private int installLocationPolicy(PackageInfoLite pkgLite) {
10432            String packageName = pkgLite.packageName;
10433            int installLocation = pkgLite.installLocation;
10434            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10435            // reader
10436            synchronized (mPackages) {
10437                PackageParser.Package pkg = mPackages.get(packageName);
10438                if (pkg != null) {
10439                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10440                        // Check for downgrading.
10441                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10442                            try {
10443                                checkDowngrade(pkg, pkgLite);
10444                            } catch (PackageManagerException e) {
10445                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10446                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10447                            }
10448                        }
10449                        // Check for updated system application.
10450                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10451                            if (onSd) {
10452                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10453                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10454                            }
10455                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10456                        } else {
10457                            if (onSd) {
10458                                // Install flag overrides everything.
10459                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10460                            }
10461                            // If current upgrade specifies particular preference
10462                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10463                                // Application explicitly specified internal.
10464                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10465                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10466                                // App explictly prefers external. Let policy decide
10467                            } else {
10468                                // Prefer previous location
10469                                if (isExternal(pkg)) {
10470                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10471                                }
10472                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10473                            }
10474                        }
10475                    } else {
10476                        // Invalid install. Return error code
10477                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10478                    }
10479                }
10480            }
10481            // All the special cases have been taken care of.
10482            // Return result based on recommended install location.
10483            if (onSd) {
10484                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10485            }
10486            return pkgLite.recommendedInstallLocation;
10487        }
10488
10489        /*
10490         * Invoke remote method to get package information and install
10491         * location values. Override install location based on default
10492         * policy if needed and then create install arguments based
10493         * on the install location.
10494         */
10495        public void handleStartCopy() throws RemoteException {
10496            int ret = PackageManager.INSTALL_SUCCEEDED;
10497
10498            // If we're already staged, we've firmly committed to an install location
10499            if (origin.staged) {
10500                if (origin.file != null) {
10501                    installFlags |= PackageManager.INSTALL_INTERNAL;
10502                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10503                } else if (origin.cid != null) {
10504                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10505                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10506                } else {
10507                    throw new IllegalStateException("Invalid stage location");
10508                }
10509            }
10510
10511            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10512            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10513
10514            PackageInfoLite pkgLite = null;
10515
10516            if (onInt && onSd) {
10517                // Check if both bits are set.
10518                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10519                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10520            } else {
10521                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10522                        packageAbiOverride);
10523
10524                /*
10525                 * If we have too little free space, try to free cache
10526                 * before giving up.
10527                 */
10528                if (!origin.staged && pkgLite.recommendedInstallLocation
10529                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10530                    // TODO: focus freeing disk space on the target device
10531                    final StorageManager storage = StorageManager.from(mContext);
10532                    final long lowThreshold = storage.getStorageLowBytes(
10533                            Environment.getDataDirectory());
10534
10535                    final long sizeBytes = mContainerService.calculateInstalledSize(
10536                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10537
10538                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10539                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10540                                installFlags, packageAbiOverride);
10541                    }
10542
10543                    /*
10544                     * The cache free must have deleted the file we
10545                     * downloaded to install.
10546                     *
10547                     * TODO: fix the "freeCache" call to not delete
10548                     *       the file we care about.
10549                     */
10550                    if (pkgLite.recommendedInstallLocation
10551                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10552                        pkgLite.recommendedInstallLocation
10553                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10554                    }
10555                }
10556            }
10557
10558            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10559                int loc = pkgLite.recommendedInstallLocation;
10560                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10561                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10562                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10563                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10564                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10565                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10566                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10567                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10568                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10569                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10570                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10571                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10572                } else {
10573                    // Override with defaults if needed.
10574                    loc = installLocationPolicy(pkgLite);
10575                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10576                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10577                    } else if (!onSd && !onInt) {
10578                        // Override install location with flags
10579                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10580                            // Set the flag to install on external media.
10581                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10582                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10583                        } else {
10584                            // Make sure the flag for installing on external
10585                            // media is unset
10586                            installFlags |= PackageManager.INSTALL_INTERNAL;
10587                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10588                        }
10589                    }
10590                }
10591            }
10592
10593            final InstallArgs args = createInstallArgs(this);
10594            mArgs = args;
10595
10596            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10597                 /*
10598                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10599                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10600                 */
10601                int userIdentifier = getUser().getIdentifier();
10602                if (userIdentifier == UserHandle.USER_ALL
10603                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10604                    userIdentifier = UserHandle.USER_OWNER;
10605                }
10606
10607                /*
10608                 * Determine if we have any installed package verifiers. If we
10609                 * do, then we'll defer to them to verify the packages.
10610                 */
10611                final int requiredUid = mRequiredVerifierPackage == null ? -1
10612                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10613                if (!origin.existing && requiredUid != -1
10614                        && isVerificationEnabled(userIdentifier, installFlags)) {
10615                    final Intent verification = new Intent(
10616                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10617                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10618                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10619                            PACKAGE_MIME_TYPE);
10620                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10621
10622                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10623                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10624                            0 /* TODO: Which userId? */);
10625
10626                    if (DEBUG_VERIFY) {
10627                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10628                                + verification.toString() + " with " + pkgLite.verifiers.length
10629                                + " optional verifiers");
10630                    }
10631
10632                    final int verificationId = mPendingVerificationToken++;
10633
10634                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10635
10636                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10637                            installerPackageName);
10638
10639                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10640                            installFlags);
10641
10642                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10643                            pkgLite.packageName);
10644
10645                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10646                            pkgLite.versionCode);
10647
10648                    if (verificationParams != null) {
10649                        if (verificationParams.getVerificationURI() != null) {
10650                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10651                                 verificationParams.getVerificationURI());
10652                        }
10653                        if (verificationParams.getOriginatingURI() != null) {
10654                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10655                                  verificationParams.getOriginatingURI());
10656                        }
10657                        if (verificationParams.getReferrer() != null) {
10658                            verification.putExtra(Intent.EXTRA_REFERRER,
10659                                  verificationParams.getReferrer());
10660                        }
10661                        if (verificationParams.getOriginatingUid() >= 0) {
10662                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10663                                  verificationParams.getOriginatingUid());
10664                        }
10665                        if (verificationParams.getInstallerUid() >= 0) {
10666                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10667                                  verificationParams.getInstallerUid());
10668                        }
10669                    }
10670
10671                    final PackageVerificationState verificationState = new PackageVerificationState(
10672                            requiredUid, args);
10673
10674                    mPendingVerification.append(verificationId, verificationState);
10675
10676                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10677                            receivers, verificationState);
10678
10679                    // Apps installed for "all" users use the device owner to verify the app
10680                    UserHandle verifierUser = getUser();
10681                    if (verifierUser == UserHandle.ALL) {
10682                        verifierUser = UserHandle.OWNER;
10683                    }
10684
10685                    /*
10686                     * If any sufficient verifiers were listed in the package
10687                     * manifest, attempt to ask them.
10688                     */
10689                    if (sufficientVerifiers != null) {
10690                        final int N = sufficientVerifiers.size();
10691                        if (N == 0) {
10692                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10693                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10694                        } else {
10695                            for (int i = 0; i < N; i++) {
10696                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10697
10698                                final Intent sufficientIntent = new Intent(verification);
10699                                sufficientIntent.setComponent(verifierComponent);
10700                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
10701                            }
10702                        }
10703                    }
10704
10705                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10706                            mRequiredVerifierPackage, receivers);
10707                    if (ret == PackageManager.INSTALL_SUCCEEDED
10708                            && mRequiredVerifierPackage != null) {
10709                        /*
10710                         * Send the intent to the required verification agent,
10711                         * but only start the verification timeout after the
10712                         * target BroadcastReceivers have run.
10713                         */
10714                        verification.setComponent(requiredVerifierComponent);
10715                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
10716                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10717                                new BroadcastReceiver() {
10718                                    @Override
10719                                    public void onReceive(Context context, Intent intent) {
10720                                        final Message msg = mHandler
10721                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10722                                        msg.arg1 = verificationId;
10723                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10724                                    }
10725                                }, null, 0, null, null);
10726
10727                        /*
10728                         * We don't want the copy to proceed until verification
10729                         * succeeds, so null out this field.
10730                         */
10731                        mArgs = null;
10732                    }
10733                } else {
10734                    /*
10735                     * No package verification is enabled, so immediately start
10736                     * the remote call to initiate copy using temporary file.
10737                     */
10738                    ret = args.copyApk(mContainerService, true);
10739                }
10740            }
10741
10742            mRet = ret;
10743        }
10744
10745        @Override
10746        void handleReturnCode() {
10747            // If mArgs is null, then MCS couldn't be reached. When it
10748            // reconnects, it will try again to install. At that point, this
10749            // will succeed.
10750            if (mArgs != null) {
10751                processPendingInstall(mArgs, mRet);
10752            }
10753        }
10754
10755        @Override
10756        void handleServiceError() {
10757            mArgs = createInstallArgs(this);
10758            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10759        }
10760
10761        public boolean isForwardLocked() {
10762            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10763        }
10764    }
10765
10766    /**
10767     * Used during creation of InstallArgs
10768     *
10769     * @param installFlags package installation flags
10770     * @return true if should be installed on external storage
10771     */
10772    private static boolean installOnExternalAsec(int installFlags) {
10773        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10774            return false;
10775        }
10776        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10777            return true;
10778        }
10779        return false;
10780    }
10781
10782    /**
10783     * Used during creation of InstallArgs
10784     *
10785     * @param installFlags package installation flags
10786     * @return true if should be installed as forward locked
10787     */
10788    private static boolean installForwardLocked(int installFlags) {
10789        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10790    }
10791
10792    private InstallArgs createInstallArgs(InstallParams params) {
10793        if (params.move != null) {
10794            return new MoveInstallArgs(params);
10795        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10796            return new AsecInstallArgs(params);
10797        } else {
10798            return new FileInstallArgs(params);
10799        }
10800    }
10801
10802    /**
10803     * Create args that describe an existing installed package. Typically used
10804     * when cleaning up old installs, or used as a move source.
10805     */
10806    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10807            String resourcePath, String[] instructionSets) {
10808        final boolean isInAsec;
10809        if (installOnExternalAsec(installFlags)) {
10810            /* Apps on SD card are always in ASEC containers. */
10811            isInAsec = true;
10812        } else if (installForwardLocked(installFlags)
10813                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10814            /*
10815             * Forward-locked apps are only in ASEC containers if they're the
10816             * new style
10817             */
10818            isInAsec = true;
10819        } else {
10820            isInAsec = false;
10821        }
10822
10823        if (isInAsec) {
10824            return new AsecInstallArgs(codePath, instructionSets,
10825                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10826        } else {
10827            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10828        }
10829    }
10830
10831    static abstract class InstallArgs {
10832        /** @see InstallParams#origin */
10833        final OriginInfo origin;
10834        /** @see InstallParams#move */
10835        final MoveInfo move;
10836
10837        final IPackageInstallObserver2 observer;
10838        // Always refers to PackageManager flags only
10839        final int installFlags;
10840        final String installerPackageName;
10841        final String volumeUuid;
10842        final ManifestDigest manifestDigest;
10843        final UserHandle user;
10844        final String abiOverride;
10845        final String[] installGrantPermissions;
10846
10847        // The list of instruction sets supported by this app. This is currently
10848        // only used during the rmdex() phase to clean up resources. We can get rid of this
10849        // if we move dex files under the common app path.
10850        /* nullable */ String[] instructionSets;
10851
10852        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10853                int installFlags, String installerPackageName, String volumeUuid,
10854                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10855                String abiOverride, String[] installGrantPermissions) {
10856            this.origin = origin;
10857            this.move = move;
10858            this.installFlags = installFlags;
10859            this.observer = observer;
10860            this.installerPackageName = installerPackageName;
10861            this.volumeUuid = volumeUuid;
10862            this.manifestDigest = manifestDigest;
10863            this.user = user;
10864            this.instructionSets = instructionSets;
10865            this.abiOverride = abiOverride;
10866            this.installGrantPermissions = installGrantPermissions;
10867        }
10868
10869        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10870        abstract int doPreInstall(int status);
10871
10872        /**
10873         * Rename package into final resting place. All paths on the given
10874         * scanned package should be updated to reflect the rename.
10875         */
10876        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10877        abstract int doPostInstall(int status, int uid);
10878
10879        /** @see PackageSettingBase#codePathString */
10880        abstract String getCodePath();
10881        /** @see PackageSettingBase#resourcePathString */
10882        abstract String getResourcePath();
10883
10884        // Need installer lock especially for dex file removal.
10885        abstract void cleanUpResourcesLI();
10886        abstract boolean doPostDeleteLI(boolean delete);
10887
10888        /**
10889         * Called before the source arguments are copied. This is used mostly
10890         * for MoveParams when it needs to read the source file to put it in the
10891         * destination.
10892         */
10893        int doPreCopy() {
10894            return PackageManager.INSTALL_SUCCEEDED;
10895        }
10896
10897        /**
10898         * Called after the source arguments are copied. This is used mostly for
10899         * MoveParams when it needs to read the source file to put it in the
10900         * destination.
10901         *
10902         * @return
10903         */
10904        int doPostCopy(int uid) {
10905            return PackageManager.INSTALL_SUCCEEDED;
10906        }
10907
10908        protected boolean isFwdLocked() {
10909            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10910        }
10911
10912        protected boolean isExternalAsec() {
10913            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10914        }
10915
10916        UserHandle getUser() {
10917            return user;
10918        }
10919    }
10920
10921    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10922        if (!allCodePaths.isEmpty()) {
10923            if (instructionSets == null) {
10924                throw new IllegalStateException("instructionSet == null");
10925            }
10926            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10927            for (String codePath : allCodePaths) {
10928                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10929                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10930                    if (retCode < 0) {
10931                        Slog.w(TAG, "Couldn't remove dex file for package: "
10932                                + " at location " + codePath + ", retcode=" + retCode);
10933                        // we don't consider this to be a failure of the core package deletion
10934                    }
10935                }
10936            }
10937        }
10938    }
10939
10940    /**
10941     * Logic to handle installation of non-ASEC applications, including copying
10942     * and renaming logic.
10943     */
10944    class FileInstallArgs extends InstallArgs {
10945        private File codeFile;
10946        private File resourceFile;
10947
10948        // Example topology:
10949        // /data/app/com.example/base.apk
10950        // /data/app/com.example/split_foo.apk
10951        // /data/app/com.example/lib/arm/libfoo.so
10952        // /data/app/com.example/lib/arm64/libfoo.so
10953        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10954
10955        /** New install */
10956        FileInstallArgs(InstallParams params) {
10957            super(params.origin, params.move, params.observer, params.installFlags,
10958                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10959                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
10960                    params.grantedRuntimePermissions);
10961            if (isFwdLocked()) {
10962                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10963            }
10964        }
10965
10966        /** Existing install */
10967        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10968            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10969                    null, null);
10970            this.codeFile = (codePath != null) ? new File(codePath) : null;
10971            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10972        }
10973
10974        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10975            if (origin.staged) {
10976                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10977                codeFile = origin.file;
10978                resourceFile = origin.file;
10979                return PackageManager.INSTALL_SUCCEEDED;
10980            }
10981
10982            try {
10983                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10984                codeFile = tempDir;
10985                resourceFile = tempDir;
10986            } catch (IOException e) {
10987                Slog.w(TAG, "Failed to create copy file: " + e);
10988                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10989            }
10990
10991            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10992                @Override
10993                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10994                    if (!FileUtils.isValidExtFilename(name)) {
10995                        throw new IllegalArgumentException("Invalid filename: " + name);
10996                    }
10997                    try {
10998                        final File file = new File(codeFile, name);
10999                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11000                                O_RDWR | O_CREAT, 0644);
11001                        Os.chmod(file.getAbsolutePath(), 0644);
11002                        return new ParcelFileDescriptor(fd);
11003                    } catch (ErrnoException e) {
11004                        throw new RemoteException("Failed to open: " + e.getMessage());
11005                    }
11006                }
11007            };
11008
11009            int ret = PackageManager.INSTALL_SUCCEEDED;
11010            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11011            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11012                Slog.e(TAG, "Failed to copy package");
11013                return ret;
11014            }
11015
11016            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11017            NativeLibraryHelper.Handle handle = null;
11018            try {
11019                handle = NativeLibraryHelper.Handle.create(codeFile);
11020                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11021                        abiOverride);
11022            } catch (IOException e) {
11023                Slog.e(TAG, "Copying native libraries failed", e);
11024                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11025            } finally {
11026                IoUtils.closeQuietly(handle);
11027            }
11028
11029            return ret;
11030        }
11031
11032        int doPreInstall(int status) {
11033            if (status != PackageManager.INSTALL_SUCCEEDED) {
11034                cleanUp();
11035            }
11036            return status;
11037        }
11038
11039        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11040            if (status != PackageManager.INSTALL_SUCCEEDED) {
11041                cleanUp();
11042                return false;
11043            }
11044
11045            final File targetDir = codeFile.getParentFile();
11046            final File beforeCodeFile = codeFile;
11047            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11048
11049            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11050            try {
11051                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11052            } catch (ErrnoException e) {
11053                Slog.w(TAG, "Failed to rename", e);
11054                return false;
11055            }
11056
11057            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11058                Slog.w(TAG, "Failed to restorecon");
11059                return false;
11060            }
11061
11062            // Reflect the rename internally
11063            codeFile = afterCodeFile;
11064            resourceFile = afterCodeFile;
11065
11066            // Reflect the rename in scanned details
11067            pkg.codePath = afterCodeFile.getAbsolutePath();
11068            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11069                    pkg.baseCodePath);
11070            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11071                    pkg.splitCodePaths);
11072
11073            // Reflect the rename in app info
11074            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11075            pkg.applicationInfo.setCodePath(pkg.codePath);
11076            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11077            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11078            pkg.applicationInfo.setResourcePath(pkg.codePath);
11079            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11080            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11081
11082            return true;
11083        }
11084
11085        int doPostInstall(int status, int uid) {
11086            if (status != PackageManager.INSTALL_SUCCEEDED) {
11087                cleanUp();
11088            }
11089            return status;
11090        }
11091
11092        @Override
11093        String getCodePath() {
11094            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11095        }
11096
11097        @Override
11098        String getResourcePath() {
11099            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11100        }
11101
11102        private boolean cleanUp() {
11103            if (codeFile == null || !codeFile.exists()) {
11104                return false;
11105            }
11106
11107            if (codeFile.isDirectory()) {
11108                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11109            } else {
11110                codeFile.delete();
11111            }
11112
11113            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11114                resourceFile.delete();
11115            }
11116
11117            return true;
11118        }
11119
11120        void cleanUpResourcesLI() {
11121            // Try enumerating all code paths before deleting
11122            List<String> allCodePaths = Collections.EMPTY_LIST;
11123            if (codeFile != null && codeFile.exists()) {
11124                try {
11125                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11126                    allCodePaths = pkg.getAllCodePaths();
11127                } catch (PackageParserException e) {
11128                    // Ignored; we tried our best
11129                }
11130            }
11131
11132            cleanUp();
11133            removeDexFiles(allCodePaths, instructionSets);
11134        }
11135
11136        boolean doPostDeleteLI(boolean delete) {
11137            // XXX err, shouldn't we respect the delete flag?
11138            cleanUpResourcesLI();
11139            return true;
11140        }
11141    }
11142
11143    private boolean isAsecExternal(String cid) {
11144        final String asecPath = PackageHelper.getSdFilesystem(cid);
11145        return !asecPath.startsWith(mAsecInternalPath);
11146    }
11147
11148    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11149            PackageManagerException {
11150        if (copyRet < 0) {
11151            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11152                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11153                throw new PackageManagerException(copyRet, message);
11154            }
11155        }
11156    }
11157
11158    /**
11159     * Extract the MountService "container ID" from the full code path of an
11160     * .apk.
11161     */
11162    static String cidFromCodePath(String fullCodePath) {
11163        int eidx = fullCodePath.lastIndexOf("/");
11164        String subStr1 = fullCodePath.substring(0, eidx);
11165        int sidx = subStr1.lastIndexOf("/");
11166        return subStr1.substring(sidx+1, eidx);
11167    }
11168
11169    /**
11170     * Logic to handle installation of ASEC applications, including copying and
11171     * renaming logic.
11172     */
11173    class AsecInstallArgs extends InstallArgs {
11174        static final String RES_FILE_NAME = "pkg.apk";
11175        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11176
11177        String cid;
11178        String packagePath;
11179        String resourcePath;
11180
11181        /** New install */
11182        AsecInstallArgs(InstallParams params) {
11183            super(params.origin, params.move, params.observer, params.installFlags,
11184                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11185                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11186                    params.grantedRuntimePermissions);
11187        }
11188
11189        /** Existing install */
11190        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11191                        boolean isExternal, boolean isForwardLocked) {
11192            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11193                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11194                    instructionSets, null, null);
11195            // Hackily pretend we're still looking at a full code path
11196            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11197                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11198            }
11199
11200            // Extract cid from fullCodePath
11201            int eidx = fullCodePath.lastIndexOf("/");
11202            String subStr1 = fullCodePath.substring(0, eidx);
11203            int sidx = subStr1.lastIndexOf("/");
11204            cid = subStr1.substring(sidx+1, eidx);
11205            setMountPath(subStr1);
11206        }
11207
11208        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11209            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11210                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11211                    instructionSets, null, null);
11212            this.cid = cid;
11213            setMountPath(PackageHelper.getSdDir(cid));
11214        }
11215
11216        void createCopyFile() {
11217            cid = mInstallerService.allocateExternalStageCidLegacy();
11218        }
11219
11220        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11221            if (origin.staged) {
11222                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11223                cid = origin.cid;
11224                setMountPath(PackageHelper.getSdDir(cid));
11225                return PackageManager.INSTALL_SUCCEEDED;
11226            }
11227
11228            if (temp) {
11229                createCopyFile();
11230            } else {
11231                /*
11232                 * Pre-emptively destroy the container since it's destroyed if
11233                 * copying fails due to it existing anyway.
11234                 */
11235                PackageHelper.destroySdDir(cid);
11236            }
11237
11238            final String newMountPath = imcs.copyPackageToContainer(
11239                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11240                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11241
11242            if (newMountPath != null) {
11243                setMountPath(newMountPath);
11244                return PackageManager.INSTALL_SUCCEEDED;
11245            } else {
11246                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11247            }
11248        }
11249
11250        @Override
11251        String getCodePath() {
11252            return packagePath;
11253        }
11254
11255        @Override
11256        String getResourcePath() {
11257            return resourcePath;
11258        }
11259
11260        int doPreInstall(int status) {
11261            if (status != PackageManager.INSTALL_SUCCEEDED) {
11262                // Destroy container
11263                PackageHelper.destroySdDir(cid);
11264            } else {
11265                boolean mounted = PackageHelper.isContainerMounted(cid);
11266                if (!mounted) {
11267                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11268                            Process.SYSTEM_UID);
11269                    if (newMountPath != null) {
11270                        setMountPath(newMountPath);
11271                    } else {
11272                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11273                    }
11274                }
11275            }
11276            return status;
11277        }
11278
11279        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11280            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11281            String newMountPath = null;
11282            if (PackageHelper.isContainerMounted(cid)) {
11283                // Unmount the container
11284                if (!PackageHelper.unMountSdDir(cid)) {
11285                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11286                    return false;
11287                }
11288            }
11289            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11290                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11291                        " which might be stale. Will try to clean up.");
11292                // Clean up the stale container and proceed to recreate.
11293                if (!PackageHelper.destroySdDir(newCacheId)) {
11294                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11295                    return false;
11296                }
11297                // Successfully cleaned up stale container. Try to rename again.
11298                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11299                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11300                            + " inspite of cleaning it up.");
11301                    return false;
11302                }
11303            }
11304            if (!PackageHelper.isContainerMounted(newCacheId)) {
11305                Slog.w(TAG, "Mounting container " + newCacheId);
11306                newMountPath = PackageHelper.mountSdDir(newCacheId,
11307                        getEncryptKey(), Process.SYSTEM_UID);
11308            } else {
11309                newMountPath = PackageHelper.getSdDir(newCacheId);
11310            }
11311            if (newMountPath == null) {
11312                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11313                return false;
11314            }
11315            Log.i(TAG, "Succesfully renamed " + cid +
11316                    " to " + newCacheId +
11317                    " at new path: " + newMountPath);
11318            cid = newCacheId;
11319
11320            final File beforeCodeFile = new File(packagePath);
11321            setMountPath(newMountPath);
11322            final File afterCodeFile = new File(packagePath);
11323
11324            // Reflect the rename in scanned details
11325            pkg.codePath = afterCodeFile.getAbsolutePath();
11326            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11327                    pkg.baseCodePath);
11328            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11329                    pkg.splitCodePaths);
11330
11331            // Reflect the rename in app info
11332            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11333            pkg.applicationInfo.setCodePath(pkg.codePath);
11334            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11335            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11336            pkg.applicationInfo.setResourcePath(pkg.codePath);
11337            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11338            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11339
11340            return true;
11341        }
11342
11343        private void setMountPath(String mountPath) {
11344            final File mountFile = new File(mountPath);
11345
11346            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11347            if (monolithicFile.exists()) {
11348                packagePath = monolithicFile.getAbsolutePath();
11349                if (isFwdLocked()) {
11350                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11351                } else {
11352                    resourcePath = packagePath;
11353                }
11354            } else {
11355                packagePath = mountFile.getAbsolutePath();
11356                resourcePath = packagePath;
11357            }
11358        }
11359
11360        int doPostInstall(int status, int uid) {
11361            if (status != PackageManager.INSTALL_SUCCEEDED) {
11362                cleanUp();
11363            } else {
11364                final int groupOwner;
11365                final String protectedFile;
11366                if (isFwdLocked()) {
11367                    groupOwner = UserHandle.getSharedAppGid(uid);
11368                    protectedFile = RES_FILE_NAME;
11369                } else {
11370                    groupOwner = -1;
11371                    protectedFile = null;
11372                }
11373
11374                if (uid < Process.FIRST_APPLICATION_UID
11375                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11376                    Slog.e(TAG, "Failed to finalize " + cid);
11377                    PackageHelper.destroySdDir(cid);
11378                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11379                }
11380
11381                boolean mounted = PackageHelper.isContainerMounted(cid);
11382                if (!mounted) {
11383                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11384                }
11385            }
11386            return status;
11387        }
11388
11389        private void cleanUp() {
11390            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11391
11392            // Destroy secure container
11393            PackageHelper.destroySdDir(cid);
11394        }
11395
11396        private List<String> getAllCodePaths() {
11397            final File codeFile = new File(getCodePath());
11398            if (codeFile != null && codeFile.exists()) {
11399                try {
11400                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11401                    return pkg.getAllCodePaths();
11402                } catch (PackageParserException e) {
11403                    // Ignored; we tried our best
11404                }
11405            }
11406            return Collections.EMPTY_LIST;
11407        }
11408
11409        void cleanUpResourcesLI() {
11410            // Enumerate all code paths before deleting
11411            cleanUpResourcesLI(getAllCodePaths());
11412        }
11413
11414        private void cleanUpResourcesLI(List<String> allCodePaths) {
11415            cleanUp();
11416            removeDexFiles(allCodePaths, instructionSets);
11417        }
11418
11419        String getPackageName() {
11420            return getAsecPackageName(cid);
11421        }
11422
11423        boolean doPostDeleteLI(boolean delete) {
11424            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11425            final List<String> allCodePaths = getAllCodePaths();
11426            boolean mounted = PackageHelper.isContainerMounted(cid);
11427            if (mounted) {
11428                // Unmount first
11429                if (PackageHelper.unMountSdDir(cid)) {
11430                    mounted = false;
11431                }
11432            }
11433            if (!mounted && delete) {
11434                cleanUpResourcesLI(allCodePaths);
11435            }
11436            return !mounted;
11437        }
11438
11439        @Override
11440        int doPreCopy() {
11441            if (isFwdLocked()) {
11442                if (!PackageHelper.fixSdPermissions(cid,
11443                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11444                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11445                }
11446            }
11447
11448            return PackageManager.INSTALL_SUCCEEDED;
11449        }
11450
11451        @Override
11452        int doPostCopy(int uid) {
11453            if (isFwdLocked()) {
11454                if (uid < Process.FIRST_APPLICATION_UID
11455                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11456                                RES_FILE_NAME)) {
11457                    Slog.e(TAG, "Failed to finalize " + cid);
11458                    PackageHelper.destroySdDir(cid);
11459                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11460                }
11461            }
11462
11463            return PackageManager.INSTALL_SUCCEEDED;
11464        }
11465    }
11466
11467    /**
11468     * Logic to handle movement of existing installed applications.
11469     */
11470    class MoveInstallArgs extends InstallArgs {
11471        private File codeFile;
11472        private File resourceFile;
11473
11474        /** New install */
11475        MoveInstallArgs(InstallParams params) {
11476            super(params.origin, params.move, params.observer, params.installFlags,
11477                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11478                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11479                    params.grantedRuntimePermissions);
11480        }
11481
11482        int copyApk(IMediaContainerService imcs, boolean temp) {
11483            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11484                    + move.fromUuid + " to " + move.toUuid);
11485            synchronized (mInstaller) {
11486                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11487                        move.dataAppName, move.appId, move.seinfo) != 0) {
11488                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11489                }
11490            }
11491
11492            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11493            resourceFile = codeFile;
11494            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11495
11496            return PackageManager.INSTALL_SUCCEEDED;
11497        }
11498
11499        int doPreInstall(int status) {
11500            if (status != PackageManager.INSTALL_SUCCEEDED) {
11501                cleanUp(move.toUuid);
11502            }
11503            return status;
11504        }
11505
11506        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11507            if (status != PackageManager.INSTALL_SUCCEEDED) {
11508                cleanUp(move.toUuid);
11509                return false;
11510            }
11511
11512            // Reflect the move in app info
11513            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11514            pkg.applicationInfo.setCodePath(pkg.codePath);
11515            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11516            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11517            pkg.applicationInfo.setResourcePath(pkg.codePath);
11518            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11519            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11520
11521            return true;
11522        }
11523
11524        int doPostInstall(int status, int uid) {
11525            if (status == PackageManager.INSTALL_SUCCEEDED) {
11526                cleanUp(move.fromUuid);
11527            } else {
11528                cleanUp(move.toUuid);
11529            }
11530            return status;
11531        }
11532
11533        @Override
11534        String getCodePath() {
11535            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11536        }
11537
11538        @Override
11539        String getResourcePath() {
11540            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11541        }
11542
11543        private boolean cleanUp(String volumeUuid) {
11544            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11545                    move.dataAppName);
11546            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11547            synchronized (mInstallLock) {
11548                // Clean up both app data and code
11549                removeDataDirsLI(volumeUuid, move.packageName);
11550                if (codeFile.isDirectory()) {
11551                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11552                } else {
11553                    codeFile.delete();
11554                }
11555            }
11556            return true;
11557        }
11558
11559        void cleanUpResourcesLI() {
11560            throw new UnsupportedOperationException();
11561        }
11562
11563        boolean doPostDeleteLI(boolean delete) {
11564            throw new UnsupportedOperationException();
11565        }
11566    }
11567
11568    static String getAsecPackageName(String packageCid) {
11569        int idx = packageCid.lastIndexOf("-");
11570        if (idx == -1) {
11571            return packageCid;
11572        }
11573        return packageCid.substring(0, idx);
11574    }
11575
11576    // Utility method used to create code paths based on package name and available index.
11577    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11578        String idxStr = "";
11579        int idx = 1;
11580        // Fall back to default value of idx=1 if prefix is not
11581        // part of oldCodePath
11582        if (oldCodePath != null) {
11583            String subStr = oldCodePath;
11584            // Drop the suffix right away
11585            if (suffix != null && subStr.endsWith(suffix)) {
11586                subStr = subStr.substring(0, subStr.length() - suffix.length());
11587            }
11588            // If oldCodePath already contains prefix find out the
11589            // ending index to either increment or decrement.
11590            int sidx = subStr.lastIndexOf(prefix);
11591            if (sidx != -1) {
11592                subStr = subStr.substring(sidx + prefix.length());
11593                if (subStr != null) {
11594                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11595                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11596                    }
11597                    try {
11598                        idx = Integer.parseInt(subStr);
11599                        if (idx <= 1) {
11600                            idx++;
11601                        } else {
11602                            idx--;
11603                        }
11604                    } catch(NumberFormatException e) {
11605                    }
11606                }
11607            }
11608        }
11609        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11610        return prefix + idxStr;
11611    }
11612
11613    private File getNextCodePath(File targetDir, String packageName) {
11614        int suffix = 1;
11615        File result;
11616        do {
11617            result = new File(targetDir, packageName + "-" + suffix);
11618            suffix++;
11619        } while (result.exists());
11620        return result;
11621    }
11622
11623    // Utility method that returns the relative package path with respect
11624    // to the installation directory. Like say for /data/data/com.test-1.apk
11625    // string com.test-1 is returned.
11626    static String deriveCodePathName(String codePath) {
11627        if (codePath == null) {
11628            return null;
11629        }
11630        final File codeFile = new File(codePath);
11631        final String name = codeFile.getName();
11632        if (codeFile.isDirectory()) {
11633            return name;
11634        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11635            final int lastDot = name.lastIndexOf('.');
11636            return name.substring(0, lastDot);
11637        } else {
11638            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11639            return null;
11640        }
11641    }
11642
11643    class PackageInstalledInfo {
11644        String name;
11645        int uid;
11646        // The set of users that originally had this package installed.
11647        int[] origUsers;
11648        // The set of users that now have this package installed.
11649        int[] newUsers;
11650        PackageParser.Package pkg;
11651        int returnCode;
11652        String returnMsg;
11653        PackageRemovedInfo removedInfo;
11654
11655        public void setError(int code, String msg) {
11656            returnCode = code;
11657            returnMsg = msg;
11658            Slog.w(TAG, msg);
11659        }
11660
11661        public void setError(String msg, PackageParserException e) {
11662            returnCode = e.error;
11663            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11664            Slog.w(TAG, msg, e);
11665        }
11666
11667        public void setError(String msg, PackageManagerException e) {
11668            returnCode = e.error;
11669            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11670            Slog.w(TAG, msg, e);
11671        }
11672
11673        // In some error cases we want to convey more info back to the observer
11674        String origPackage;
11675        String origPermission;
11676    }
11677
11678    /*
11679     * Install a non-existing package.
11680     */
11681    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11682            UserHandle user, String installerPackageName, String volumeUuid,
11683            PackageInstalledInfo res) {
11684        // Remember this for later, in case we need to rollback this install
11685        String pkgName = pkg.packageName;
11686
11687        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11688        final boolean dataDirExists = Environment
11689                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists();
11690        synchronized(mPackages) {
11691            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11692                // A package with the same name is already installed, though
11693                // it has been renamed to an older name.  The package we
11694                // are trying to install should be installed as an update to
11695                // the existing one, but that has not been requested, so bail.
11696                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11697                        + " without first uninstalling package running as "
11698                        + mSettings.mRenamedPackages.get(pkgName));
11699                return;
11700            }
11701            if (mPackages.containsKey(pkgName)) {
11702                // Don't allow installation over an existing package with the same name.
11703                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11704                        + " without first uninstalling.");
11705                return;
11706            }
11707        }
11708
11709        try {
11710            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11711                    System.currentTimeMillis(), user);
11712
11713            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11714            // delete the partially installed application. the data directory will have to be
11715            // restored if it was already existing
11716            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11717                // remove package from internal structures.  Note that we want deletePackageX to
11718                // delete the package data and cache directories that it created in
11719                // scanPackageLocked, unless those directories existed before we even tried to
11720                // install.
11721                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11722                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11723                                res.removedInfo, true);
11724            }
11725
11726        } catch (PackageManagerException e) {
11727            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11728        }
11729    }
11730
11731    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11732        // Can't rotate keys during boot or if sharedUser.
11733        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11734                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11735            return false;
11736        }
11737        // app is using upgradeKeySets; make sure all are valid
11738        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11739        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11740        for (int i = 0; i < upgradeKeySets.length; i++) {
11741            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11742                Slog.wtf(TAG, "Package "
11743                         + (oldPs.name != null ? oldPs.name : "<null>")
11744                         + " contains upgrade-key-set reference to unknown key-set: "
11745                         + upgradeKeySets[i]
11746                         + " reverting to signatures check.");
11747                return false;
11748            }
11749        }
11750        return true;
11751    }
11752
11753    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11754        // Upgrade keysets are being used.  Determine if new package has a superset of the
11755        // required keys.
11756        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11757        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11758        for (int i = 0; i < upgradeKeySets.length; i++) {
11759            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11760            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11761                return true;
11762            }
11763        }
11764        return false;
11765    }
11766
11767    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11768            UserHandle user, String installerPackageName, String volumeUuid,
11769            PackageInstalledInfo res) {
11770        final PackageParser.Package oldPackage;
11771        final String pkgName = pkg.packageName;
11772        final int[] allUsers;
11773        final boolean[] perUserInstalled;
11774        final boolean weFroze;
11775
11776        // First find the old package info and check signatures
11777        synchronized(mPackages) {
11778            oldPackage = mPackages.get(pkgName);
11779            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11780            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11781            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11782                if(!checkUpgradeKeySetLP(ps, pkg)) {
11783                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11784                            "New package not signed by keys specified by upgrade-keysets: "
11785                            + pkgName);
11786                    return;
11787                }
11788            } else {
11789                // default to original signature matching
11790                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11791                    != PackageManager.SIGNATURE_MATCH) {
11792                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11793                            "New package has a different signature: " + pkgName);
11794                    return;
11795                }
11796            }
11797
11798            // In case of rollback, remember per-user/profile install state
11799            allUsers = sUserManager.getUserIds();
11800            perUserInstalled = new boolean[allUsers.length];
11801            for (int i = 0; i < allUsers.length; i++) {
11802                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11803            }
11804
11805            // Mark the app as frozen to prevent launching during the upgrade
11806            // process, and then kill all running instances
11807            if (!ps.frozen) {
11808                ps.frozen = true;
11809                weFroze = true;
11810            } else {
11811                weFroze = false;
11812            }
11813        }
11814
11815        // Now that we're guarded by frozen state, kill app during upgrade
11816        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11817
11818        try {
11819            boolean sysPkg = (isSystemApp(oldPackage));
11820            if (sysPkg) {
11821                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11822                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11823            } else {
11824                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11825                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11826            }
11827        } finally {
11828            // Regardless of success or failure of upgrade steps above, always
11829            // unfreeze the package if we froze it
11830            if (weFroze) {
11831                unfreezePackage(pkgName);
11832            }
11833        }
11834    }
11835
11836    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11837            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11838            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11839            String volumeUuid, PackageInstalledInfo res) {
11840        String pkgName = deletedPackage.packageName;
11841        boolean deletedPkg = true;
11842        boolean updatedSettings = false;
11843
11844        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11845                + deletedPackage);
11846        long origUpdateTime;
11847        if (pkg.mExtras != null) {
11848            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11849        } else {
11850            origUpdateTime = 0;
11851        }
11852
11853        // First delete the existing package while retaining the data directory
11854        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11855                res.removedInfo, true)) {
11856            // If the existing package wasn't successfully deleted
11857            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11858            deletedPkg = false;
11859        } else {
11860            // Successfully deleted the old package; proceed with replace.
11861
11862            // If deleted package lived in a container, give users a chance to
11863            // relinquish resources before killing.
11864            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11865                if (DEBUG_INSTALL) {
11866                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11867                }
11868                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11869                final ArrayList<String> pkgList = new ArrayList<String>(1);
11870                pkgList.add(deletedPackage.applicationInfo.packageName);
11871                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11872            }
11873
11874            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11875            try {
11876                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11877                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11878                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11879                        perUserInstalled, res, user);
11880                updatedSettings = true;
11881            } catch (PackageManagerException e) {
11882                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11883            }
11884        }
11885
11886        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11887            // remove package from internal structures.  Note that we want deletePackageX to
11888            // delete the package data and cache directories that it created in
11889            // scanPackageLocked, unless those directories existed before we even tried to
11890            // install.
11891            if(updatedSettings) {
11892                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11893                deletePackageLI(
11894                        pkgName, null, true, allUsers, perUserInstalled,
11895                        PackageManager.DELETE_KEEP_DATA,
11896                                res.removedInfo, true);
11897            }
11898            // Since we failed to install the new package we need to restore the old
11899            // package that we deleted.
11900            if (deletedPkg) {
11901                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11902                File restoreFile = new File(deletedPackage.codePath);
11903                // Parse old package
11904                boolean oldExternal = isExternal(deletedPackage);
11905                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11906                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11907                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11908                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11909                try {
11910                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11911                } catch (PackageManagerException e) {
11912                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11913                            + e.getMessage());
11914                    return;
11915                }
11916                // Restore of old package succeeded. Update permissions.
11917                // writer
11918                synchronized (mPackages) {
11919                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11920                            UPDATE_PERMISSIONS_ALL);
11921                    // can downgrade to reader
11922                    mSettings.writeLPr();
11923                }
11924                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11925            }
11926        }
11927    }
11928
11929    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11930            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11931            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11932            String volumeUuid, PackageInstalledInfo res) {
11933        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11934                + ", old=" + deletedPackage);
11935        boolean disabledSystem = false;
11936        boolean updatedSettings = false;
11937        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11938        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11939                != 0) {
11940            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11941        }
11942        String packageName = deletedPackage.packageName;
11943        if (packageName == null) {
11944            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11945                    "Attempt to delete null packageName.");
11946            return;
11947        }
11948        PackageParser.Package oldPkg;
11949        PackageSetting oldPkgSetting;
11950        // reader
11951        synchronized (mPackages) {
11952            oldPkg = mPackages.get(packageName);
11953            oldPkgSetting = mSettings.mPackages.get(packageName);
11954            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11955                    (oldPkgSetting == null)) {
11956                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11957                        "Couldn't find package:" + packageName + " information");
11958                return;
11959            }
11960        }
11961
11962        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11963        res.removedInfo.removedPackage = packageName;
11964        // Remove existing system package
11965        removePackageLI(oldPkgSetting, true);
11966        // writer
11967        synchronized (mPackages) {
11968            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11969            if (!disabledSystem && deletedPackage != null) {
11970                // We didn't need to disable the .apk as a current system package,
11971                // which means we are replacing another update that is already
11972                // installed.  We need to make sure to delete the older one's .apk.
11973                res.removedInfo.args = createInstallArgsForExisting(0,
11974                        deletedPackage.applicationInfo.getCodePath(),
11975                        deletedPackage.applicationInfo.getResourcePath(),
11976                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11977            } else {
11978                res.removedInfo.args = null;
11979            }
11980        }
11981
11982        // Successfully disabled the old package. Now proceed with re-installation
11983        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11984
11985        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11986        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11987
11988        PackageParser.Package newPackage = null;
11989        try {
11990            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11991            if (newPackage.mExtras != null) {
11992                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11993                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11994                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11995
11996                // is the update attempting to change shared user? that isn't going to work...
11997                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11998                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11999                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12000                            + " to " + newPkgSetting.sharedUser);
12001                    updatedSettings = true;
12002                }
12003            }
12004
12005            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12006                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12007                        perUserInstalled, res, user);
12008                updatedSettings = true;
12009            }
12010
12011        } catch (PackageManagerException e) {
12012            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12013        }
12014
12015        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12016            // Re installation failed. Restore old information
12017            // Remove new pkg information
12018            if (newPackage != null) {
12019                removeInstalledPackageLI(newPackage, true);
12020            }
12021            // Add back the old system package
12022            try {
12023                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12024            } catch (PackageManagerException e) {
12025                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12026            }
12027            // Restore the old system information in Settings
12028            synchronized (mPackages) {
12029                if (disabledSystem) {
12030                    mSettings.enableSystemPackageLPw(packageName);
12031                }
12032                if (updatedSettings) {
12033                    mSettings.setInstallerPackageName(packageName,
12034                            oldPkgSetting.installerPackageName);
12035                }
12036                mSettings.writeLPr();
12037            }
12038        }
12039    }
12040
12041    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12042            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12043            UserHandle user) {
12044        String pkgName = newPackage.packageName;
12045        synchronized (mPackages) {
12046            //write settings. the installStatus will be incomplete at this stage.
12047            //note that the new package setting would have already been
12048            //added to mPackages. It hasn't been persisted yet.
12049            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12050            mSettings.writeLPr();
12051        }
12052
12053        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12054
12055        synchronized (mPackages) {
12056            updatePermissionsLPw(newPackage.packageName, newPackage,
12057                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12058                            ? UPDATE_PERMISSIONS_ALL : 0));
12059            // For system-bundled packages, we assume that installing an upgraded version
12060            // of the package implies that the user actually wants to run that new code,
12061            // so we enable the package.
12062            PackageSetting ps = mSettings.mPackages.get(pkgName);
12063            if (ps != null) {
12064                if (isSystemApp(newPackage)) {
12065                    // NB: implicit assumption that system package upgrades apply to all users
12066                    if (DEBUG_INSTALL) {
12067                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12068                    }
12069                    if (res.origUsers != null) {
12070                        for (int userHandle : res.origUsers) {
12071                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12072                                    userHandle, installerPackageName);
12073                        }
12074                    }
12075                    // Also convey the prior install/uninstall state
12076                    if (allUsers != null && perUserInstalled != null) {
12077                        for (int i = 0; i < allUsers.length; i++) {
12078                            if (DEBUG_INSTALL) {
12079                                Slog.d(TAG, "    user " + allUsers[i]
12080                                        + " => " + perUserInstalled[i]);
12081                            }
12082                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12083                        }
12084                        // these install state changes will be persisted in the
12085                        // upcoming call to mSettings.writeLPr().
12086                    }
12087                }
12088                // It's implied that when a user requests installation, they want the app to be
12089                // installed and enabled.
12090                int userId = user.getIdentifier();
12091                if (userId != UserHandle.USER_ALL) {
12092                    ps.setInstalled(true, userId);
12093                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12094                }
12095            }
12096            res.name = pkgName;
12097            res.uid = newPackage.applicationInfo.uid;
12098            res.pkg = newPackage;
12099            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12100            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12101            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12102            //to update install status
12103            mSettings.writeLPr();
12104        }
12105    }
12106
12107    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12108        final int installFlags = args.installFlags;
12109        final String installerPackageName = args.installerPackageName;
12110        final String volumeUuid = args.volumeUuid;
12111        final File tmpPackageFile = new File(args.getCodePath());
12112        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12113        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12114                || (args.volumeUuid != null));
12115        boolean replace = false;
12116        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12117        if (args.move != null) {
12118            // moving a complete application; perfom an initial scan on the new install location
12119            scanFlags |= SCAN_INITIAL;
12120        }
12121        // Result object to be returned
12122        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12123
12124        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12125        // Retrieve PackageSettings and parse package
12126        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12127                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12128                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12129        PackageParser pp = new PackageParser();
12130        pp.setSeparateProcesses(mSeparateProcesses);
12131        pp.setDisplayMetrics(mMetrics);
12132
12133        final PackageParser.Package pkg;
12134        try {
12135            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12136        } catch (PackageParserException e) {
12137            res.setError("Failed parse during installPackageLI", e);
12138            return;
12139        }
12140
12141        // Mark that we have an install time CPU ABI override.
12142        pkg.cpuAbiOverride = args.abiOverride;
12143
12144        String pkgName = res.name = pkg.packageName;
12145        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12146            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12147                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12148                return;
12149            }
12150        }
12151
12152        try {
12153            pp.collectCertificates(pkg, parseFlags);
12154            pp.collectManifestDigest(pkg);
12155        } catch (PackageParserException e) {
12156            res.setError("Failed collect during installPackageLI", e);
12157            return;
12158        }
12159
12160        /* If the installer passed in a manifest digest, compare it now. */
12161        if (args.manifestDigest != null) {
12162            if (DEBUG_INSTALL) {
12163                final String parsedManifest = pkg.manifestDigest == null ? "null"
12164                        : pkg.manifestDigest.toString();
12165                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12166                        + parsedManifest);
12167            }
12168
12169            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12170                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12171                return;
12172            }
12173        } else if (DEBUG_INSTALL) {
12174            final String parsedManifest = pkg.manifestDigest == null
12175                    ? "null" : pkg.manifestDigest.toString();
12176            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12177        }
12178
12179        // Get rid of all references to package scan path via parser.
12180        pp = null;
12181        String oldCodePath = null;
12182        boolean systemApp = false;
12183        synchronized (mPackages) {
12184            // Check if installing already existing package
12185            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12186                String oldName = mSettings.mRenamedPackages.get(pkgName);
12187                if (pkg.mOriginalPackages != null
12188                        && pkg.mOriginalPackages.contains(oldName)
12189                        && mPackages.containsKey(oldName)) {
12190                    // This package is derived from an original package,
12191                    // and this device has been updating from that original
12192                    // name.  We must continue using the original name, so
12193                    // rename the new package here.
12194                    pkg.setPackageName(oldName);
12195                    pkgName = pkg.packageName;
12196                    replace = true;
12197                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12198                            + oldName + " pkgName=" + pkgName);
12199                } else if (mPackages.containsKey(pkgName)) {
12200                    // This package, under its official name, already exists
12201                    // on the device; we should replace it.
12202                    replace = true;
12203                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12204                }
12205
12206                // Prevent apps opting out from runtime permissions
12207                if (replace) {
12208                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12209                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12210                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12211                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12212                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12213                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12214                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12215                                        + " doesn't support runtime permissions but the old"
12216                                        + " target SDK " + oldTargetSdk + " does.");
12217                        return;
12218                    }
12219                }
12220            }
12221
12222            PackageSetting ps = mSettings.mPackages.get(pkgName);
12223            if (ps != null) {
12224                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12225
12226                // Quick sanity check that we're signed correctly if updating;
12227                // we'll check this again later when scanning, but we want to
12228                // bail early here before tripping over redefined permissions.
12229                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12230                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12231                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12232                                + pkg.packageName + " upgrade keys do not match the "
12233                                + "previously installed version");
12234                        return;
12235                    }
12236                } else {
12237                    try {
12238                        verifySignaturesLP(ps, pkg);
12239                    } catch (PackageManagerException e) {
12240                        res.setError(e.error, e.getMessage());
12241                        return;
12242                    }
12243                }
12244
12245                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12246                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12247                    systemApp = (ps.pkg.applicationInfo.flags &
12248                            ApplicationInfo.FLAG_SYSTEM) != 0;
12249                }
12250                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12251            }
12252
12253            // Check whether the newly-scanned package wants to define an already-defined perm
12254            int N = pkg.permissions.size();
12255            for (int i = N-1; i >= 0; i--) {
12256                PackageParser.Permission perm = pkg.permissions.get(i);
12257                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12258                if (bp != null) {
12259                    // If the defining package is signed with our cert, it's okay.  This
12260                    // also includes the "updating the same package" case, of course.
12261                    // "updating same package" could also involve key-rotation.
12262                    final boolean sigsOk;
12263                    if (bp.sourcePackage.equals(pkg.packageName)
12264                            && (bp.packageSetting instanceof PackageSetting)
12265                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12266                                    scanFlags))) {
12267                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12268                    } else {
12269                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12270                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12271                    }
12272                    if (!sigsOk) {
12273                        // If the owning package is the system itself, we log but allow
12274                        // install to proceed; we fail the install on all other permission
12275                        // redefinitions.
12276                        if (!bp.sourcePackage.equals("android")) {
12277                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12278                                    + pkg.packageName + " attempting to redeclare permission "
12279                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12280                            res.origPermission = perm.info.name;
12281                            res.origPackage = bp.sourcePackage;
12282                            return;
12283                        } else {
12284                            Slog.w(TAG, "Package " + pkg.packageName
12285                                    + " attempting to redeclare system permission "
12286                                    + perm.info.name + "; ignoring new declaration");
12287                            pkg.permissions.remove(i);
12288                        }
12289                    }
12290                }
12291            }
12292
12293        }
12294
12295        if (systemApp && onExternal) {
12296            // Disable updates to system apps on sdcard
12297            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12298                    "Cannot install updates to system apps on sdcard");
12299            return;
12300        }
12301
12302        if (args.move != null) {
12303            // We did an in-place move, so dex is ready to roll
12304            scanFlags |= SCAN_NO_DEX;
12305            scanFlags |= SCAN_MOVE;
12306
12307            synchronized (mPackages) {
12308                final PackageSetting ps = mSettings.mPackages.get(pkgName);
12309                if (ps == null) {
12310                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
12311                            "Missing settings for moved package " + pkgName);
12312                }
12313
12314                // We moved the entire application as-is, so bring over the
12315                // previously derived ABI information.
12316                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
12317                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
12318            }
12319
12320        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12321            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12322            scanFlags |= SCAN_NO_DEX;
12323
12324            try {
12325                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12326                        true /* extract libs */);
12327            } catch (PackageManagerException pme) {
12328                Slog.e(TAG, "Error deriving application ABI", pme);
12329                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12330                return;
12331            }
12332
12333            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12334            int result = mPackageDexOptimizer
12335                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12336                            false /* defer */, false /* inclDependencies */);
12337            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12338                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12339                return;
12340            }
12341        }
12342
12343        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12344            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12345            return;
12346        }
12347
12348        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12349
12350        if (replace) {
12351            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
12352                    installerPackageName, volumeUuid, res);
12353        } else {
12354            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12355                    args.user, installerPackageName, volumeUuid, res);
12356        }
12357        synchronized (mPackages) {
12358            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12359            if (ps != null) {
12360                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12361            }
12362        }
12363    }
12364
12365    private void startIntentFilterVerifications(int userId, boolean replacing,
12366            PackageParser.Package pkg) {
12367        if (mIntentFilterVerifierComponent == null) {
12368            Slog.w(TAG, "No IntentFilter verification will not be done as "
12369                    + "there is no IntentFilterVerifier available!");
12370            return;
12371        }
12372
12373        final int verifierUid = getPackageUid(
12374                mIntentFilterVerifierComponent.getPackageName(),
12375                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12376
12377        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12378        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12379        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12380        mHandler.sendMessage(msg);
12381    }
12382
12383    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12384            PackageParser.Package pkg) {
12385        int size = pkg.activities.size();
12386        if (size == 0) {
12387            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12388                    "No activity, so no need to verify any IntentFilter!");
12389            return;
12390        }
12391
12392        final boolean hasDomainURLs = hasDomainURLs(pkg);
12393        if (!hasDomainURLs) {
12394            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12395                    "No domain URLs, so no need to verify any IntentFilter!");
12396            return;
12397        }
12398
12399        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12400                + " if any IntentFilter from the " + size
12401                + " Activities needs verification ...");
12402
12403        int count = 0;
12404        final String packageName = pkg.packageName;
12405
12406        synchronized (mPackages) {
12407            // If this is a new install and we see that we've already run verification for this
12408            // package, we have nothing to do: it means the state was restored from backup.
12409            if (!replacing) {
12410                IntentFilterVerificationInfo ivi =
12411                        mSettings.getIntentFilterVerificationLPr(packageName);
12412                if (ivi != null) {
12413                    if (DEBUG_DOMAIN_VERIFICATION) {
12414                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12415                                + ivi.getStatusString());
12416                    }
12417                    return;
12418                }
12419            }
12420
12421            // If any filters need to be verified, then all need to be.
12422            boolean needToVerify = false;
12423            for (PackageParser.Activity a : pkg.activities) {
12424                for (ActivityIntentInfo filter : a.intents) {
12425                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12426                        if (DEBUG_DOMAIN_VERIFICATION) {
12427                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12428                        }
12429                        needToVerify = true;
12430                        break;
12431                    }
12432                }
12433            }
12434
12435            if (needToVerify) {
12436                final int verificationId = mIntentFilterVerificationToken++;
12437                for (PackageParser.Activity a : pkg.activities) {
12438                    for (ActivityIntentInfo filter : a.intents) {
12439                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12440                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12441                                    "Verification needed for IntentFilter:" + filter.toString());
12442                            mIntentFilterVerifier.addOneIntentFilterVerification(
12443                                    verifierUid, userId, verificationId, filter, packageName);
12444                            count++;
12445                        }
12446                    }
12447                }
12448            }
12449        }
12450
12451        if (count > 0) {
12452            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12453                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12454                    +  " for userId:" + userId);
12455            mIntentFilterVerifier.startVerifications(userId);
12456        } else {
12457            if (DEBUG_DOMAIN_VERIFICATION) {
12458                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12459            }
12460        }
12461    }
12462
12463    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12464        final ComponentName cn  = filter.activity.getComponentName();
12465        final String packageName = cn.getPackageName();
12466
12467        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12468                packageName);
12469        if (ivi == null) {
12470            return true;
12471        }
12472        int status = ivi.getStatus();
12473        switch (status) {
12474            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12475            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12476                return true;
12477
12478            default:
12479                // Nothing to do
12480                return false;
12481        }
12482    }
12483
12484    private static boolean isMultiArch(PackageSetting ps) {
12485        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12486    }
12487
12488    private static boolean isMultiArch(ApplicationInfo info) {
12489        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12490    }
12491
12492    private static boolean isExternal(PackageParser.Package pkg) {
12493        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12494    }
12495
12496    private static boolean isExternal(PackageSetting ps) {
12497        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12498    }
12499
12500    private static boolean isExternal(ApplicationInfo info) {
12501        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12502    }
12503
12504    private static boolean isSystemApp(PackageParser.Package pkg) {
12505        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12506    }
12507
12508    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12509        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12510    }
12511
12512    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12513        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12514    }
12515
12516    private static boolean isSystemApp(PackageSetting ps) {
12517        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12518    }
12519
12520    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12521        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12522    }
12523
12524    private int packageFlagsToInstallFlags(PackageSetting ps) {
12525        int installFlags = 0;
12526        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12527            // This existing package was an external ASEC install when we have
12528            // the external flag without a UUID
12529            installFlags |= PackageManager.INSTALL_EXTERNAL;
12530        }
12531        if (ps.isForwardLocked()) {
12532            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12533        }
12534        return installFlags;
12535    }
12536
12537    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
12538        if (isExternal(pkg)) {
12539            if (TextUtils.isEmpty(pkg.volumeUuid)) {
12540                return mSettings.getExternalVersion();
12541            } else {
12542                return mSettings.findOrCreateVersion(pkg.volumeUuid);
12543            }
12544        } else {
12545            return mSettings.getInternalVersion();
12546        }
12547    }
12548
12549    private void deleteTempPackageFiles() {
12550        final FilenameFilter filter = new FilenameFilter() {
12551            public boolean accept(File dir, String name) {
12552                return name.startsWith("vmdl") && name.endsWith(".tmp");
12553            }
12554        };
12555        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12556            file.delete();
12557        }
12558    }
12559
12560    @Override
12561    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12562            int flags) {
12563        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12564                flags);
12565    }
12566
12567    @Override
12568    public void deletePackage(final String packageName,
12569            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12570        mContext.enforceCallingOrSelfPermission(
12571                android.Manifest.permission.DELETE_PACKAGES, null);
12572        Preconditions.checkNotNull(packageName);
12573        Preconditions.checkNotNull(observer);
12574        final int uid = Binder.getCallingUid();
12575        if (UserHandle.getUserId(uid) != userId) {
12576            mContext.enforceCallingPermission(
12577                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12578                    "deletePackage for user " + userId);
12579        }
12580        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12581            try {
12582                observer.onPackageDeleted(packageName,
12583                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12584            } catch (RemoteException re) {
12585            }
12586            return;
12587        }
12588
12589        boolean uninstallBlocked = false;
12590        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12591            int[] users = sUserManager.getUserIds();
12592            for (int i = 0; i < users.length; ++i) {
12593                if (getBlockUninstallForUser(packageName, users[i])) {
12594                    uninstallBlocked = true;
12595                    break;
12596                }
12597            }
12598        } else {
12599            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12600        }
12601        if (uninstallBlocked) {
12602            try {
12603                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12604                        null);
12605            } catch (RemoteException re) {
12606            }
12607            return;
12608        }
12609
12610        if (DEBUG_REMOVE) {
12611            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12612        }
12613        // Queue up an async operation since the package deletion may take a little while.
12614        mHandler.post(new Runnable() {
12615            public void run() {
12616                mHandler.removeCallbacks(this);
12617                final int returnCode = deletePackageX(packageName, userId, flags);
12618                if (observer != null) {
12619                    try {
12620                        observer.onPackageDeleted(packageName, returnCode, null);
12621                    } catch (RemoteException e) {
12622                        Log.i(TAG, "Observer no longer exists.");
12623                    } //end catch
12624                } //end if
12625            } //end run
12626        });
12627    }
12628
12629    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12630        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12631                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12632        try {
12633            if (dpm != null) {
12634                if (dpm.isDeviceOwner(packageName)) {
12635                    return true;
12636                }
12637                int[] users;
12638                if (userId == UserHandle.USER_ALL) {
12639                    users = sUserManager.getUserIds();
12640                } else {
12641                    users = new int[]{userId};
12642                }
12643                for (int i = 0; i < users.length; ++i) {
12644                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12645                        return true;
12646                    }
12647                }
12648            }
12649        } catch (RemoteException e) {
12650        }
12651        return false;
12652    }
12653
12654    /**
12655     *  This method is an internal method that could be get invoked either
12656     *  to delete an installed package or to clean up a failed installation.
12657     *  After deleting an installed package, a broadcast is sent to notify any
12658     *  listeners that the package has been installed. For cleaning up a failed
12659     *  installation, the broadcast is not necessary since the package's
12660     *  installation wouldn't have sent the initial broadcast either
12661     *  The key steps in deleting a package are
12662     *  deleting the package information in internal structures like mPackages,
12663     *  deleting the packages base directories through installd
12664     *  updating mSettings to reflect current status
12665     *  persisting settings for later use
12666     *  sending a broadcast if necessary
12667     */
12668    private int deletePackageX(String packageName, int userId, int flags) {
12669        final PackageRemovedInfo info = new PackageRemovedInfo();
12670        final boolean res;
12671
12672        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12673                ? UserHandle.ALL : new UserHandle(userId);
12674
12675        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12676            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12677            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12678        }
12679
12680        boolean removedForAllUsers = false;
12681        boolean systemUpdate = false;
12682
12683        // for the uninstall-updates case and restricted profiles, remember the per-
12684        // userhandle installed state
12685        int[] allUsers;
12686        boolean[] perUserInstalled;
12687        synchronized (mPackages) {
12688            PackageSetting ps = mSettings.mPackages.get(packageName);
12689            allUsers = sUserManager.getUserIds();
12690            perUserInstalled = new boolean[allUsers.length];
12691            for (int i = 0; i < allUsers.length; i++) {
12692                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12693            }
12694        }
12695
12696        synchronized (mInstallLock) {
12697            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12698            res = deletePackageLI(packageName, removeForUser,
12699                    true, allUsers, perUserInstalled,
12700                    flags | REMOVE_CHATTY, info, true);
12701            systemUpdate = info.isRemovedPackageSystemUpdate;
12702            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12703                removedForAllUsers = true;
12704            }
12705            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12706                    + " removedForAllUsers=" + removedForAllUsers);
12707        }
12708
12709        if (res) {
12710            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12711
12712            // If the removed package was a system update, the old system package
12713            // was re-enabled; we need to broadcast this information
12714            if (systemUpdate) {
12715                Bundle extras = new Bundle(1);
12716                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12717                        ? info.removedAppId : info.uid);
12718                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12719
12720                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12721                        extras, null, null, null);
12722                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12723                        extras, null, null, null);
12724                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12725                        null, packageName, null, null);
12726            }
12727        }
12728        // Force a gc here.
12729        Runtime.getRuntime().gc();
12730        // Delete the resources here after sending the broadcast to let
12731        // other processes clean up before deleting resources.
12732        if (info.args != null) {
12733            synchronized (mInstallLock) {
12734                info.args.doPostDeleteLI(true);
12735            }
12736        }
12737
12738        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12739    }
12740
12741    class PackageRemovedInfo {
12742        String removedPackage;
12743        int uid = -1;
12744        int removedAppId = -1;
12745        int[] removedUsers = null;
12746        boolean isRemovedPackageSystemUpdate = false;
12747        // Clean up resources deleted packages.
12748        InstallArgs args = null;
12749
12750        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12751            Bundle extras = new Bundle(1);
12752            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12753            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12754            if (replacing) {
12755                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12756            }
12757            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12758            if (removedPackage != null) {
12759                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12760                        extras, null, null, removedUsers);
12761                if (fullRemove && !replacing) {
12762                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12763                            extras, null, null, removedUsers);
12764                }
12765            }
12766            if (removedAppId >= 0) {
12767                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12768                        removedUsers);
12769            }
12770        }
12771    }
12772
12773    /*
12774     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12775     * flag is not set, the data directory is removed as well.
12776     * make sure this flag is set for partially installed apps. If not its meaningless to
12777     * delete a partially installed application.
12778     */
12779    private void removePackageDataLI(PackageSetting ps,
12780            int[] allUserHandles, boolean[] perUserInstalled,
12781            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12782        String packageName = ps.name;
12783        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12784        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12785        // Retrieve object to delete permissions for shared user later on
12786        final PackageSetting deletedPs;
12787        // reader
12788        synchronized (mPackages) {
12789            deletedPs = mSettings.mPackages.get(packageName);
12790            if (outInfo != null) {
12791                outInfo.removedPackage = packageName;
12792                outInfo.removedUsers = deletedPs != null
12793                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12794                        : null;
12795            }
12796        }
12797        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12798            removeDataDirsLI(ps.volumeUuid, packageName);
12799            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12800        }
12801        // writer
12802        synchronized (mPackages) {
12803            if (deletedPs != null) {
12804                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12805                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12806                    clearDefaultBrowserIfNeeded(packageName);
12807                    if (outInfo != null) {
12808                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12809                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12810                    }
12811                    updatePermissionsLPw(deletedPs.name, null, 0);
12812                    if (deletedPs.sharedUser != null) {
12813                        // Remove permissions associated with package. Since runtime
12814                        // permissions are per user we have to kill the removed package
12815                        // or packages running under the shared user of the removed
12816                        // package if revoking the permissions requested only by the removed
12817                        // package is successful and this causes a change in gids.
12818                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12819                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12820                                    userId);
12821                            if (userIdToKill == UserHandle.USER_ALL
12822                                    || userIdToKill >= UserHandle.USER_OWNER) {
12823                                // If gids changed for this user, kill all affected packages.
12824                                mHandler.post(new Runnable() {
12825                                    @Override
12826                                    public void run() {
12827                                        // This has to happen with no lock held.
12828                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12829                                                KILL_APP_REASON_GIDS_CHANGED);
12830                                    }
12831                                });
12832                                break;
12833                            }
12834                        }
12835                    }
12836                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12837                }
12838                // make sure to preserve per-user disabled state if this removal was just
12839                // a downgrade of a system app to the factory package
12840                if (allUserHandles != null && perUserInstalled != null) {
12841                    if (DEBUG_REMOVE) {
12842                        Slog.d(TAG, "Propagating install state across downgrade");
12843                    }
12844                    for (int i = 0; i < allUserHandles.length; i++) {
12845                        if (DEBUG_REMOVE) {
12846                            Slog.d(TAG, "    user " + allUserHandles[i]
12847                                    + " => " + perUserInstalled[i]);
12848                        }
12849                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12850                    }
12851                }
12852            }
12853            // can downgrade to reader
12854            if (writeSettings) {
12855                // Save settings now
12856                mSettings.writeLPr();
12857            }
12858        }
12859        if (outInfo != null) {
12860            // A user ID was deleted here. Go through all users and remove it
12861            // from KeyStore.
12862            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12863        }
12864    }
12865
12866    static boolean locationIsPrivileged(File path) {
12867        try {
12868            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12869                    .getCanonicalPath();
12870            return path.getCanonicalPath().startsWith(privilegedAppDir);
12871        } catch (IOException e) {
12872            Slog.e(TAG, "Unable to access code path " + path);
12873        }
12874        return false;
12875    }
12876
12877    /*
12878     * Tries to delete system package.
12879     */
12880    private boolean deleteSystemPackageLI(PackageSetting newPs,
12881            int[] allUserHandles, boolean[] perUserInstalled,
12882            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12883        final boolean applyUserRestrictions
12884                = (allUserHandles != null) && (perUserInstalled != null);
12885        PackageSetting disabledPs = null;
12886        // Confirm if the system package has been updated
12887        // An updated system app can be deleted. This will also have to restore
12888        // the system pkg from system partition
12889        // reader
12890        synchronized (mPackages) {
12891            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12892        }
12893        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12894                + " disabledPs=" + disabledPs);
12895        if (disabledPs == null) {
12896            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12897            return false;
12898        } else if (DEBUG_REMOVE) {
12899            Slog.d(TAG, "Deleting system pkg from data partition");
12900        }
12901        if (DEBUG_REMOVE) {
12902            if (applyUserRestrictions) {
12903                Slog.d(TAG, "Remembering install states:");
12904                for (int i = 0; i < allUserHandles.length; i++) {
12905                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12906                }
12907            }
12908        }
12909        // Delete the updated package
12910        outInfo.isRemovedPackageSystemUpdate = true;
12911        if (disabledPs.versionCode < newPs.versionCode) {
12912            // Delete data for downgrades
12913            flags &= ~PackageManager.DELETE_KEEP_DATA;
12914        } else {
12915            // Preserve data by setting flag
12916            flags |= PackageManager.DELETE_KEEP_DATA;
12917        }
12918        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12919                allUserHandles, perUserInstalled, outInfo, writeSettings);
12920        if (!ret) {
12921            return false;
12922        }
12923        // writer
12924        synchronized (mPackages) {
12925            // Reinstate the old system package
12926            mSettings.enableSystemPackageLPw(newPs.name);
12927            // Remove any native libraries from the upgraded package.
12928            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12929        }
12930        // Install the system package
12931        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12932        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12933        if (locationIsPrivileged(disabledPs.codePath)) {
12934            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12935        }
12936
12937        final PackageParser.Package newPkg;
12938        try {
12939            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12940        } catch (PackageManagerException e) {
12941            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12942            return false;
12943        }
12944
12945        // writer
12946        synchronized (mPackages) {
12947            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12948
12949            updatePermissionsLPw(newPkg.packageName, newPkg,
12950                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12951
12952            if (applyUserRestrictions) {
12953                if (DEBUG_REMOVE) {
12954                    Slog.d(TAG, "Propagating install state across reinstall");
12955                }
12956                for (int i = 0; i < allUserHandles.length; i++) {
12957                    if (DEBUG_REMOVE) {
12958                        Slog.d(TAG, "    user " + allUserHandles[i]
12959                                + " => " + perUserInstalled[i]);
12960                    }
12961                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12962
12963                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
12964                }
12965                // Regardless of writeSettings we need to ensure that this restriction
12966                // state propagation is persisted
12967                mSettings.writeAllUsersPackageRestrictionsLPr();
12968            }
12969            // can downgrade to reader here
12970            if (writeSettings) {
12971                mSettings.writeLPr();
12972            }
12973        }
12974        return true;
12975    }
12976
12977    private boolean deleteInstalledPackageLI(PackageSetting ps,
12978            boolean deleteCodeAndResources, int flags,
12979            int[] allUserHandles, boolean[] perUserInstalled,
12980            PackageRemovedInfo outInfo, boolean writeSettings) {
12981        if (outInfo != null) {
12982            outInfo.uid = ps.appId;
12983        }
12984
12985        // Delete package data from internal structures and also remove data if flag is set
12986        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12987
12988        // Delete application code and resources
12989        if (deleteCodeAndResources && (outInfo != null)) {
12990            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12991                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12992            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12993        }
12994        return true;
12995    }
12996
12997    @Override
12998    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12999            int userId) {
13000        mContext.enforceCallingOrSelfPermission(
13001                android.Manifest.permission.DELETE_PACKAGES, null);
13002        synchronized (mPackages) {
13003            PackageSetting ps = mSettings.mPackages.get(packageName);
13004            if (ps == null) {
13005                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13006                return false;
13007            }
13008            if (!ps.getInstalled(userId)) {
13009                // Can't block uninstall for an app that is not installed or enabled.
13010                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13011                return false;
13012            }
13013            ps.setBlockUninstall(blockUninstall, userId);
13014            mSettings.writePackageRestrictionsLPr(userId);
13015        }
13016        return true;
13017    }
13018
13019    @Override
13020    public boolean getBlockUninstallForUser(String packageName, int userId) {
13021        synchronized (mPackages) {
13022            PackageSetting ps = mSettings.mPackages.get(packageName);
13023            if (ps == null) {
13024                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13025                return false;
13026            }
13027            return ps.getBlockUninstall(userId);
13028        }
13029    }
13030
13031    /*
13032     * This method handles package deletion in general
13033     */
13034    private boolean deletePackageLI(String packageName, UserHandle user,
13035            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13036            int flags, PackageRemovedInfo outInfo,
13037            boolean writeSettings) {
13038        if (packageName == null) {
13039            Slog.w(TAG, "Attempt to delete null packageName.");
13040            return false;
13041        }
13042        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13043        PackageSetting ps;
13044        boolean dataOnly = false;
13045        int removeUser = -1;
13046        int appId = -1;
13047        synchronized (mPackages) {
13048            ps = mSettings.mPackages.get(packageName);
13049            if (ps == null) {
13050                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13051                return false;
13052            }
13053            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13054                    && user.getIdentifier() != UserHandle.USER_ALL) {
13055                // The caller is asking that the package only be deleted for a single
13056                // user.  To do this, we just mark its uninstalled state and delete
13057                // its data.  If this is a system app, we only allow this to happen if
13058                // they have set the special DELETE_SYSTEM_APP which requests different
13059                // semantics than normal for uninstalling system apps.
13060                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13061                ps.setUserState(user.getIdentifier(),
13062                        COMPONENT_ENABLED_STATE_DEFAULT,
13063                        false, //installed
13064                        true,  //stopped
13065                        true,  //notLaunched
13066                        false, //hidden
13067                        null, null, null,
13068                        false, // blockUninstall
13069                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED, 0);
13070                if (!isSystemApp(ps)) {
13071                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
13072                        // Other user still have this package installed, so all
13073                        // we need to do is clear this user's data and save that
13074                        // it is uninstalled.
13075                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13076                        removeUser = user.getIdentifier();
13077                        appId = ps.appId;
13078                        scheduleWritePackageRestrictionsLocked(removeUser);
13079                    } else {
13080                        // We need to set it back to 'installed' so the uninstall
13081                        // broadcasts will be sent correctly.
13082                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13083                        ps.setInstalled(true, user.getIdentifier());
13084                    }
13085                } else {
13086                    // This is a system app, so we assume that the
13087                    // other users still have this package installed, so all
13088                    // we need to do is clear this user's data and save that
13089                    // it is uninstalled.
13090                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13091                    removeUser = user.getIdentifier();
13092                    appId = ps.appId;
13093                    scheduleWritePackageRestrictionsLocked(removeUser);
13094                }
13095            }
13096        }
13097
13098        if (removeUser >= 0) {
13099            // From above, we determined that we are deleting this only
13100            // for a single user.  Continue the work here.
13101            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13102            if (outInfo != null) {
13103                outInfo.removedPackage = packageName;
13104                outInfo.removedAppId = appId;
13105                outInfo.removedUsers = new int[] {removeUser};
13106            }
13107            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13108            removeKeystoreDataIfNeeded(removeUser, appId);
13109            schedulePackageCleaning(packageName, removeUser, false);
13110            synchronized (mPackages) {
13111                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13112                    scheduleWritePackageRestrictionsLocked(removeUser);
13113                }
13114                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13115            }
13116            return true;
13117        }
13118
13119        if (dataOnly) {
13120            // Delete application data first
13121            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13122            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13123            return true;
13124        }
13125
13126        boolean ret = false;
13127        if (isSystemApp(ps)) {
13128            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13129            // When an updated system application is deleted we delete the existing resources as well and
13130            // fall back to existing code in system partition
13131            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13132                    flags, outInfo, writeSettings);
13133        } else {
13134            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13135            // Kill application pre-emptively especially for apps on sd.
13136            killApplication(packageName, ps.appId, "uninstall pkg");
13137            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13138                    allUserHandles, perUserInstalled,
13139                    outInfo, writeSettings);
13140        }
13141
13142        return ret;
13143    }
13144
13145    private final class ClearStorageConnection implements ServiceConnection {
13146        IMediaContainerService mContainerService;
13147
13148        @Override
13149        public void onServiceConnected(ComponentName name, IBinder service) {
13150            synchronized (this) {
13151                mContainerService = IMediaContainerService.Stub.asInterface(service);
13152                notifyAll();
13153            }
13154        }
13155
13156        @Override
13157        public void onServiceDisconnected(ComponentName name) {
13158        }
13159    }
13160
13161    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13162        final boolean mounted;
13163        if (Environment.isExternalStorageEmulated()) {
13164            mounted = true;
13165        } else {
13166            final String status = Environment.getExternalStorageState();
13167
13168            mounted = status.equals(Environment.MEDIA_MOUNTED)
13169                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13170        }
13171
13172        if (!mounted) {
13173            return;
13174        }
13175
13176        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13177        int[] users;
13178        if (userId == UserHandle.USER_ALL) {
13179            users = sUserManager.getUserIds();
13180        } else {
13181            users = new int[] { userId };
13182        }
13183        final ClearStorageConnection conn = new ClearStorageConnection();
13184        if (mContext.bindServiceAsUser(
13185                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
13186            try {
13187                for (int curUser : users) {
13188                    long timeout = SystemClock.uptimeMillis() + 5000;
13189                    synchronized (conn) {
13190                        long now = SystemClock.uptimeMillis();
13191                        while (conn.mContainerService == null && now < timeout) {
13192                            try {
13193                                conn.wait(timeout - now);
13194                            } catch (InterruptedException e) {
13195                            }
13196                        }
13197                    }
13198                    if (conn.mContainerService == null) {
13199                        return;
13200                    }
13201
13202                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13203                    clearDirectory(conn.mContainerService,
13204                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13205                    if (allData) {
13206                        clearDirectory(conn.mContainerService,
13207                                userEnv.buildExternalStorageAppDataDirs(packageName));
13208                        clearDirectory(conn.mContainerService,
13209                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13210                    }
13211                }
13212            } finally {
13213                mContext.unbindService(conn);
13214            }
13215        }
13216    }
13217
13218    @Override
13219    public void clearApplicationUserData(final String packageName,
13220            final IPackageDataObserver observer, final int userId) {
13221        mContext.enforceCallingOrSelfPermission(
13222                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13223        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13224        // Queue up an async operation since the package deletion may take a little while.
13225        mHandler.post(new Runnable() {
13226            public void run() {
13227                mHandler.removeCallbacks(this);
13228                final boolean succeeded;
13229                synchronized (mInstallLock) {
13230                    succeeded = clearApplicationUserDataLI(packageName, userId);
13231                }
13232                clearExternalStorageDataSync(packageName, userId, true);
13233                if (succeeded) {
13234                    // invoke DeviceStorageMonitor's update method to clear any notifications
13235                    DeviceStorageMonitorInternal
13236                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13237                    if (dsm != null) {
13238                        dsm.checkMemory();
13239                    }
13240                }
13241                if(observer != null) {
13242                    try {
13243                        observer.onRemoveCompleted(packageName, succeeded);
13244                    } catch (RemoteException e) {
13245                        Log.i(TAG, "Observer no longer exists.");
13246                    }
13247                } //end if observer
13248            } //end run
13249        });
13250    }
13251
13252    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13253        if (packageName == null) {
13254            Slog.w(TAG, "Attempt to delete null packageName.");
13255            return false;
13256        }
13257
13258        // Try finding details about the requested package
13259        PackageParser.Package pkg;
13260        synchronized (mPackages) {
13261            pkg = mPackages.get(packageName);
13262            if (pkg == null) {
13263                final PackageSetting ps = mSettings.mPackages.get(packageName);
13264                if (ps != null) {
13265                    pkg = ps.pkg;
13266                }
13267            }
13268
13269            if (pkg == null) {
13270                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13271                return false;
13272            }
13273
13274            PackageSetting ps = (PackageSetting) pkg.mExtras;
13275            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13276        }
13277
13278        // Always delete data directories for package, even if we found no other
13279        // record of app. This helps users recover from UID mismatches without
13280        // resorting to a full data wipe.
13281        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13282        if (retCode < 0) {
13283            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13284            return false;
13285        }
13286
13287        final int appId = pkg.applicationInfo.uid;
13288        removeKeystoreDataIfNeeded(userId, appId);
13289
13290        // Create a native library symlink only if we have native libraries
13291        // and if the native libraries are 32 bit libraries. We do not provide
13292        // this symlink for 64 bit libraries.
13293        if (pkg.applicationInfo.primaryCpuAbi != null &&
13294                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13295            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13296            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13297                    nativeLibPath, userId) < 0) {
13298                Slog.w(TAG, "Failed linking native library dir");
13299                return false;
13300            }
13301        }
13302
13303        return true;
13304    }
13305
13306    /**
13307     * Reverts user permission state changes (permissions and flags) in
13308     * all packages for a given user.
13309     *
13310     * @param userId The device user for which to do a reset.
13311     */
13312    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
13313        final int packageCount = mPackages.size();
13314        for (int i = 0; i < packageCount; i++) {
13315            PackageParser.Package pkg = mPackages.valueAt(i);
13316            PackageSetting ps = (PackageSetting) pkg.mExtras;
13317            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13318        }
13319    }
13320
13321    /**
13322     * Reverts user permission state changes (permissions and flags).
13323     *
13324     * @param ps The package for which to reset.
13325     * @param userId The device user for which to do a reset.
13326     */
13327    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
13328            final PackageSetting ps, final int userId) {
13329        if (ps.pkg == null) {
13330            return;
13331        }
13332
13333        final int userSettableFlags = FLAG_PERMISSION_USER_SET
13334                | FLAG_PERMISSION_USER_FIXED
13335                | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13336
13337        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13338                | FLAG_PERMISSION_POLICY_FIXED;
13339
13340        boolean writeInstallPermissions = false;
13341        boolean writeRuntimePermissions = false;
13342
13343        final int permissionCount = ps.pkg.requestedPermissions.size();
13344        for (int i = 0; i < permissionCount; i++) {
13345            String permission = ps.pkg.requestedPermissions.get(i);
13346
13347            BasePermission bp = mSettings.mPermissions.get(permission);
13348            if (bp == null) {
13349                continue;
13350            }
13351
13352            // If shared user we just reset the state to which only this app contributed.
13353            if (ps.sharedUser != null) {
13354                boolean used = false;
13355                final int packageCount = ps.sharedUser.packages.size();
13356                for (int j = 0; j < packageCount; j++) {
13357                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13358                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13359                            && pkg.pkg.requestedPermissions.contains(permission)) {
13360                        used = true;
13361                        break;
13362                    }
13363                }
13364                if (used) {
13365                    continue;
13366                }
13367            }
13368
13369            PermissionsState permissionsState = ps.getPermissionsState();
13370
13371            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13372
13373            // Always clear the user settable flags.
13374            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13375                    bp.name) != null;
13376            if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13377                if (hasInstallState) {
13378                    writeInstallPermissions = true;
13379                } else {
13380                    writeRuntimePermissions = true;
13381                }
13382            }
13383
13384            // Below is only runtime permission handling.
13385            if (!bp.isRuntime()) {
13386                continue;
13387            }
13388
13389            // Never clobber system or policy.
13390            if ((oldFlags & policyOrSystemFlags) != 0) {
13391                continue;
13392            }
13393
13394            // If this permission was granted by default, make sure it is.
13395            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13396                if (permissionsState.grantRuntimePermission(bp, userId)
13397                        != PERMISSION_OPERATION_FAILURE) {
13398                    writeRuntimePermissions = true;
13399                }
13400            } else {
13401                // Otherwise, reset the permission.
13402                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13403                switch (revokeResult) {
13404                    case PERMISSION_OPERATION_SUCCESS: {
13405                        writeRuntimePermissions = true;
13406                    } break;
13407
13408                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13409                        writeRuntimePermissions = true;
13410                        // If gids changed for this user, kill all affected packages.
13411                        mHandler.post(new Runnable() {
13412                            @Override
13413                            public void run() {
13414                                // This has to happen with no lock held.
13415                                killSettingPackagesForUser(ps, userId,
13416                                        KILL_APP_REASON_GIDS_CHANGED);
13417                            }
13418                        });
13419                    } break;
13420                }
13421            }
13422        }
13423
13424        // Synchronously write as we are taking permissions away.
13425        if (writeRuntimePermissions) {
13426            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13427        }
13428
13429        // Synchronously write as we are taking permissions away.
13430        if (writeInstallPermissions) {
13431            mSettings.writeLPr();
13432        }
13433    }
13434
13435    /**
13436     * Remove entries from the keystore daemon. Will only remove it if the
13437     * {@code appId} is valid.
13438     */
13439    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13440        if (appId < 0) {
13441            return;
13442        }
13443
13444        final KeyStore keyStore = KeyStore.getInstance();
13445        if (keyStore != null) {
13446            if (userId == UserHandle.USER_ALL) {
13447                for (final int individual : sUserManager.getUserIds()) {
13448                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13449                }
13450            } else {
13451                keyStore.clearUid(UserHandle.getUid(userId, appId));
13452            }
13453        } else {
13454            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13455        }
13456    }
13457
13458    @Override
13459    public void deleteApplicationCacheFiles(final String packageName,
13460            final IPackageDataObserver observer) {
13461        mContext.enforceCallingOrSelfPermission(
13462                android.Manifest.permission.DELETE_CACHE_FILES, null);
13463        // Queue up an async operation since the package deletion may take a little while.
13464        final int userId = UserHandle.getCallingUserId();
13465        mHandler.post(new Runnable() {
13466            public void run() {
13467                mHandler.removeCallbacks(this);
13468                final boolean succeded;
13469                synchronized (mInstallLock) {
13470                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13471                }
13472                clearExternalStorageDataSync(packageName, userId, false);
13473                if (observer != null) {
13474                    try {
13475                        observer.onRemoveCompleted(packageName, succeded);
13476                    } catch (RemoteException e) {
13477                        Log.i(TAG, "Observer no longer exists.");
13478                    }
13479                } //end if observer
13480            } //end run
13481        });
13482    }
13483
13484    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13485        if (packageName == null) {
13486            Slog.w(TAG, "Attempt to delete null packageName.");
13487            return false;
13488        }
13489        PackageParser.Package p;
13490        synchronized (mPackages) {
13491            p = mPackages.get(packageName);
13492        }
13493        if (p == null) {
13494            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13495            return false;
13496        }
13497        final ApplicationInfo applicationInfo = p.applicationInfo;
13498        if (applicationInfo == null) {
13499            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13500            return false;
13501        }
13502        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13503        if (retCode < 0) {
13504            Slog.w(TAG, "Couldn't remove cache files for package: "
13505                       + packageName + " u" + userId);
13506            return false;
13507        }
13508        return true;
13509    }
13510
13511    @Override
13512    public void getPackageSizeInfo(final String packageName, int userHandle,
13513            final IPackageStatsObserver observer) {
13514        mContext.enforceCallingOrSelfPermission(
13515                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13516        if (packageName == null) {
13517            throw new IllegalArgumentException("Attempt to get size of null packageName");
13518        }
13519
13520        PackageStats stats = new PackageStats(packageName, userHandle);
13521
13522        /*
13523         * Queue up an async operation since the package measurement may take a
13524         * little while.
13525         */
13526        Message msg = mHandler.obtainMessage(INIT_COPY);
13527        msg.obj = new MeasureParams(stats, observer);
13528        mHandler.sendMessage(msg);
13529    }
13530
13531    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13532            PackageStats pStats) {
13533        if (packageName == null) {
13534            Slog.w(TAG, "Attempt to get size of null packageName.");
13535            return false;
13536        }
13537        PackageParser.Package p;
13538        boolean dataOnly = false;
13539        String libDirRoot = null;
13540        String asecPath = null;
13541        PackageSetting ps = null;
13542        synchronized (mPackages) {
13543            p = mPackages.get(packageName);
13544            ps = mSettings.mPackages.get(packageName);
13545            if(p == null) {
13546                dataOnly = true;
13547                if((ps == null) || (ps.pkg == null)) {
13548                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13549                    return false;
13550                }
13551                p = ps.pkg;
13552            }
13553            if (ps != null) {
13554                libDirRoot = ps.legacyNativeLibraryPathString;
13555            }
13556            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13557                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13558                if (secureContainerId != null) {
13559                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13560                }
13561            }
13562        }
13563        String publicSrcDir = null;
13564        if(!dataOnly) {
13565            final ApplicationInfo applicationInfo = p.applicationInfo;
13566            if (applicationInfo == null) {
13567                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13568                return false;
13569            }
13570            if (p.isForwardLocked()) {
13571                publicSrcDir = applicationInfo.getBaseResourcePath();
13572            }
13573        }
13574        // TODO: extend to measure size of split APKs
13575        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13576        // not just the first level.
13577        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13578        // just the primary.
13579        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13580        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13581                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13582        if (res < 0) {
13583            return false;
13584        }
13585
13586        // Fix-up for forward-locked applications in ASEC containers.
13587        if (!isExternal(p)) {
13588            pStats.codeSize += pStats.externalCodeSize;
13589            pStats.externalCodeSize = 0L;
13590        }
13591
13592        return true;
13593    }
13594
13595
13596    @Override
13597    public void addPackageToPreferred(String packageName) {
13598        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13599    }
13600
13601    @Override
13602    public void removePackageFromPreferred(String packageName) {
13603        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13604    }
13605
13606    @Override
13607    public List<PackageInfo> getPreferredPackages(int flags) {
13608        return new ArrayList<PackageInfo>();
13609    }
13610
13611    private int getUidTargetSdkVersionLockedLPr(int uid) {
13612        Object obj = mSettings.getUserIdLPr(uid);
13613        if (obj instanceof SharedUserSetting) {
13614            final SharedUserSetting sus = (SharedUserSetting) obj;
13615            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13616            final Iterator<PackageSetting> it = sus.packages.iterator();
13617            while (it.hasNext()) {
13618                final PackageSetting ps = it.next();
13619                if (ps.pkg != null) {
13620                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13621                    if (v < vers) vers = v;
13622                }
13623            }
13624            return vers;
13625        } else if (obj instanceof PackageSetting) {
13626            final PackageSetting ps = (PackageSetting) obj;
13627            if (ps.pkg != null) {
13628                return ps.pkg.applicationInfo.targetSdkVersion;
13629            }
13630        }
13631        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13632    }
13633
13634    @Override
13635    public void addPreferredActivity(IntentFilter filter, int match,
13636            ComponentName[] set, ComponentName activity, int userId) {
13637        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13638                "Adding preferred");
13639    }
13640
13641    private void addPreferredActivityInternal(IntentFilter filter, int match,
13642            ComponentName[] set, ComponentName activity, boolean always, int userId,
13643            String opname) {
13644        // writer
13645        int callingUid = Binder.getCallingUid();
13646        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13647        if (filter.countActions() == 0) {
13648            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13649            return;
13650        }
13651        synchronized (mPackages) {
13652            if (mContext.checkCallingOrSelfPermission(
13653                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13654                    != PackageManager.PERMISSION_GRANTED) {
13655                if (getUidTargetSdkVersionLockedLPr(callingUid)
13656                        < Build.VERSION_CODES.FROYO) {
13657                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13658                            + callingUid);
13659                    return;
13660                }
13661                mContext.enforceCallingOrSelfPermission(
13662                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13663            }
13664
13665            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13666            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13667                    + userId + ":");
13668            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13669            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13670            scheduleWritePackageRestrictionsLocked(userId);
13671        }
13672    }
13673
13674    @Override
13675    public void replacePreferredActivity(IntentFilter filter, int match,
13676            ComponentName[] set, ComponentName activity, int userId) {
13677        if (filter.countActions() != 1) {
13678            throw new IllegalArgumentException(
13679                    "replacePreferredActivity expects filter to have only 1 action.");
13680        }
13681        if (filter.countDataAuthorities() != 0
13682                || filter.countDataPaths() != 0
13683                || filter.countDataSchemes() > 1
13684                || filter.countDataTypes() != 0) {
13685            throw new IllegalArgumentException(
13686                    "replacePreferredActivity expects filter to have no data authorities, " +
13687                    "paths, or types; and at most one scheme.");
13688        }
13689
13690        final int callingUid = Binder.getCallingUid();
13691        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13692        synchronized (mPackages) {
13693            if (mContext.checkCallingOrSelfPermission(
13694                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13695                    != PackageManager.PERMISSION_GRANTED) {
13696                if (getUidTargetSdkVersionLockedLPr(callingUid)
13697                        < Build.VERSION_CODES.FROYO) {
13698                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13699                            + Binder.getCallingUid());
13700                    return;
13701                }
13702                mContext.enforceCallingOrSelfPermission(
13703                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13704            }
13705
13706            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13707            if (pir != null) {
13708                // Get all of the existing entries that exactly match this filter.
13709                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13710                if (existing != null && existing.size() == 1) {
13711                    PreferredActivity cur = existing.get(0);
13712                    if (DEBUG_PREFERRED) {
13713                        Slog.i(TAG, "Checking replace of preferred:");
13714                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13715                        if (!cur.mPref.mAlways) {
13716                            Slog.i(TAG, "  -- CUR; not mAlways!");
13717                        } else {
13718                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13719                            Slog.i(TAG, "  -- CUR: mSet="
13720                                    + Arrays.toString(cur.mPref.mSetComponents));
13721                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13722                            Slog.i(TAG, "  -- NEW: mMatch="
13723                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13724                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13725                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13726                        }
13727                    }
13728                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13729                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13730                            && cur.mPref.sameSet(set)) {
13731                        // Setting the preferred activity to what it happens to be already
13732                        if (DEBUG_PREFERRED) {
13733                            Slog.i(TAG, "Replacing with same preferred activity "
13734                                    + cur.mPref.mShortComponent + " for user "
13735                                    + userId + ":");
13736                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13737                        }
13738                        return;
13739                    }
13740                }
13741
13742                if (existing != null) {
13743                    if (DEBUG_PREFERRED) {
13744                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13745                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13746                    }
13747                    for (int i = 0; i < existing.size(); i++) {
13748                        PreferredActivity pa = existing.get(i);
13749                        if (DEBUG_PREFERRED) {
13750                            Slog.i(TAG, "Removing existing preferred activity "
13751                                    + pa.mPref.mComponent + ":");
13752                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13753                        }
13754                        pir.removeFilter(pa);
13755                    }
13756                }
13757            }
13758            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13759                    "Replacing preferred");
13760        }
13761    }
13762
13763    @Override
13764    public void clearPackagePreferredActivities(String packageName) {
13765        final int uid = Binder.getCallingUid();
13766        // writer
13767        synchronized (mPackages) {
13768            PackageParser.Package pkg = mPackages.get(packageName);
13769            if (pkg == null || pkg.applicationInfo.uid != uid) {
13770                if (mContext.checkCallingOrSelfPermission(
13771                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13772                        != PackageManager.PERMISSION_GRANTED) {
13773                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13774                            < Build.VERSION_CODES.FROYO) {
13775                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13776                                + Binder.getCallingUid());
13777                        return;
13778                    }
13779                    mContext.enforceCallingOrSelfPermission(
13780                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13781                }
13782            }
13783
13784            int user = UserHandle.getCallingUserId();
13785            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13786                scheduleWritePackageRestrictionsLocked(user);
13787            }
13788        }
13789    }
13790
13791    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13792    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13793        ArrayList<PreferredActivity> removed = null;
13794        boolean changed = false;
13795        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13796            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13797            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13798            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13799                continue;
13800            }
13801            Iterator<PreferredActivity> it = pir.filterIterator();
13802            while (it.hasNext()) {
13803                PreferredActivity pa = it.next();
13804                // Mark entry for removal only if it matches the package name
13805                // and the entry is of type "always".
13806                if (packageName == null ||
13807                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13808                                && pa.mPref.mAlways)) {
13809                    if (removed == null) {
13810                        removed = new ArrayList<PreferredActivity>();
13811                    }
13812                    removed.add(pa);
13813                }
13814            }
13815            if (removed != null) {
13816                for (int j=0; j<removed.size(); j++) {
13817                    PreferredActivity pa = removed.get(j);
13818                    pir.removeFilter(pa);
13819                }
13820                changed = true;
13821            }
13822        }
13823        return changed;
13824    }
13825
13826    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13827    private void clearIntentFilterVerificationsLPw(int userId) {
13828        final int packageCount = mPackages.size();
13829        for (int i = 0; i < packageCount; i++) {
13830            PackageParser.Package pkg = mPackages.valueAt(i);
13831            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
13832        }
13833    }
13834
13835    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13836    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13837        if (userId == UserHandle.USER_ALL) {
13838            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13839                    sUserManager.getUserIds())) {
13840                for (int oneUserId : sUserManager.getUserIds()) {
13841                    scheduleWritePackageRestrictionsLocked(oneUserId);
13842                }
13843            }
13844        } else {
13845            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13846                scheduleWritePackageRestrictionsLocked(userId);
13847            }
13848        }
13849    }
13850
13851    void clearDefaultBrowserIfNeeded(String packageName) {
13852        for (int oneUserId : sUserManager.getUserIds()) {
13853            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13854            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13855            if (packageName.equals(defaultBrowserPackageName)) {
13856                setDefaultBrowserPackageName(null, oneUserId);
13857            }
13858        }
13859    }
13860
13861    @Override
13862    public void resetApplicationPreferences(int userId) {
13863        mContext.enforceCallingOrSelfPermission(
13864                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13865        // writer
13866        synchronized (mPackages) {
13867            final long identity = Binder.clearCallingIdentity();
13868            try {
13869                clearPackagePreferredActivitiesLPw(null, userId);
13870                mSettings.applyDefaultPreferredAppsLPw(this, userId);
13871                // TODO: We have to reset the default SMS and Phone. This requires
13872                // significant refactoring to keep all default apps in the package
13873                // manager (cleaner but more work) or have the services provide
13874                // callbacks to the package manager to request a default app reset.
13875                applyFactoryDefaultBrowserLPw(userId);
13876                clearIntentFilterVerificationsLPw(userId);
13877                primeDomainVerificationsLPw(userId);
13878                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
13879                scheduleWritePackageRestrictionsLocked(userId);
13880            } finally {
13881                Binder.restoreCallingIdentity(identity);
13882            }
13883        }
13884    }
13885
13886    @Override
13887    public int getPreferredActivities(List<IntentFilter> outFilters,
13888            List<ComponentName> outActivities, String packageName) {
13889
13890        int num = 0;
13891        final int userId = UserHandle.getCallingUserId();
13892        // reader
13893        synchronized (mPackages) {
13894            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13895            if (pir != null) {
13896                final Iterator<PreferredActivity> it = pir.filterIterator();
13897                while (it.hasNext()) {
13898                    final PreferredActivity pa = it.next();
13899                    if (packageName == null
13900                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13901                                    && pa.mPref.mAlways)) {
13902                        if (outFilters != null) {
13903                            outFilters.add(new IntentFilter(pa));
13904                        }
13905                        if (outActivities != null) {
13906                            outActivities.add(pa.mPref.mComponent);
13907                        }
13908                    }
13909                }
13910            }
13911        }
13912
13913        return num;
13914    }
13915
13916    @Override
13917    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13918            int userId) {
13919        int callingUid = Binder.getCallingUid();
13920        if (callingUid != Process.SYSTEM_UID) {
13921            throw new SecurityException(
13922                    "addPersistentPreferredActivity can only be run by the system");
13923        }
13924        if (filter.countActions() == 0) {
13925            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13926            return;
13927        }
13928        synchronized (mPackages) {
13929            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13930                    " :");
13931            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13932            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13933                    new PersistentPreferredActivity(filter, activity));
13934            scheduleWritePackageRestrictionsLocked(userId);
13935        }
13936    }
13937
13938    @Override
13939    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13940        int callingUid = Binder.getCallingUid();
13941        if (callingUid != Process.SYSTEM_UID) {
13942            throw new SecurityException(
13943                    "clearPackagePersistentPreferredActivities can only be run by the system");
13944        }
13945        ArrayList<PersistentPreferredActivity> removed = null;
13946        boolean changed = false;
13947        synchronized (mPackages) {
13948            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13949                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13950                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13951                        .valueAt(i);
13952                if (userId != thisUserId) {
13953                    continue;
13954                }
13955                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13956                while (it.hasNext()) {
13957                    PersistentPreferredActivity ppa = it.next();
13958                    // Mark entry for removal only if it matches the package name.
13959                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13960                        if (removed == null) {
13961                            removed = new ArrayList<PersistentPreferredActivity>();
13962                        }
13963                        removed.add(ppa);
13964                    }
13965                }
13966                if (removed != null) {
13967                    for (int j=0; j<removed.size(); j++) {
13968                        PersistentPreferredActivity ppa = removed.get(j);
13969                        ppir.removeFilter(ppa);
13970                    }
13971                    changed = true;
13972                }
13973            }
13974
13975            if (changed) {
13976                scheduleWritePackageRestrictionsLocked(userId);
13977            }
13978        }
13979    }
13980
13981    /**
13982     * Common machinery for picking apart a restored XML blob and passing
13983     * it to a caller-supplied functor to be applied to the running system.
13984     */
13985    private void restoreFromXml(XmlPullParser parser, int userId,
13986            String expectedStartTag, BlobXmlRestorer functor)
13987            throws IOException, XmlPullParserException {
13988        int type;
13989        while ((type = parser.next()) != XmlPullParser.START_TAG
13990                && type != XmlPullParser.END_DOCUMENT) {
13991        }
13992        if (type != XmlPullParser.START_TAG) {
13993            // oops didn't find a start tag?!
13994            if (DEBUG_BACKUP) {
13995                Slog.e(TAG, "Didn't find start tag during restore");
13996            }
13997            return;
13998        }
13999
14000        // this is supposed to be TAG_PREFERRED_BACKUP
14001        if (!expectedStartTag.equals(parser.getName())) {
14002            if (DEBUG_BACKUP) {
14003                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14004            }
14005            return;
14006        }
14007
14008        // skip interfering stuff, then we're aligned with the backing implementation
14009        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14010        functor.apply(parser, userId);
14011    }
14012
14013    private interface BlobXmlRestorer {
14014        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14015    }
14016
14017    /**
14018     * Non-Binder method, support for the backup/restore mechanism: write the
14019     * full set of preferred activities in its canonical XML format.  Returns the
14020     * XML output as a byte array, or null if there is none.
14021     */
14022    @Override
14023    public byte[] getPreferredActivityBackup(int userId) {
14024        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14025            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14026        }
14027
14028        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14029        try {
14030            final XmlSerializer serializer = new FastXmlSerializer();
14031            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14032            serializer.startDocument(null, true);
14033            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14034
14035            synchronized (mPackages) {
14036                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14037            }
14038
14039            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14040            serializer.endDocument();
14041            serializer.flush();
14042        } catch (Exception e) {
14043            if (DEBUG_BACKUP) {
14044                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14045            }
14046            return null;
14047        }
14048
14049        return dataStream.toByteArray();
14050    }
14051
14052    @Override
14053    public void restorePreferredActivities(byte[] backup, int userId) {
14054        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14055            throw new SecurityException("Only the system may call restorePreferredActivities()");
14056        }
14057
14058        try {
14059            final XmlPullParser parser = Xml.newPullParser();
14060            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14061            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14062                    new BlobXmlRestorer() {
14063                        @Override
14064                        public void apply(XmlPullParser parser, int userId)
14065                                throws XmlPullParserException, IOException {
14066                            synchronized (mPackages) {
14067                                mSettings.readPreferredActivitiesLPw(parser, userId);
14068                            }
14069                        }
14070                    } );
14071        } catch (Exception e) {
14072            if (DEBUG_BACKUP) {
14073                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14074            }
14075        }
14076    }
14077
14078    /**
14079     * Non-Binder method, support for the backup/restore mechanism: write the
14080     * default browser (etc) settings in its canonical XML format.  Returns the default
14081     * browser XML representation as a byte array, or null if there is none.
14082     */
14083    @Override
14084    public byte[] getDefaultAppsBackup(int userId) {
14085        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14086            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14087        }
14088
14089        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14090        try {
14091            final XmlSerializer serializer = new FastXmlSerializer();
14092            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14093            serializer.startDocument(null, true);
14094            serializer.startTag(null, TAG_DEFAULT_APPS);
14095
14096            synchronized (mPackages) {
14097                mSettings.writeDefaultAppsLPr(serializer, userId);
14098            }
14099
14100            serializer.endTag(null, TAG_DEFAULT_APPS);
14101            serializer.endDocument();
14102            serializer.flush();
14103        } catch (Exception e) {
14104            if (DEBUG_BACKUP) {
14105                Slog.e(TAG, "Unable to write default apps for backup", e);
14106            }
14107            return null;
14108        }
14109
14110        return dataStream.toByteArray();
14111    }
14112
14113    @Override
14114    public void restoreDefaultApps(byte[] backup, int userId) {
14115        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14116            throw new SecurityException("Only the system may call restoreDefaultApps()");
14117        }
14118
14119        try {
14120            final XmlPullParser parser = Xml.newPullParser();
14121            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14122            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14123                    new BlobXmlRestorer() {
14124                        @Override
14125                        public void apply(XmlPullParser parser, int userId)
14126                                throws XmlPullParserException, IOException {
14127                            synchronized (mPackages) {
14128                                mSettings.readDefaultAppsLPw(parser, userId);
14129                            }
14130                        }
14131                    } );
14132        } catch (Exception e) {
14133            if (DEBUG_BACKUP) {
14134                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14135            }
14136        }
14137    }
14138
14139    @Override
14140    public byte[] getIntentFilterVerificationBackup(int userId) {
14141        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14142            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14143        }
14144
14145        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14146        try {
14147            final XmlSerializer serializer = new FastXmlSerializer();
14148            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14149            serializer.startDocument(null, true);
14150            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14151
14152            synchronized (mPackages) {
14153                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14154            }
14155
14156            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14157            serializer.endDocument();
14158            serializer.flush();
14159        } catch (Exception e) {
14160            if (DEBUG_BACKUP) {
14161                Slog.e(TAG, "Unable to write default apps for backup", e);
14162            }
14163            return null;
14164        }
14165
14166        return dataStream.toByteArray();
14167    }
14168
14169    @Override
14170    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14171        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14172            throw new SecurityException("Only the system may call restorePreferredActivities()");
14173        }
14174
14175        try {
14176            final XmlPullParser parser = Xml.newPullParser();
14177            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14178            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14179                    new BlobXmlRestorer() {
14180                        @Override
14181                        public void apply(XmlPullParser parser, int userId)
14182                                throws XmlPullParserException, IOException {
14183                            synchronized (mPackages) {
14184                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14185                                mSettings.writeLPr();
14186                            }
14187                        }
14188                    } );
14189        } catch (Exception e) {
14190            if (DEBUG_BACKUP) {
14191                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14192            }
14193        }
14194    }
14195
14196    @Override
14197    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14198            int sourceUserId, int targetUserId, int flags) {
14199        mContext.enforceCallingOrSelfPermission(
14200                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14201        int callingUid = Binder.getCallingUid();
14202        enforceOwnerRights(ownerPackage, callingUid);
14203        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14204        if (intentFilter.countActions() == 0) {
14205            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14206            return;
14207        }
14208        synchronized (mPackages) {
14209            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14210                    ownerPackage, targetUserId, flags);
14211            CrossProfileIntentResolver resolver =
14212                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14213            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14214            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14215            if (existing != null) {
14216                int size = existing.size();
14217                for (int i = 0; i < size; i++) {
14218                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14219                        return;
14220                    }
14221                }
14222            }
14223            resolver.addFilter(newFilter);
14224            scheduleWritePackageRestrictionsLocked(sourceUserId);
14225        }
14226    }
14227
14228    @Override
14229    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14230        mContext.enforceCallingOrSelfPermission(
14231                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14232        int callingUid = Binder.getCallingUid();
14233        enforceOwnerRights(ownerPackage, callingUid);
14234        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14235        synchronized (mPackages) {
14236            CrossProfileIntentResolver resolver =
14237                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14238            ArraySet<CrossProfileIntentFilter> set =
14239                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14240            for (CrossProfileIntentFilter filter : set) {
14241                if (filter.getOwnerPackage().equals(ownerPackage)) {
14242                    resolver.removeFilter(filter);
14243                }
14244            }
14245            scheduleWritePackageRestrictionsLocked(sourceUserId);
14246        }
14247    }
14248
14249    // Enforcing that callingUid is owning pkg on userId
14250    private void enforceOwnerRights(String pkg, int callingUid) {
14251        // The system owns everything.
14252        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14253            return;
14254        }
14255        int callingUserId = UserHandle.getUserId(callingUid);
14256        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14257        if (pi == null) {
14258            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14259                    + callingUserId);
14260        }
14261        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14262            throw new SecurityException("Calling uid " + callingUid
14263                    + " does not own package " + pkg);
14264        }
14265    }
14266
14267    @Override
14268    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14269        Intent intent = new Intent(Intent.ACTION_MAIN);
14270        intent.addCategory(Intent.CATEGORY_HOME);
14271
14272        final int callingUserId = UserHandle.getCallingUserId();
14273        List<ResolveInfo> list = queryIntentActivities(intent, null,
14274                PackageManager.GET_META_DATA, callingUserId);
14275        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14276                true, false, false, callingUserId);
14277
14278        allHomeCandidates.clear();
14279        if (list != null) {
14280            for (ResolveInfo ri : list) {
14281                allHomeCandidates.add(ri);
14282            }
14283        }
14284        return (preferred == null || preferred.activityInfo == null)
14285                ? null
14286                : new ComponentName(preferred.activityInfo.packageName,
14287                        preferred.activityInfo.name);
14288    }
14289
14290    @Override
14291    public void setApplicationEnabledSetting(String appPackageName,
14292            int newState, int flags, int userId, String callingPackage) {
14293        if (!sUserManager.exists(userId)) return;
14294        if (callingPackage == null) {
14295            callingPackage = Integer.toString(Binder.getCallingUid());
14296        }
14297        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14298    }
14299
14300    @Override
14301    public void setComponentEnabledSetting(ComponentName componentName,
14302            int newState, int flags, int userId) {
14303        if (!sUserManager.exists(userId)) return;
14304        setEnabledSetting(componentName.getPackageName(),
14305                componentName.getClassName(), newState, flags, userId, null);
14306    }
14307
14308    private void setEnabledSetting(final String packageName, String className, int newState,
14309            final int flags, int userId, String callingPackage) {
14310        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14311              || newState == COMPONENT_ENABLED_STATE_ENABLED
14312              || newState == COMPONENT_ENABLED_STATE_DISABLED
14313              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14314              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14315            throw new IllegalArgumentException("Invalid new component state: "
14316                    + newState);
14317        }
14318        PackageSetting pkgSetting;
14319        final int uid = Binder.getCallingUid();
14320        final int permission = mContext.checkCallingOrSelfPermission(
14321                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14322        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14323        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14324        boolean sendNow = false;
14325        boolean isApp = (className == null);
14326        String componentName = isApp ? packageName : className;
14327        int packageUid = -1;
14328        ArrayList<String> components;
14329
14330        // writer
14331        synchronized (mPackages) {
14332            pkgSetting = mSettings.mPackages.get(packageName);
14333            if (pkgSetting == null) {
14334                if (className == null) {
14335                    throw new IllegalArgumentException(
14336                            "Unknown package: " + packageName);
14337                }
14338                throw new IllegalArgumentException(
14339                        "Unknown component: " + packageName
14340                        + "/" + className);
14341            }
14342            // Allow root and verify that userId is not being specified by a different user
14343            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14344                throw new SecurityException(
14345                        "Permission Denial: attempt to change component state from pid="
14346                        + Binder.getCallingPid()
14347                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14348            }
14349            if (className == null) {
14350                // We're dealing with an application/package level state change
14351                if (pkgSetting.getEnabled(userId) == newState) {
14352                    // Nothing to do
14353                    return;
14354                }
14355                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14356                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14357                    // Don't care about who enables an app.
14358                    callingPackage = null;
14359                }
14360                pkgSetting.setEnabled(newState, userId, callingPackage);
14361                // pkgSetting.pkg.mSetEnabled = newState;
14362            } else {
14363                // We're dealing with a component level state change
14364                // First, verify that this is a valid class name.
14365                PackageParser.Package pkg = pkgSetting.pkg;
14366                if (pkg == null || !pkg.hasComponentClassName(className)) {
14367                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14368                        throw new IllegalArgumentException("Component class " + className
14369                                + " does not exist in " + packageName);
14370                    } else {
14371                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14372                                + className + " does not exist in " + packageName);
14373                    }
14374                }
14375                switch (newState) {
14376                case COMPONENT_ENABLED_STATE_ENABLED:
14377                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14378                        return;
14379                    }
14380                    break;
14381                case COMPONENT_ENABLED_STATE_DISABLED:
14382                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14383                        return;
14384                    }
14385                    break;
14386                case COMPONENT_ENABLED_STATE_DEFAULT:
14387                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14388                        return;
14389                    }
14390                    break;
14391                default:
14392                    Slog.e(TAG, "Invalid new component state: " + newState);
14393                    return;
14394                }
14395            }
14396            scheduleWritePackageRestrictionsLocked(userId);
14397            components = mPendingBroadcasts.get(userId, packageName);
14398            final boolean newPackage = components == null;
14399            if (newPackage) {
14400                components = new ArrayList<String>();
14401            }
14402            if (!components.contains(componentName)) {
14403                components.add(componentName);
14404            }
14405            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14406                sendNow = true;
14407                // Purge entry from pending broadcast list if another one exists already
14408                // since we are sending one right away.
14409                mPendingBroadcasts.remove(userId, packageName);
14410            } else {
14411                if (newPackage) {
14412                    mPendingBroadcasts.put(userId, packageName, components);
14413                }
14414                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14415                    // Schedule a message
14416                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14417                }
14418            }
14419        }
14420
14421        long callingId = Binder.clearCallingIdentity();
14422        try {
14423            if (sendNow) {
14424                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14425                sendPackageChangedBroadcast(packageName,
14426                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14427            }
14428        } finally {
14429            Binder.restoreCallingIdentity(callingId);
14430        }
14431    }
14432
14433    private void sendPackageChangedBroadcast(String packageName,
14434            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14435        if (DEBUG_INSTALL)
14436            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14437                    + componentNames);
14438        Bundle extras = new Bundle(4);
14439        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14440        String nameList[] = new String[componentNames.size()];
14441        componentNames.toArray(nameList);
14442        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14443        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14444        extras.putInt(Intent.EXTRA_UID, packageUid);
14445        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14446                new int[] {UserHandle.getUserId(packageUid)});
14447    }
14448
14449    @Override
14450    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14451        if (!sUserManager.exists(userId)) return;
14452        final int uid = Binder.getCallingUid();
14453        final int permission = mContext.checkCallingOrSelfPermission(
14454                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14455        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14456        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14457        // writer
14458        synchronized (mPackages) {
14459            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14460                    allowedByPermission, uid, userId)) {
14461                scheduleWritePackageRestrictionsLocked(userId);
14462            }
14463        }
14464    }
14465
14466    @Override
14467    public String getInstallerPackageName(String packageName) {
14468        // reader
14469        synchronized (mPackages) {
14470            return mSettings.getInstallerPackageNameLPr(packageName);
14471        }
14472    }
14473
14474    @Override
14475    public int getApplicationEnabledSetting(String packageName, int userId) {
14476        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14477        int uid = Binder.getCallingUid();
14478        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14479        // reader
14480        synchronized (mPackages) {
14481            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14482        }
14483    }
14484
14485    @Override
14486    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14487        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14488        int uid = Binder.getCallingUid();
14489        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14490        // reader
14491        synchronized (mPackages) {
14492            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14493        }
14494    }
14495
14496    @Override
14497    public void enterSafeMode() {
14498        enforceSystemOrRoot("Only the system can request entering safe mode");
14499
14500        if (!mSystemReady) {
14501            mSafeMode = true;
14502        }
14503    }
14504
14505    @Override
14506    public void systemReady() {
14507        mSystemReady = true;
14508
14509        // Read the compatibilty setting when the system is ready.
14510        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14511                mContext.getContentResolver(),
14512                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14513        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14514        if (DEBUG_SETTINGS) {
14515            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14516        }
14517
14518        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14519
14520        synchronized (mPackages) {
14521            // Verify that all of the preferred activity components actually
14522            // exist.  It is possible for applications to be updated and at
14523            // that point remove a previously declared activity component that
14524            // had been set as a preferred activity.  We try to clean this up
14525            // the next time we encounter that preferred activity, but it is
14526            // possible for the user flow to never be able to return to that
14527            // situation so here we do a sanity check to make sure we haven't
14528            // left any junk around.
14529            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14530            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14531                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14532                removed.clear();
14533                for (PreferredActivity pa : pir.filterSet()) {
14534                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14535                        removed.add(pa);
14536                    }
14537                }
14538                if (removed.size() > 0) {
14539                    for (int r=0; r<removed.size(); r++) {
14540                        PreferredActivity pa = removed.get(r);
14541                        Slog.w(TAG, "Removing dangling preferred activity: "
14542                                + pa.mPref.mComponent);
14543                        pir.removeFilter(pa);
14544                    }
14545                    mSettings.writePackageRestrictionsLPr(
14546                            mSettings.mPreferredActivities.keyAt(i));
14547                }
14548            }
14549
14550            for (int userId : UserManagerService.getInstance().getUserIds()) {
14551                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14552                    grantPermissionsUserIds = ArrayUtils.appendInt(
14553                            grantPermissionsUserIds, userId);
14554                }
14555            }
14556        }
14557        sUserManager.systemReady();
14558
14559        // If we upgraded grant all default permissions before kicking off.
14560        for (int userId : grantPermissionsUserIds) {
14561            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14562        }
14563
14564        // Kick off any messages waiting for system ready
14565        if (mPostSystemReadyMessages != null) {
14566            for (Message msg : mPostSystemReadyMessages) {
14567                msg.sendToTarget();
14568            }
14569            mPostSystemReadyMessages = null;
14570        }
14571
14572        // Watch for external volumes that come and go over time
14573        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14574        storage.registerListener(mStorageListener);
14575
14576        mInstallerService.systemReady();
14577        mPackageDexOptimizer.systemReady();
14578
14579        MountServiceInternal mountServiceInternal = LocalServices.getService(
14580                MountServiceInternal.class);
14581        mountServiceInternal.addExternalStoragePolicy(
14582                new MountServiceInternal.ExternalStorageMountPolicy() {
14583            @Override
14584            public int getMountMode(int uid, String packageName) {
14585                if (Process.isIsolated(uid)) {
14586                    return Zygote.MOUNT_EXTERNAL_NONE;
14587                }
14588                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
14589                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14590                }
14591                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14592                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14593                }
14594                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14595                    return Zygote.MOUNT_EXTERNAL_READ;
14596                }
14597                return Zygote.MOUNT_EXTERNAL_WRITE;
14598            }
14599
14600            @Override
14601            public boolean hasExternalStorage(int uid, String packageName) {
14602                return true;
14603            }
14604        });
14605    }
14606
14607    @Override
14608    public boolean isSafeMode() {
14609        return mSafeMode;
14610    }
14611
14612    @Override
14613    public boolean hasSystemUidErrors() {
14614        return mHasSystemUidErrors;
14615    }
14616
14617    static String arrayToString(int[] array) {
14618        StringBuffer buf = new StringBuffer(128);
14619        buf.append('[');
14620        if (array != null) {
14621            for (int i=0; i<array.length; i++) {
14622                if (i > 0) buf.append(", ");
14623                buf.append(array[i]);
14624            }
14625        }
14626        buf.append(']');
14627        return buf.toString();
14628    }
14629
14630    static class DumpState {
14631        public static final int DUMP_LIBS = 1 << 0;
14632        public static final int DUMP_FEATURES = 1 << 1;
14633        public static final int DUMP_RESOLVERS = 1 << 2;
14634        public static final int DUMP_PERMISSIONS = 1 << 3;
14635        public static final int DUMP_PACKAGES = 1 << 4;
14636        public static final int DUMP_SHARED_USERS = 1 << 5;
14637        public static final int DUMP_MESSAGES = 1 << 6;
14638        public static final int DUMP_PROVIDERS = 1 << 7;
14639        public static final int DUMP_VERIFIERS = 1 << 8;
14640        public static final int DUMP_PREFERRED = 1 << 9;
14641        public static final int DUMP_PREFERRED_XML = 1 << 10;
14642        public static final int DUMP_KEYSETS = 1 << 11;
14643        public static final int DUMP_VERSION = 1 << 12;
14644        public static final int DUMP_INSTALLS = 1 << 13;
14645        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14646        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14647
14648        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14649
14650        private int mTypes;
14651
14652        private int mOptions;
14653
14654        private boolean mTitlePrinted;
14655
14656        private SharedUserSetting mSharedUser;
14657
14658        public boolean isDumping(int type) {
14659            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14660                return true;
14661            }
14662
14663            return (mTypes & type) != 0;
14664        }
14665
14666        public void setDump(int type) {
14667            mTypes |= type;
14668        }
14669
14670        public boolean isOptionEnabled(int option) {
14671            return (mOptions & option) != 0;
14672        }
14673
14674        public void setOptionEnabled(int option) {
14675            mOptions |= option;
14676        }
14677
14678        public boolean onTitlePrinted() {
14679            final boolean printed = mTitlePrinted;
14680            mTitlePrinted = true;
14681            return printed;
14682        }
14683
14684        public boolean getTitlePrinted() {
14685            return mTitlePrinted;
14686        }
14687
14688        public void setTitlePrinted(boolean enabled) {
14689            mTitlePrinted = enabled;
14690        }
14691
14692        public SharedUserSetting getSharedUser() {
14693            return mSharedUser;
14694        }
14695
14696        public void setSharedUser(SharedUserSetting user) {
14697            mSharedUser = user;
14698        }
14699    }
14700
14701    @Override
14702    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14703        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14704                != PackageManager.PERMISSION_GRANTED) {
14705            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14706                    + Binder.getCallingPid()
14707                    + ", uid=" + Binder.getCallingUid()
14708                    + " without permission "
14709                    + android.Manifest.permission.DUMP);
14710            return;
14711        }
14712
14713        DumpState dumpState = new DumpState();
14714        boolean fullPreferred = false;
14715        boolean checkin = false;
14716
14717        String packageName = null;
14718        ArraySet<String> permissionNames = null;
14719
14720        int opti = 0;
14721        while (opti < args.length) {
14722            String opt = args[opti];
14723            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14724                break;
14725            }
14726            opti++;
14727
14728            if ("-a".equals(opt)) {
14729                // Right now we only know how to print all.
14730            } else if ("-h".equals(opt)) {
14731                pw.println("Package manager dump options:");
14732                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14733                pw.println("    --checkin: dump for a checkin");
14734                pw.println("    -f: print details of intent filters");
14735                pw.println("    -h: print this help");
14736                pw.println("  cmd may be one of:");
14737                pw.println("    l[ibraries]: list known shared libraries");
14738                pw.println("    f[ibraries]: list device features");
14739                pw.println("    k[eysets]: print known keysets");
14740                pw.println("    r[esolvers]: dump intent resolvers");
14741                pw.println("    perm[issions]: dump permissions");
14742                pw.println("    permission [name ...]: dump declaration and use of given permission");
14743                pw.println("    pref[erred]: print preferred package settings");
14744                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14745                pw.println("    prov[iders]: dump content providers");
14746                pw.println("    p[ackages]: dump installed packages");
14747                pw.println("    s[hared-users]: dump shared user IDs");
14748                pw.println("    m[essages]: print collected runtime messages");
14749                pw.println("    v[erifiers]: print package verifier info");
14750                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14751                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14752                pw.println("    version: print database version info");
14753                pw.println("    write: write current settings now");
14754                pw.println("    installs: details about install sessions");
14755                pw.println("    <package.name>: info about given package");
14756                return;
14757            } else if ("--checkin".equals(opt)) {
14758                checkin = true;
14759            } else if ("-f".equals(opt)) {
14760                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14761            } else {
14762                pw.println("Unknown argument: " + opt + "; use -h for help");
14763            }
14764        }
14765
14766        // Is the caller requesting to dump a particular piece of data?
14767        if (opti < args.length) {
14768            String cmd = args[opti];
14769            opti++;
14770            // Is this a package name?
14771            if ("android".equals(cmd) || cmd.contains(".")) {
14772                packageName = cmd;
14773                // When dumping a single package, we always dump all of its
14774                // filter information since the amount of data will be reasonable.
14775                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14776            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14777                dumpState.setDump(DumpState.DUMP_LIBS);
14778            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14779                dumpState.setDump(DumpState.DUMP_FEATURES);
14780            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14781                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14782            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14783                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14784            } else if ("permission".equals(cmd)) {
14785                if (opti >= args.length) {
14786                    pw.println("Error: permission requires permission name");
14787                    return;
14788                }
14789                permissionNames = new ArraySet<>();
14790                while (opti < args.length) {
14791                    permissionNames.add(args[opti]);
14792                    opti++;
14793                }
14794                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14795                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14796            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14797                dumpState.setDump(DumpState.DUMP_PREFERRED);
14798            } else if ("preferred-xml".equals(cmd)) {
14799                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14800                if (opti < args.length && "--full".equals(args[opti])) {
14801                    fullPreferred = true;
14802                    opti++;
14803                }
14804            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14805                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14806            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14807                dumpState.setDump(DumpState.DUMP_PACKAGES);
14808            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14809                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14810            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14811                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14812            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14813                dumpState.setDump(DumpState.DUMP_MESSAGES);
14814            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14815                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14816            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14817                    || "intent-filter-verifiers".equals(cmd)) {
14818                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14819            } else if ("version".equals(cmd)) {
14820                dumpState.setDump(DumpState.DUMP_VERSION);
14821            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14822                dumpState.setDump(DumpState.DUMP_KEYSETS);
14823            } else if ("installs".equals(cmd)) {
14824                dumpState.setDump(DumpState.DUMP_INSTALLS);
14825            } else if ("write".equals(cmd)) {
14826                synchronized (mPackages) {
14827                    mSettings.writeLPr();
14828                    pw.println("Settings written.");
14829                    return;
14830                }
14831            }
14832        }
14833
14834        if (checkin) {
14835            pw.println("vers,1");
14836        }
14837
14838        // reader
14839        synchronized (mPackages) {
14840            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14841                if (!checkin) {
14842                    if (dumpState.onTitlePrinted())
14843                        pw.println();
14844                    pw.println("Database versions:");
14845                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
14846                }
14847            }
14848
14849            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14850                if (!checkin) {
14851                    if (dumpState.onTitlePrinted())
14852                        pw.println();
14853                    pw.println("Verifiers:");
14854                    pw.print("  Required: ");
14855                    pw.print(mRequiredVerifierPackage);
14856                    pw.print(" (uid=");
14857                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14858                    pw.println(")");
14859                } else if (mRequiredVerifierPackage != null) {
14860                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14861                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14862                }
14863            }
14864
14865            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14866                    packageName == null) {
14867                if (mIntentFilterVerifierComponent != null) {
14868                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14869                    if (!checkin) {
14870                        if (dumpState.onTitlePrinted())
14871                            pw.println();
14872                        pw.println("Intent Filter Verifier:");
14873                        pw.print("  Using: ");
14874                        pw.print(verifierPackageName);
14875                        pw.print(" (uid=");
14876                        pw.print(getPackageUid(verifierPackageName, 0));
14877                        pw.println(")");
14878                    } else if (verifierPackageName != null) {
14879                        pw.print("ifv,"); pw.print(verifierPackageName);
14880                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14881                    }
14882                } else {
14883                    pw.println();
14884                    pw.println("No Intent Filter Verifier available!");
14885                }
14886            }
14887
14888            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14889                boolean printedHeader = false;
14890                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14891                while (it.hasNext()) {
14892                    String name = it.next();
14893                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14894                    if (!checkin) {
14895                        if (!printedHeader) {
14896                            if (dumpState.onTitlePrinted())
14897                                pw.println();
14898                            pw.println("Libraries:");
14899                            printedHeader = true;
14900                        }
14901                        pw.print("  ");
14902                    } else {
14903                        pw.print("lib,");
14904                    }
14905                    pw.print(name);
14906                    if (!checkin) {
14907                        pw.print(" -> ");
14908                    }
14909                    if (ent.path != null) {
14910                        if (!checkin) {
14911                            pw.print("(jar) ");
14912                            pw.print(ent.path);
14913                        } else {
14914                            pw.print(",jar,");
14915                            pw.print(ent.path);
14916                        }
14917                    } else {
14918                        if (!checkin) {
14919                            pw.print("(apk) ");
14920                            pw.print(ent.apk);
14921                        } else {
14922                            pw.print(",apk,");
14923                            pw.print(ent.apk);
14924                        }
14925                    }
14926                    pw.println();
14927                }
14928            }
14929
14930            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14931                if (dumpState.onTitlePrinted())
14932                    pw.println();
14933                if (!checkin) {
14934                    pw.println("Features:");
14935                }
14936                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14937                while (it.hasNext()) {
14938                    String name = it.next();
14939                    if (!checkin) {
14940                        pw.print("  ");
14941                    } else {
14942                        pw.print("feat,");
14943                    }
14944                    pw.println(name);
14945                }
14946            }
14947
14948            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14949                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14950                        : "Activity Resolver Table:", "  ", packageName,
14951                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14952                    dumpState.setTitlePrinted(true);
14953                }
14954                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14955                        : "Receiver Resolver Table:", "  ", packageName,
14956                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14957                    dumpState.setTitlePrinted(true);
14958                }
14959                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14960                        : "Service Resolver Table:", "  ", packageName,
14961                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14962                    dumpState.setTitlePrinted(true);
14963                }
14964                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14965                        : "Provider Resolver Table:", "  ", packageName,
14966                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14967                    dumpState.setTitlePrinted(true);
14968                }
14969            }
14970
14971            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14972                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14973                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14974                    int user = mSettings.mPreferredActivities.keyAt(i);
14975                    if (pir.dump(pw,
14976                            dumpState.getTitlePrinted()
14977                                ? "\nPreferred Activities User " + user + ":"
14978                                : "Preferred Activities User " + user + ":", "  ",
14979                            packageName, true, false)) {
14980                        dumpState.setTitlePrinted(true);
14981                    }
14982                }
14983            }
14984
14985            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14986                pw.flush();
14987                FileOutputStream fout = new FileOutputStream(fd);
14988                BufferedOutputStream str = new BufferedOutputStream(fout);
14989                XmlSerializer serializer = new FastXmlSerializer();
14990                try {
14991                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14992                    serializer.startDocument(null, true);
14993                    serializer.setFeature(
14994                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14995                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14996                    serializer.endDocument();
14997                    serializer.flush();
14998                } catch (IllegalArgumentException e) {
14999                    pw.println("Failed writing: " + e);
15000                } catch (IllegalStateException e) {
15001                    pw.println("Failed writing: " + e);
15002                } catch (IOException e) {
15003                    pw.println("Failed writing: " + e);
15004                }
15005            }
15006
15007            if (!checkin
15008                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15009                    && packageName == null) {
15010                pw.println();
15011                int count = mSettings.mPackages.size();
15012                if (count == 0) {
15013                    pw.println("No applications!");
15014                    pw.println();
15015                } else {
15016                    final String prefix = "  ";
15017                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15018                    if (allPackageSettings.size() == 0) {
15019                        pw.println("No domain preferred apps!");
15020                        pw.println();
15021                    } else {
15022                        pw.println("App verification status:");
15023                        pw.println();
15024                        count = 0;
15025                        for (PackageSetting ps : allPackageSettings) {
15026                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15027                            if (ivi == null || ivi.getPackageName() == null) continue;
15028                            pw.println(prefix + "Package: " + ivi.getPackageName());
15029                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15030                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15031                            pw.println();
15032                            count++;
15033                        }
15034                        if (count == 0) {
15035                            pw.println(prefix + "No app verification established.");
15036                            pw.println();
15037                        }
15038                        for (int userId : sUserManager.getUserIds()) {
15039                            pw.println("App linkages for user " + userId + ":");
15040                            pw.println();
15041                            count = 0;
15042                            for (PackageSetting ps : allPackageSettings) {
15043                                final long status = ps.getDomainVerificationStatusForUser(userId);
15044                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15045                                    continue;
15046                                }
15047                                pw.println(prefix + "Package: " + ps.name);
15048                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15049                                String statusStr = IntentFilterVerificationInfo.
15050                                        getStatusStringFromValue(status);
15051                                pw.println(prefix + "Status:  " + statusStr);
15052                                pw.println();
15053                                count++;
15054                            }
15055                            if (count == 0) {
15056                                pw.println(prefix + "No configured app linkages.");
15057                                pw.println();
15058                            }
15059                        }
15060                    }
15061                }
15062            }
15063
15064            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15065                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15066                if (packageName == null && permissionNames == null) {
15067                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15068                        if (iperm == 0) {
15069                            if (dumpState.onTitlePrinted())
15070                                pw.println();
15071                            pw.println("AppOp Permissions:");
15072                        }
15073                        pw.print("  AppOp Permission ");
15074                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15075                        pw.println(":");
15076                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15077                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15078                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15079                        }
15080                    }
15081                }
15082            }
15083
15084            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15085                boolean printedSomething = false;
15086                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15087                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15088                        continue;
15089                    }
15090                    if (!printedSomething) {
15091                        if (dumpState.onTitlePrinted())
15092                            pw.println();
15093                        pw.println("Registered ContentProviders:");
15094                        printedSomething = true;
15095                    }
15096                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15097                    pw.print("    "); pw.println(p.toString());
15098                }
15099                printedSomething = false;
15100                for (Map.Entry<String, PackageParser.Provider> entry :
15101                        mProvidersByAuthority.entrySet()) {
15102                    PackageParser.Provider p = entry.getValue();
15103                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15104                        continue;
15105                    }
15106                    if (!printedSomething) {
15107                        if (dumpState.onTitlePrinted())
15108                            pw.println();
15109                        pw.println("ContentProvider Authorities:");
15110                        printedSomething = true;
15111                    }
15112                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15113                    pw.print("    "); pw.println(p.toString());
15114                    if (p.info != null && p.info.applicationInfo != null) {
15115                        final String appInfo = p.info.applicationInfo.toString();
15116                        pw.print("      applicationInfo="); pw.println(appInfo);
15117                    }
15118                }
15119            }
15120
15121            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15122                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15123            }
15124
15125            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15126                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15127            }
15128
15129            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15130                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15131            }
15132
15133            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15134                // XXX should handle packageName != null by dumping only install data that
15135                // the given package is involved with.
15136                if (dumpState.onTitlePrinted()) pw.println();
15137                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15138            }
15139
15140            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15141                if (dumpState.onTitlePrinted()) pw.println();
15142                mSettings.dumpReadMessagesLPr(pw, dumpState);
15143
15144                pw.println();
15145                pw.println("Package warning messages:");
15146                BufferedReader in = null;
15147                String line = null;
15148                try {
15149                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15150                    while ((line = in.readLine()) != null) {
15151                        if (line.contains("ignored: updated version")) continue;
15152                        pw.println(line);
15153                    }
15154                } catch (IOException ignored) {
15155                } finally {
15156                    IoUtils.closeQuietly(in);
15157                }
15158            }
15159
15160            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15161                BufferedReader in = null;
15162                String line = null;
15163                try {
15164                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15165                    while ((line = in.readLine()) != null) {
15166                        if (line.contains("ignored: updated version")) continue;
15167                        pw.print("msg,");
15168                        pw.println(line);
15169                    }
15170                } catch (IOException ignored) {
15171                } finally {
15172                    IoUtils.closeQuietly(in);
15173                }
15174            }
15175        }
15176    }
15177
15178    private String dumpDomainString(String packageName) {
15179        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15180        List<IntentFilter> filters = getAllIntentFilters(packageName);
15181
15182        ArraySet<String> result = new ArraySet<>();
15183        if (iviList.size() > 0) {
15184            for (IntentFilterVerificationInfo ivi : iviList) {
15185                for (String host : ivi.getDomains()) {
15186                    result.add(host);
15187                }
15188            }
15189        }
15190        if (filters != null && filters.size() > 0) {
15191            for (IntentFilter filter : filters) {
15192                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
15193                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15194                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
15195                    result.addAll(filter.getHostsList());
15196                }
15197            }
15198        }
15199
15200        StringBuilder sb = new StringBuilder(result.size() * 16);
15201        for (String domain : result) {
15202            if (sb.length() > 0) sb.append(" ");
15203            sb.append(domain);
15204        }
15205        return sb.toString();
15206    }
15207
15208    // ------- apps on sdcard specific code -------
15209    static final boolean DEBUG_SD_INSTALL = false;
15210
15211    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15212
15213    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15214
15215    private boolean mMediaMounted = false;
15216
15217    static String getEncryptKey() {
15218        try {
15219            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15220                    SD_ENCRYPTION_KEYSTORE_NAME);
15221            if (sdEncKey == null) {
15222                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15223                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15224                if (sdEncKey == null) {
15225                    Slog.e(TAG, "Failed to create encryption keys");
15226                    return null;
15227                }
15228            }
15229            return sdEncKey;
15230        } catch (NoSuchAlgorithmException nsae) {
15231            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15232            return null;
15233        } catch (IOException ioe) {
15234            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15235            return null;
15236        }
15237    }
15238
15239    /*
15240     * Update media status on PackageManager.
15241     */
15242    @Override
15243    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15244        int callingUid = Binder.getCallingUid();
15245        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15246            throw new SecurityException("Media status can only be updated by the system");
15247        }
15248        // reader; this apparently protects mMediaMounted, but should probably
15249        // be a different lock in that case.
15250        synchronized (mPackages) {
15251            Log.i(TAG, "Updating external media status from "
15252                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15253                    + (mediaStatus ? "mounted" : "unmounted"));
15254            if (DEBUG_SD_INSTALL)
15255                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15256                        + ", mMediaMounted=" + mMediaMounted);
15257            if (mediaStatus == mMediaMounted) {
15258                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15259                        : 0, -1);
15260                mHandler.sendMessage(msg);
15261                return;
15262            }
15263            mMediaMounted = mediaStatus;
15264        }
15265        // Queue up an async operation since the package installation may take a
15266        // little while.
15267        mHandler.post(new Runnable() {
15268            public void run() {
15269                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15270            }
15271        });
15272    }
15273
15274    /**
15275     * Called by MountService when the initial ASECs to scan are available.
15276     * Should block until all the ASEC containers are finished being scanned.
15277     */
15278    public void scanAvailableAsecs() {
15279        updateExternalMediaStatusInner(true, false, false);
15280        if (mShouldRestoreconData) {
15281            SELinuxMMAC.setRestoreconDone();
15282            mShouldRestoreconData = false;
15283        }
15284    }
15285
15286    /*
15287     * Collect information of applications on external media, map them against
15288     * existing containers and update information based on current mount status.
15289     * Please note that we always have to report status if reportStatus has been
15290     * set to true especially when unloading packages.
15291     */
15292    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15293            boolean externalStorage) {
15294        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15295        int[] uidArr = EmptyArray.INT;
15296
15297        final String[] list = PackageHelper.getSecureContainerList();
15298        if (ArrayUtils.isEmpty(list)) {
15299            Log.i(TAG, "No secure containers found");
15300        } else {
15301            // Process list of secure containers and categorize them
15302            // as active or stale based on their package internal state.
15303
15304            // reader
15305            synchronized (mPackages) {
15306                for (String cid : list) {
15307                    // Leave stages untouched for now; installer service owns them
15308                    if (PackageInstallerService.isStageName(cid)) continue;
15309
15310                    if (DEBUG_SD_INSTALL)
15311                        Log.i(TAG, "Processing container " + cid);
15312                    String pkgName = getAsecPackageName(cid);
15313                    if (pkgName == null) {
15314                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15315                        continue;
15316                    }
15317                    if (DEBUG_SD_INSTALL)
15318                        Log.i(TAG, "Looking for pkg : " + pkgName);
15319
15320                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15321                    if (ps == null) {
15322                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15323                        continue;
15324                    }
15325
15326                    /*
15327                     * Skip packages that are not external if we're unmounting
15328                     * external storage.
15329                     */
15330                    if (externalStorage && !isMounted && !isExternal(ps)) {
15331                        continue;
15332                    }
15333
15334                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15335                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15336                    // The package status is changed only if the code path
15337                    // matches between settings and the container id.
15338                    if (ps.codePathString != null
15339                            && ps.codePathString.startsWith(args.getCodePath())) {
15340                        if (DEBUG_SD_INSTALL) {
15341                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15342                                    + " at code path: " + ps.codePathString);
15343                        }
15344
15345                        // We do have a valid package installed on sdcard
15346                        processCids.put(args, ps.codePathString);
15347                        final int uid = ps.appId;
15348                        if (uid != -1) {
15349                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15350                        }
15351                    } else {
15352                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15353                                + ps.codePathString);
15354                    }
15355                }
15356            }
15357
15358            Arrays.sort(uidArr);
15359        }
15360
15361        // Process packages with valid entries.
15362        if (isMounted) {
15363            if (DEBUG_SD_INSTALL)
15364                Log.i(TAG, "Loading packages");
15365            loadMediaPackages(processCids, uidArr);
15366            startCleaningPackages();
15367            mInstallerService.onSecureContainersAvailable();
15368        } else {
15369            if (DEBUG_SD_INSTALL)
15370                Log.i(TAG, "Unloading packages");
15371            unloadMediaPackages(processCids, uidArr, reportStatus);
15372        }
15373    }
15374
15375    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15376            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15377        final int size = infos.size();
15378        final String[] packageNames = new String[size];
15379        final int[] packageUids = new int[size];
15380        for (int i = 0; i < size; i++) {
15381            final ApplicationInfo info = infos.get(i);
15382            packageNames[i] = info.packageName;
15383            packageUids[i] = info.uid;
15384        }
15385        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15386                finishedReceiver);
15387    }
15388
15389    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15390            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15391        sendResourcesChangedBroadcast(mediaStatus, replacing,
15392                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15393    }
15394
15395    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15396            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15397        int size = pkgList.length;
15398        if (size > 0) {
15399            // Send broadcasts here
15400            Bundle extras = new Bundle();
15401            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15402            if (uidArr != null) {
15403                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15404            }
15405            if (replacing) {
15406                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15407            }
15408            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15409                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15410            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15411        }
15412    }
15413
15414   /*
15415     * Look at potentially valid container ids from processCids If package
15416     * information doesn't match the one on record or package scanning fails,
15417     * the cid is added to list of removeCids. We currently don't delete stale
15418     * containers.
15419     */
15420    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
15421        ArrayList<String> pkgList = new ArrayList<String>();
15422        Set<AsecInstallArgs> keys = processCids.keySet();
15423
15424        for (AsecInstallArgs args : keys) {
15425            String codePath = processCids.get(args);
15426            if (DEBUG_SD_INSTALL)
15427                Log.i(TAG, "Loading container : " + args.cid);
15428            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15429            try {
15430                // Make sure there are no container errors first.
15431                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15432                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15433                            + " when installing from sdcard");
15434                    continue;
15435                }
15436                // Check code path here.
15437                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15438                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15439                            + " does not match one in settings " + codePath);
15440                    continue;
15441                }
15442                // Parse package
15443                int parseFlags = mDefParseFlags;
15444                if (args.isExternalAsec()) {
15445                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15446                }
15447                if (args.isFwdLocked()) {
15448                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15449                }
15450
15451                synchronized (mInstallLock) {
15452                    PackageParser.Package pkg = null;
15453                    try {
15454                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15455                    } catch (PackageManagerException e) {
15456                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15457                    }
15458                    // Scan the package
15459                    if (pkg != null) {
15460                        /*
15461                         * TODO why is the lock being held? doPostInstall is
15462                         * called in other places without the lock. This needs
15463                         * to be straightened out.
15464                         */
15465                        // writer
15466                        synchronized (mPackages) {
15467                            retCode = PackageManager.INSTALL_SUCCEEDED;
15468                            pkgList.add(pkg.packageName);
15469                            // Post process args
15470                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15471                                    pkg.applicationInfo.uid);
15472                        }
15473                    } else {
15474                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15475                    }
15476                }
15477
15478            } finally {
15479                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15480                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15481                }
15482            }
15483        }
15484        // writer
15485        synchronized (mPackages) {
15486            // If the platform SDK has changed since the last time we booted,
15487            // we need to re-grant app permission to catch any new ones that
15488            // appear. This is really a hack, and means that apps can in some
15489            // cases get permissions that the user didn't initially explicitly
15490            // allow... it would be nice to have some better way to handle
15491            // this situation.
15492            final VersionInfo ver = mSettings.getExternalVersion();
15493
15494            int updateFlags = UPDATE_PERMISSIONS_ALL;
15495            if (ver.sdkVersion != mSdkVersion) {
15496                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15497                        + mSdkVersion + "; regranting permissions for external");
15498                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15499            }
15500            updatePermissionsLPw(null, null, updateFlags);
15501
15502            // Yay, everything is now upgraded
15503            ver.forceCurrent();
15504
15505            // can downgrade to reader
15506            // Persist settings
15507            mSettings.writeLPr();
15508        }
15509        // Send a broadcast to let everyone know we are done processing
15510        if (pkgList.size() > 0) {
15511            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15512        }
15513    }
15514
15515   /*
15516     * Utility method to unload a list of specified containers
15517     */
15518    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15519        // Just unmount all valid containers.
15520        for (AsecInstallArgs arg : cidArgs) {
15521            synchronized (mInstallLock) {
15522                arg.doPostDeleteLI(false);
15523           }
15524       }
15525   }
15526
15527    /*
15528     * Unload packages mounted on external media. This involves deleting package
15529     * data from internal structures, sending broadcasts about diabled packages,
15530     * gc'ing to free up references, unmounting all secure containers
15531     * corresponding to packages on external media, and posting a
15532     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15533     * that we always have to post this message if status has been requested no
15534     * matter what.
15535     */
15536    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15537            final boolean reportStatus) {
15538        if (DEBUG_SD_INSTALL)
15539            Log.i(TAG, "unloading media packages");
15540        ArrayList<String> pkgList = new ArrayList<String>();
15541        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15542        final Set<AsecInstallArgs> keys = processCids.keySet();
15543        for (AsecInstallArgs args : keys) {
15544            String pkgName = args.getPackageName();
15545            if (DEBUG_SD_INSTALL)
15546                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15547            // Delete package internally
15548            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15549            synchronized (mInstallLock) {
15550                boolean res = deletePackageLI(pkgName, null, false, null, null,
15551                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15552                if (res) {
15553                    pkgList.add(pkgName);
15554                } else {
15555                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15556                    failedList.add(args);
15557                }
15558            }
15559        }
15560
15561        // reader
15562        synchronized (mPackages) {
15563            // We didn't update the settings after removing each package;
15564            // write them now for all packages.
15565            mSettings.writeLPr();
15566        }
15567
15568        // We have to absolutely send UPDATED_MEDIA_STATUS only
15569        // after confirming that all the receivers processed the ordered
15570        // broadcast when packages get disabled, force a gc to clean things up.
15571        // and unload all the containers.
15572        if (pkgList.size() > 0) {
15573            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15574                    new IIntentReceiver.Stub() {
15575                public void performReceive(Intent intent, int resultCode, String data,
15576                        Bundle extras, boolean ordered, boolean sticky,
15577                        int sendingUser) throws RemoteException {
15578                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15579                            reportStatus ? 1 : 0, 1, keys);
15580                    mHandler.sendMessage(msg);
15581                }
15582            });
15583        } else {
15584            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15585                    keys);
15586            mHandler.sendMessage(msg);
15587        }
15588    }
15589
15590    private void loadPrivatePackages(VolumeInfo vol) {
15591        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15592        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15593        synchronized (mInstallLock) {
15594        synchronized (mPackages) {
15595            final VersionInfo ver = mSettings.findOrCreateVersion(vol.fsUuid);
15596            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15597            for (PackageSetting ps : packages) {
15598                final PackageParser.Package pkg;
15599                try {
15600                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15601                    loaded.add(pkg.applicationInfo);
15602                } catch (PackageManagerException e) {
15603                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15604                }
15605
15606                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
15607                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
15608                }
15609            }
15610
15611            int updateFlags = UPDATE_PERMISSIONS_ALL;
15612            if (ver.sdkVersion != mSdkVersion) {
15613                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15614                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
15615                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15616            }
15617            updatePermissionsLPw(null, null, updateFlags);
15618
15619            // Yay, everything is now upgraded
15620            ver.forceCurrent();
15621
15622            mSettings.writeLPr();
15623        }
15624        }
15625
15626        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15627        sendResourcesChangedBroadcast(true, false, loaded, null);
15628    }
15629
15630    private void unloadPrivatePackages(VolumeInfo vol) {
15631        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15632        synchronized (mInstallLock) {
15633        synchronized (mPackages) {
15634            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15635            for (PackageSetting ps : packages) {
15636                if (ps.pkg == null) continue;
15637
15638                final ApplicationInfo info = ps.pkg.applicationInfo;
15639                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15640                if (deletePackageLI(ps.name, null, false, null, null,
15641                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15642                    unloaded.add(info);
15643                } else {
15644                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15645                }
15646            }
15647
15648            mSettings.writeLPr();
15649        }
15650        }
15651
15652        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15653        sendResourcesChangedBroadcast(false, false, unloaded, null);
15654    }
15655
15656    /**
15657     * Examine all users present on given mounted volume, and destroy data
15658     * belonging to users that are no longer valid, or whose user ID has been
15659     * recycled.
15660     */
15661    private void reconcileUsers(String volumeUuid) {
15662        final File[] files = FileUtils
15663                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
15664        for (File file : files) {
15665            if (!file.isDirectory()) continue;
15666
15667            final int userId;
15668            final UserInfo info;
15669            try {
15670                userId = Integer.parseInt(file.getName());
15671                info = sUserManager.getUserInfo(userId);
15672            } catch (NumberFormatException e) {
15673                Slog.w(TAG, "Invalid user directory " + file);
15674                continue;
15675            }
15676
15677            boolean destroyUser = false;
15678            if (info == null) {
15679                logCriticalInfo(Log.WARN, "Destroying user directory " + file
15680                        + " because no matching user was found");
15681                destroyUser = true;
15682            } else {
15683                try {
15684                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
15685                } catch (IOException e) {
15686                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
15687                            + " because we failed to enforce serial number: " + e);
15688                    destroyUser = true;
15689                }
15690            }
15691
15692            if (destroyUser) {
15693                synchronized (mInstallLock) {
15694                    mInstaller.removeUserDataDirs(volumeUuid, userId);
15695                }
15696            }
15697        }
15698
15699        final UserManager um = mContext.getSystemService(UserManager.class);
15700        for (UserInfo user : um.getUsers()) {
15701            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
15702            if (userDir.exists()) continue;
15703
15704            try {
15705                UserManagerService.prepareUserDirectory(userDir);
15706                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
15707            } catch (IOException e) {
15708                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
15709            }
15710        }
15711    }
15712
15713    /**
15714     * Examine all apps present on given mounted volume, and destroy apps that
15715     * aren't expected, either due to uninstallation or reinstallation on
15716     * another volume.
15717     */
15718    private void reconcileApps(String volumeUuid) {
15719        final File[] files = FileUtils
15720                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
15721        for (File file : files) {
15722            final boolean isPackage = (isApkFile(file) || file.isDirectory())
15723                    && !PackageInstallerService.isStageName(file.getName());
15724            if (!isPackage) {
15725                // Ignore entries which are not packages
15726                continue;
15727            }
15728
15729            boolean destroyApp = false;
15730            String packageName = null;
15731            try {
15732                final PackageLite pkg = PackageParser.parsePackageLite(file,
15733                        PackageParser.PARSE_MUST_BE_APK);
15734                packageName = pkg.packageName;
15735
15736                synchronized (mPackages) {
15737                    final PackageSetting ps = mSettings.mPackages.get(packageName);
15738                    if (ps == null) {
15739                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
15740                                + volumeUuid + " because we found no install record");
15741                        destroyApp = true;
15742                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
15743                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
15744                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
15745                        destroyApp = true;
15746                    }
15747                }
15748
15749            } catch (PackageParserException e) {
15750                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
15751                destroyApp = true;
15752            }
15753
15754            if (destroyApp) {
15755                synchronized (mInstallLock) {
15756                    if (packageName != null) {
15757                        removeDataDirsLI(volumeUuid, packageName);
15758                    }
15759                    if (file.isDirectory()) {
15760                        mInstaller.rmPackageDir(file.getAbsolutePath());
15761                    } else {
15762                        file.delete();
15763                    }
15764                }
15765            }
15766        }
15767    }
15768
15769    private void unfreezePackage(String packageName) {
15770        synchronized (mPackages) {
15771            final PackageSetting ps = mSettings.mPackages.get(packageName);
15772            if (ps != null) {
15773                ps.frozen = false;
15774            }
15775        }
15776    }
15777
15778    @Override
15779    public int movePackage(final String packageName, final String volumeUuid) {
15780        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15781
15782        final int moveId = mNextMoveId.getAndIncrement();
15783        try {
15784            movePackageInternal(packageName, volumeUuid, moveId);
15785        } catch (PackageManagerException e) {
15786            Slog.w(TAG, "Failed to move " + packageName, e);
15787            mMoveCallbacks.notifyStatusChanged(moveId,
15788                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15789        }
15790        return moveId;
15791    }
15792
15793    private void movePackageInternal(final String packageName, final String volumeUuid,
15794            final int moveId) throws PackageManagerException {
15795        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15796        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15797        final PackageManager pm = mContext.getPackageManager();
15798
15799        final boolean currentAsec;
15800        final String currentVolumeUuid;
15801        final File codeFile;
15802        final String installerPackageName;
15803        final String packageAbiOverride;
15804        final int appId;
15805        final String seinfo;
15806        final String label;
15807
15808        // reader
15809        synchronized (mPackages) {
15810            final PackageParser.Package pkg = mPackages.get(packageName);
15811            final PackageSetting ps = mSettings.mPackages.get(packageName);
15812            if (pkg == null || ps == null) {
15813                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15814            }
15815
15816            if (pkg.applicationInfo.isSystemApp()) {
15817                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15818                        "Cannot move system application");
15819            }
15820
15821            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
15822                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15823                        "Package already moved to " + volumeUuid);
15824            }
15825
15826            final File probe = new File(pkg.codePath);
15827            final File probeOat = new File(probe, "oat");
15828            if (!probe.isDirectory() || !probeOat.isDirectory()) {
15829                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15830                        "Move only supported for modern cluster style installs");
15831            }
15832
15833            if (ps.frozen) {
15834                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15835                        "Failed to move already frozen package");
15836            }
15837            ps.frozen = true;
15838
15839            currentAsec = pkg.applicationInfo.isForwardLocked()
15840                    || pkg.applicationInfo.isExternalAsec();
15841            currentVolumeUuid = ps.volumeUuid;
15842            codeFile = new File(pkg.codePath);
15843            installerPackageName = ps.installerPackageName;
15844            packageAbiOverride = ps.cpuAbiOverrideString;
15845            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15846            seinfo = pkg.applicationInfo.seinfo;
15847            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15848        }
15849
15850        // Now that we're guarded by frozen state, kill app during move
15851        final long token = Binder.clearCallingIdentity();
15852        try {
15853            killApplication(packageName, appId, "move pkg");
15854        } finally {
15855            Binder.restoreCallingIdentity(token);
15856        }
15857
15858        final Bundle extras = new Bundle();
15859        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15860        extras.putString(Intent.EXTRA_TITLE, label);
15861        mMoveCallbacks.notifyCreated(moveId, extras);
15862
15863        int installFlags;
15864        final boolean moveCompleteApp;
15865        final File measurePath;
15866
15867        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
15868            installFlags = INSTALL_INTERNAL;
15869            moveCompleteApp = !currentAsec;
15870            measurePath = Environment.getDataAppDirectory(volumeUuid);
15871        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
15872            installFlags = INSTALL_EXTERNAL;
15873            moveCompleteApp = false;
15874            measurePath = storage.getPrimaryPhysicalVolume().getPath();
15875        } else {
15876            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15877            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15878                    || !volume.isMountedWritable()) {
15879                unfreezePackage(packageName);
15880                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15881                        "Move location not mounted private volume");
15882            }
15883
15884            Preconditions.checkState(!currentAsec);
15885
15886            installFlags = INSTALL_INTERNAL;
15887            moveCompleteApp = true;
15888            measurePath = Environment.getDataAppDirectory(volumeUuid);
15889        }
15890
15891        final PackageStats stats = new PackageStats(null, -1);
15892        synchronized (mInstaller) {
15893            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15894                unfreezePackage(packageName);
15895                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15896                        "Failed to measure package size");
15897            }
15898        }
15899
15900        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
15901                + stats.dataSize);
15902
15903        final long startFreeBytes = measurePath.getFreeSpace();
15904        final long sizeBytes;
15905        if (moveCompleteApp) {
15906            sizeBytes = stats.codeSize + stats.dataSize;
15907        } else {
15908            sizeBytes = stats.codeSize;
15909        }
15910
15911        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
15912            unfreezePackage(packageName);
15913            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15914                    "Not enough free space to move");
15915        }
15916
15917        mMoveCallbacks.notifyStatusChanged(moveId, 10);
15918
15919        final CountDownLatch installedLatch = new CountDownLatch(1);
15920        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
15921            @Override
15922            public void onUserActionRequired(Intent intent) throws RemoteException {
15923                throw new IllegalStateException();
15924            }
15925
15926            @Override
15927            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
15928                    Bundle extras) throws RemoteException {
15929                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
15930                        + PackageManager.installStatusToString(returnCode, msg));
15931
15932                installedLatch.countDown();
15933
15934                // Regardless of success or failure of the move operation,
15935                // always unfreeze the package
15936                unfreezePackage(packageName);
15937
15938                final int status = PackageManager.installStatusToPublicStatus(returnCode);
15939                switch (status) {
15940                    case PackageInstaller.STATUS_SUCCESS:
15941                        mMoveCallbacks.notifyStatusChanged(moveId,
15942                                PackageManager.MOVE_SUCCEEDED);
15943                        break;
15944                    case PackageInstaller.STATUS_FAILURE_STORAGE:
15945                        mMoveCallbacks.notifyStatusChanged(moveId,
15946                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
15947                        break;
15948                    default:
15949                        mMoveCallbacks.notifyStatusChanged(moveId,
15950                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15951                        break;
15952                }
15953            }
15954        };
15955
15956        final MoveInfo move;
15957        if (moveCompleteApp) {
15958            // Kick off a thread to report progress estimates
15959            new Thread() {
15960                @Override
15961                public void run() {
15962                    while (true) {
15963                        try {
15964                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
15965                                break;
15966                            }
15967                        } catch (InterruptedException ignored) {
15968                        }
15969
15970                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
15971                        final int progress = 10 + (int) MathUtils.constrain(
15972                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
15973                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
15974                    }
15975                }
15976            }.start();
15977
15978            final String dataAppName = codeFile.getName();
15979            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
15980                    dataAppName, appId, seinfo);
15981        } else {
15982            move = null;
15983        }
15984
15985        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
15986
15987        final Message msg = mHandler.obtainMessage(INIT_COPY);
15988        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
15989        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
15990                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
15991        mHandler.sendMessage(msg);
15992    }
15993
15994    @Override
15995    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
15996        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15997
15998        final int realMoveId = mNextMoveId.getAndIncrement();
15999        final Bundle extras = new Bundle();
16000        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
16001        mMoveCallbacks.notifyCreated(realMoveId, extras);
16002
16003        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
16004            @Override
16005            public void onCreated(int moveId, Bundle extras) {
16006                // Ignored
16007            }
16008
16009            @Override
16010            public void onStatusChanged(int moveId, int status, long estMillis) {
16011                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16012            }
16013        };
16014
16015        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16016        storage.setPrimaryStorageUuid(volumeUuid, callback);
16017        return realMoveId;
16018    }
16019
16020    @Override
16021    public int getMoveStatus(int moveId) {
16022        mContext.enforceCallingOrSelfPermission(
16023                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16024        return mMoveCallbacks.mLastStatus.get(moveId);
16025    }
16026
16027    @Override
16028    public void registerMoveCallback(IPackageMoveObserver callback) {
16029        mContext.enforceCallingOrSelfPermission(
16030                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16031        mMoveCallbacks.register(callback);
16032    }
16033
16034    @Override
16035    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16036        mContext.enforceCallingOrSelfPermission(
16037                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16038        mMoveCallbacks.unregister(callback);
16039    }
16040
16041    @Override
16042    public boolean setInstallLocation(int loc) {
16043        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16044                null);
16045        if (getInstallLocation() == loc) {
16046            return true;
16047        }
16048        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16049                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16050            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16051                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16052            return true;
16053        }
16054        return false;
16055   }
16056
16057    @Override
16058    public int getInstallLocation() {
16059        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16060                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16061                PackageHelper.APP_INSTALL_AUTO);
16062    }
16063
16064    /** Called by UserManagerService */
16065    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
16066        mDirtyUsers.remove(userHandle);
16067        mSettings.removeUserLPw(userHandle);
16068        mPendingBroadcasts.remove(userHandle);
16069        if (mInstaller != null) {
16070            // Technically, we shouldn't be doing this with the package lock
16071            // held.  However, this is very rare, and there is already so much
16072            // other disk I/O going on, that we'll let it slide for now.
16073            final StorageManager storage = mContext.getSystemService(StorageManager.class);
16074            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16075                final String volumeUuid = vol.getFsUuid();
16076                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16077                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16078            }
16079        }
16080        mUserNeedsBadging.delete(userHandle);
16081        removeUnusedPackagesLILPw(userManager, userHandle);
16082    }
16083
16084    /**
16085     * We're removing userHandle and would like to remove any downloaded packages
16086     * that are no longer in use by any other user.
16087     * @param userHandle the user being removed
16088     */
16089    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16090        final boolean DEBUG_CLEAN_APKS = false;
16091        int [] users = userManager.getUserIdsLPr();
16092        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16093        while (psit.hasNext()) {
16094            PackageSetting ps = psit.next();
16095            if (ps.pkg == null) {
16096                continue;
16097            }
16098            final String packageName = ps.pkg.packageName;
16099            // Skip over if system app
16100            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16101                continue;
16102            }
16103            if (DEBUG_CLEAN_APKS) {
16104                Slog.i(TAG, "Checking package " + packageName);
16105            }
16106            boolean keep = false;
16107            for (int i = 0; i < users.length; i++) {
16108                if (users[i] != userHandle && ps.getInstalled(users[i])) {
16109                    keep = true;
16110                    if (DEBUG_CLEAN_APKS) {
16111                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
16112                                + users[i]);
16113                    }
16114                    break;
16115                }
16116            }
16117            if (!keep) {
16118                if (DEBUG_CLEAN_APKS) {
16119                    Slog.i(TAG, "  Removing package " + packageName);
16120                }
16121                mHandler.post(new Runnable() {
16122                    public void run() {
16123                        deletePackageX(packageName, userHandle, 0);
16124                    } //end run
16125                });
16126            }
16127        }
16128    }
16129
16130    /** Called by UserManagerService */
16131    void createNewUserLILPw(int userHandle) {
16132        if (mInstaller != null) {
16133            mInstaller.createUserConfig(userHandle);
16134            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
16135            applyFactoryDefaultBrowserLPw(userHandle);
16136            primeDomainVerificationsLPw(userHandle);
16137        }
16138    }
16139
16140    void newUserCreated(final int userHandle) {
16141        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
16142    }
16143
16144    @Override
16145    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
16146        mContext.enforceCallingOrSelfPermission(
16147                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16148                "Only package verification agents can read the verifier device identity");
16149
16150        synchronized (mPackages) {
16151            return mSettings.getVerifierDeviceIdentityLPw();
16152        }
16153    }
16154
16155    @Override
16156    public void setPermissionEnforced(String permission, boolean enforced) {
16157        // TODO: Now that we no longer change GID for storage, this should to away.
16158        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
16159                "setPermissionEnforced");
16160        if (READ_EXTERNAL_STORAGE.equals(permission)) {
16161            synchronized (mPackages) {
16162                if (mSettings.mReadExternalStorageEnforced == null
16163                        || mSettings.mReadExternalStorageEnforced != enforced) {
16164                    mSettings.mReadExternalStorageEnforced = enforced;
16165                    mSettings.writeLPr();
16166                }
16167            }
16168            // kill any non-foreground processes so we restart them and
16169            // grant/revoke the GID.
16170            final IActivityManager am = ActivityManagerNative.getDefault();
16171            if (am != null) {
16172                final long token = Binder.clearCallingIdentity();
16173                try {
16174                    am.killProcessesBelowForeground("setPermissionEnforcement");
16175                } catch (RemoteException e) {
16176                } finally {
16177                    Binder.restoreCallingIdentity(token);
16178                }
16179            }
16180        } else {
16181            throw new IllegalArgumentException("No selective enforcement for " + permission);
16182        }
16183    }
16184
16185    @Override
16186    @Deprecated
16187    public boolean isPermissionEnforced(String permission) {
16188        return true;
16189    }
16190
16191    @Override
16192    public boolean isStorageLow() {
16193        final long token = Binder.clearCallingIdentity();
16194        try {
16195            final DeviceStorageMonitorInternal
16196                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16197            if (dsm != null) {
16198                return dsm.isMemoryLow();
16199            } else {
16200                return false;
16201            }
16202        } finally {
16203            Binder.restoreCallingIdentity(token);
16204        }
16205    }
16206
16207    @Override
16208    public IPackageInstaller getPackageInstaller() {
16209        return mInstallerService;
16210    }
16211
16212    private boolean userNeedsBadging(int userId) {
16213        int index = mUserNeedsBadging.indexOfKey(userId);
16214        if (index < 0) {
16215            final UserInfo userInfo;
16216            final long token = Binder.clearCallingIdentity();
16217            try {
16218                userInfo = sUserManager.getUserInfo(userId);
16219            } finally {
16220                Binder.restoreCallingIdentity(token);
16221            }
16222            final boolean b;
16223            if (userInfo != null && userInfo.isManagedProfile()) {
16224                b = true;
16225            } else {
16226                b = false;
16227            }
16228            mUserNeedsBadging.put(userId, b);
16229            return b;
16230        }
16231        return mUserNeedsBadging.valueAt(index);
16232    }
16233
16234    @Override
16235    public KeySet getKeySetByAlias(String packageName, String alias) {
16236        if (packageName == null || alias == null) {
16237            return null;
16238        }
16239        synchronized(mPackages) {
16240            final PackageParser.Package pkg = mPackages.get(packageName);
16241            if (pkg == null) {
16242                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16243                throw new IllegalArgumentException("Unknown package: " + packageName);
16244            }
16245            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16246            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16247        }
16248    }
16249
16250    @Override
16251    public KeySet getSigningKeySet(String packageName) {
16252        if (packageName == null) {
16253            return null;
16254        }
16255        synchronized(mPackages) {
16256            final PackageParser.Package pkg = mPackages.get(packageName);
16257            if (pkg == null) {
16258                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16259                throw new IllegalArgumentException("Unknown package: " + packageName);
16260            }
16261            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16262                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16263                throw new SecurityException("May not access signing KeySet of other apps.");
16264            }
16265            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16266            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16267        }
16268    }
16269
16270    @Override
16271    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16272        if (packageName == null || ks == null) {
16273            return false;
16274        }
16275        synchronized(mPackages) {
16276            final PackageParser.Package pkg = mPackages.get(packageName);
16277            if (pkg == null) {
16278                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16279                throw new IllegalArgumentException("Unknown package: " + packageName);
16280            }
16281            IBinder ksh = ks.getToken();
16282            if (ksh instanceof KeySetHandle) {
16283                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16284                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16285            }
16286            return false;
16287        }
16288    }
16289
16290    @Override
16291    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16292        if (packageName == null || ks == null) {
16293            return false;
16294        }
16295        synchronized(mPackages) {
16296            final PackageParser.Package pkg = mPackages.get(packageName);
16297            if (pkg == null) {
16298                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16299                throw new IllegalArgumentException("Unknown package: " + packageName);
16300            }
16301            IBinder ksh = ks.getToken();
16302            if (ksh instanceof KeySetHandle) {
16303                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16304                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16305            }
16306            return false;
16307        }
16308    }
16309
16310    public void getUsageStatsIfNoPackageUsageInfo() {
16311        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16312            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16313            if (usm == null) {
16314                throw new IllegalStateException("UsageStatsManager must be initialized");
16315            }
16316            long now = System.currentTimeMillis();
16317            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16318            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16319                String packageName = entry.getKey();
16320                PackageParser.Package pkg = mPackages.get(packageName);
16321                if (pkg == null) {
16322                    continue;
16323                }
16324                UsageStats usage = entry.getValue();
16325                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16326                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16327            }
16328        }
16329    }
16330
16331    /**
16332     * Check and throw if the given before/after packages would be considered a
16333     * downgrade.
16334     */
16335    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16336            throws PackageManagerException {
16337        if (after.versionCode < before.mVersionCode) {
16338            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16339                    "Update version code " + after.versionCode + " is older than current "
16340                    + before.mVersionCode);
16341        } else if (after.versionCode == before.mVersionCode) {
16342            if (after.baseRevisionCode < before.baseRevisionCode) {
16343                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16344                        "Update base revision code " + after.baseRevisionCode
16345                        + " is older than current " + before.baseRevisionCode);
16346            }
16347
16348            if (!ArrayUtils.isEmpty(after.splitNames)) {
16349                for (int i = 0; i < after.splitNames.length; i++) {
16350                    final String splitName = after.splitNames[i];
16351                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16352                    if (j != -1) {
16353                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16354                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16355                                    "Update split " + splitName + " revision code "
16356                                    + after.splitRevisionCodes[i] + " is older than current "
16357                                    + before.splitRevisionCodes[j]);
16358                        }
16359                    }
16360                }
16361            }
16362        }
16363    }
16364
16365    private static class MoveCallbacks extends Handler {
16366        private static final int MSG_CREATED = 1;
16367        private static final int MSG_STATUS_CHANGED = 2;
16368
16369        private final RemoteCallbackList<IPackageMoveObserver>
16370                mCallbacks = new RemoteCallbackList<>();
16371
16372        private final SparseIntArray mLastStatus = new SparseIntArray();
16373
16374        public MoveCallbacks(Looper looper) {
16375            super(looper);
16376        }
16377
16378        public void register(IPackageMoveObserver callback) {
16379            mCallbacks.register(callback);
16380        }
16381
16382        public void unregister(IPackageMoveObserver callback) {
16383            mCallbacks.unregister(callback);
16384        }
16385
16386        @Override
16387        public void handleMessage(Message msg) {
16388            final SomeArgs args = (SomeArgs) msg.obj;
16389            final int n = mCallbacks.beginBroadcast();
16390            for (int i = 0; i < n; i++) {
16391                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16392                try {
16393                    invokeCallback(callback, msg.what, args);
16394                } catch (RemoteException ignored) {
16395                }
16396            }
16397            mCallbacks.finishBroadcast();
16398            args.recycle();
16399        }
16400
16401        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16402                throws RemoteException {
16403            switch (what) {
16404                case MSG_CREATED: {
16405                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16406                    break;
16407                }
16408                case MSG_STATUS_CHANGED: {
16409                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16410                    break;
16411                }
16412            }
16413        }
16414
16415        private void notifyCreated(int moveId, Bundle extras) {
16416            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16417
16418            final SomeArgs args = SomeArgs.obtain();
16419            args.argi1 = moveId;
16420            args.arg2 = extras;
16421            obtainMessage(MSG_CREATED, args).sendToTarget();
16422        }
16423
16424        private void notifyStatusChanged(int moveId, int status) {
16425            notifyStatusChanged(moveId, status, -1);
16426        }
16427
16428        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16429            Slog.v(TAG, "Move " + moveId + " status " + status);
16430
16431            final SomeArgs args = SomeArgs.obtain();
16432            args.argi1 = moveId;
16433            args.argi2 = status;
16434            args.arg3 = estMillis;
16435            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16436
16437            synchronized (mLastStatus) {
16438                mLastStatus.put(moveId, status);
16439            }
16440        }
16441    }
16442
16443    private final class OnPermissionChangeListeners extends Handler {
16444        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16445
16446        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16447                new RemoteCallbackList<>();
16448
16449        public OnPermissionChangeListeners(Looper looper) {
16450            super(looper);
16451        }
16452
16453        @Override
16454        public void handleMessage(Message msg) {
16455            switch (msg.what) {
16456                case MSG_ON_PERMISSIONS_CHANGED: {
16457                    final int uid = msg.arg1;
16458                    handleOnPermissionsChanged(uid);
16459                } break;
16460            }
16461        }
16462
16463        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16464            mPermissionListeners.register(listener);
16465
16466        }
16467
16468        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16469            mPermissionListeners.unregister(listener);
16470        }
16471
16472        public void onPermissionsChanged(int uid) {
16473            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16474                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16475            }
16476        }
16477
16478        private void handleOnPermissionsChanged(int uid) {
16479            final int count = mPermissionListeners.beginBroadcast();
16480            try {
16481                for (int i = 0; i < count; i++) {
16482                    IOnPermissionsChangeListener callback = mPermissionListeners
16483                            .getBroadcastItem(i);
16484                    try {
16485                        callback.onPermissionsChanged(uid);
16486                    } catch (RemoteException e) {
16487                        Log.e(TAG, "Permission listener is dead", e);
16488                    }
16489                }
16490            } finally {
16491                mPermissionListeners.finishBroadcast();
16492            }
16493        }
16494    }
16495
16496    private class PackageManagerInternalImpl extends PackageManagerInternal {
16497        @Override
16498        public void setLocationPackagesProvider(PackagesProvider provider) {
16499            synchronized (mPackages) {
16500                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16501            }
16502        }
16503
16504        @Override
16505        public void setImePackagesProvider(PackagesProvider provider) {
16506            synchronized (mPackages) {
16507                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16508            }
16509        }
16510
16511        @Override
16512        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16513            synchronized (mPackages) {
16514                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16515            }
16516        }
16517
16518        @Override
16519        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16520            synchronized (mPackages) {
16521                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16522            }
16523        }
16524
16525        @Override
16526        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16527            synchronized (mPackages) {
16528                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16529            }
16530        }
16531
16532        @Override
16533        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16534            synchronized (mPackages) {
16535                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
16536            }
16537        }
16538
16539        @Override
16540        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16541            synchronized (mPackages) {
16542                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16543                        packageName, userId);
16544            }
16545        }
16546
16547        @Override
16548        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16549            synchronized (mPackages) {
16550                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16551                        packageName, userId);
16552            }
16553        }
16554    }
16555
16556    @Override
16557    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16558        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16559        synchronized (mPackages) {
16560            final long identity = Binder.clearCallingIdentity();
16561            try {
16562                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16563                        packageNames, userId);
16564            } finally {
16565                Binder.restoreCallingIdentity(identity);
16566            }
16567        }
16568    }
16569
16570    private static void enforceSystemOrPhoneCaller(String tag) {
16571        int callingUid = Binder.getCallingUid();
16572        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16573            throw new SecurityException(
16574                    "Cannot call " + tag + " from UID " + callingUid);
16575        }
16576    }
16577}
16578