PackageManagerService.java revision d13cb798506a1e04d716c6eac41492c5ae95ccc8
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.GRANT_REVOKE_PERMISSIONS;
20import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
22import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
34import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
35import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
36import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
37import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
40import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
41import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
45import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
46import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
47import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
48import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
49import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
54import static android.content.pm.PackageManager.INSTALL_INTERNAL;
55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
60import static android.content.pm.PackageManager.MATCH_ALL;
61import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
62import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
63import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
64import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
65import static android.content.pm.PackageManager.PERMISSION_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.Binder;
147import android.os.Build;
148import android.os.Bundle;
149import android.os.Environment;
150import android.os.Environment.UserEnvironment;
151import android.os.FileUtils;
152import android.os.Handler;
153import android.os.IBinder;
154import android.os.Looper;
155import android.os.Message;
156import android.os.Parcel;
157import android.os.ParcelFileDescriptor;
158import android.os.Process;
159import android.os.RemoteCallbackList;
160import android.os.RemoteException;
161import android.os.SELinux;
162import android.os.ServiceManager;
163import android.os.SystemClock;
164import android.os.SystemProperties;
165import android.os.UserHandle;
166import android.os.UserManager;
167import android.os.storage.IMountService;
168import android.os.storage.StorageEventListener;
169import android.os.storage.StorageManager;
170import android.os.storage.VolumeInfo;
171import android.os.storage.VolumeRecord;
172import android.security.KeyStore;
173import android.security.SystemKeyStore;
174import android.system.ErrnoException;
175import android.system.Os;
176import android.system.StructStat;
177import android.text.TextUtils;
178import android.text.format.DateUtils;
179import android.util.ArrayMap;
180import android.util.ArraySet;
181import android.util.AtomicFile;
182import android.util.DisplayMetrics;
183import android.util.EventLog;
184import android.util.ExceptionUtils;
185import android.util.Log;
186import android.util.LogPrinter;
187import android.util.MathUtils;
188import android.util.PrintStreamPrinter;
189import android.util.Slog;
190import android.util.SparseArray;
191import android.util.SparseBooleanArray;
192import android.util.SparseIntArray;
193import android.util.Xml;
194import android.view.Display;
195
196import dalvik.system.DexFile;
197import dalvik.system.VMRuntime;
198
199import libcore.io.IoUtils;
200import libcore.util.EmptyArray;
201
202import com.android.internal.R;
203import com.android.internal.annotations.GuardedBy;
204import com.android.internal.app.IMediaContainerService;
205import com.android.internal.app.ResolverActivity;
206import com.android.internal.content.NativeLibraryHelper;
207import com.android.internal.content.PackageHelper;
208import com.android.internal.os.IParcelFileDescriptorFactory;
209import com.android.internal.os.SomeArgs;
210import com.android.internal.os.Zygote;
211import com.android.internal.util.ArrayUtils;
212import com.android.internal.util.FastPrintWriter;
213import com.android.internal.util.FastXmlSerializer;
214import com.android.internal.util.IndentingPrintWriter;
215import com.android.internal.util.Preconditions;
216import com.android.server.EventLogTags;
217import com.android.server.FgThread;
218import com.android.server.IntentResolver;
219import com.android.server.LocalServices;
220import com.android.server.ServiceThread;
221import com.android.server.SystemConfig;
222import com.android.server.Watchdog;
223import com.android.server.pm.PermissionsState.PermissionState;
224import com.android.server.pm.Settings.DatabaseVersion;
225import com.android.server.storage.DeviceStorageMonitorInternal;
226
227import org.xmlpull.v1.XmlPullParser;
228import org.xmlpull.v1.XmlPullParserException;
229import org.xmlpull.v1.XmlSerializer;
230
231import java.io.BufferedInputStream;
232import java.io.BufferedOutputStream;
233import java.io.BufferedReader;
234import java.io.ByteArrayInputStream;
235import java.io.ByteArrayOutputStream;
236import java.io.File;
237import java.io.FileDescriptor;
238import java.io.FileNotFoundException;
239import java.io.FileOutputStream;
240import java.io.FileReader;
241import java.io.FilenameFilter;
242import java.io.IOException;
243import java.io.InputStream;
244import java.io.PrintWriter;
245import java.nio.charset.StandardCharsets;
246import java.security.NoSuchAlgorithmException;
247import java.security.PublicKey;
248import java.security.cert.CertificateEncodingException;
249import java.security.cert.CertificateException;
250import java.text.SimpleDateFormat;
251import java.util.ArrayList;
252import java.util.Arrays;
253import java.util.Collection;
254import java.util.Collections;
255import java.util.Comparator;
256import java.util.Date;
257import java.util.Iterator;
258import java.util.List;
259import java.util.Map;
260import java.util.Objects;
261import java.util.Set;
262import java.util.concurrent.CountDownLatch;
263import java.util.concurrent.TimeUnit;
264import java.util.concurrent.atomic.AtomicBoolean;
265import java.util.concurrent.atomic.AtomicInteger;
266import java.util.concurrent.atomic.AtomicLong;
267
268/**
269 * Keep track of all those .apks everywhere.
270 *
271 * This is very central to the platform's security; please run the unit
272 * tests whenever making modifications here:
273 *
274mmm frameworks/base/tests/AndroidTests
275adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
276adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
277 *
278 * {@hide}
279 */
280public class PackageManagerService extends IPackageManager.Stub {
281    static final String TAG = "PackageManager";
282    static final boolean DEBUG_SETTINGS = false;
283    static final boolean DEBUG_PREFERRED = false;
284    static final boolean DEBUG_UPGRADE = false;
285    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
286    private static final boolean DEBUG_BACKUP = false;
287    private static final boolean DEBUG_INSTALL = false;
288    private static final boolean DEBUG_REMOVE = false;
289    private static final boolean DEBUG_BROADCASTS = false;
290    private static final boolean DEBUG_SHOW_INFO = false;
291    private static final boolean DEBUG_PACKAGE_INFO = false;
292    private static final boolean DEBUG_INTENT_MATCHING = false;
293    private static final boolean DEBUG_PACKAGE_SCANNING = false;
294    private static final boolean DEBUG_VERIFY = false;
295    private static final boolean DEBUG_DEXOPT = false;
296    private static final boolean DEBUG_ABI_SELECTION = false;
297
298    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = Build.IS_DEBUGGABLE;
299
300    private static final int RADIO_UID = Process.PHONE_UID;
301    private static final int LOG_UID = Process.LOG_UID;
302    private static final int NFC_UID = Process.NFC_UID;
303    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
304    private static final int SHELL_UID = Process.SHELL_UID;
305
306    // Cap the size of permission trees that 3rd party apps can define
307    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
308
309    // Suffix used during package installation when copying/moving
310    // package apks to install directory.
311    private static final String INSTALL_PACKAGE_SUFFIX = "-";
312
313    static final int SCAN_NO_DEX = 1<<1;
314    static final int SCAN_FORCE_DEX = 1<<2;
315    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
316    static final int SCAN_NEW_INSTALL = 1<<4;
317    static final int SCAN_NO_PATHS = 1<<5;
318    static final int SCAN_UPDATE_TIME = 1<<6;
319    static final int SCAN_DEFER_DEX = 1<<7;
320    static final int SCAN_BOOTING = 1<<8;
321    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
322    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
323    static final int SCAN_REQUIRE_KNOWN = 1<<12;
324    static final int SCAN_MOVE = 1<<13;
325    static final int SCAN_INITIAL = 1<<14;
326
327    static final int REMOVE_CHATTY = 1<<16;
328
329    private static final int[] EMPTY_INT_ARRAY = new int[0];
330
331    /**
332     * Timeout (in milliseconds) after which the watchdog should declare that
333     * our handler thread is wedged.  The usual default for such things is one
334     * minute but we sometimes do very lengthy I/O operations on this thread,
335     * such as installing multi-gigabyte applications, so ours needs to be longer.
336     */
337    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
338
339    /**
340     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
341     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
342     * settings entry if available, otherwise we use the hardcoded default.  If it's been
343     * more than this long since the last fstrim, we force one during the boot sequence.
344     *
345     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
346     * one gets run at the next available charging+idle time.  This final mandatory
347     * no-fstrim check kicks in only of the other scheduling criteria is never met.
348     */
349    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
350
351    /**
352     * Whether verification is enabled by default.
353     */
354    private static final boolean DEFAULT_VERIFY_ENABLE = true;
355
356    /**
357     * The default maximum time to wait for the verification agent to return in
358     * milliseconds.
359     */
360    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
361
362    /**
363     * The default response for package verification timeout.
364     *
365     * This can be either PackageManager.VERIFICATION_ALLOW or
366     * PackageManager.VERIFICATION_REJECT.
367     */
368    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
369
370    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
371
372    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
373            DEFAULT_CONTAINER_PACKAGE,
374            "com.android.defcontainer.DefaultContainerService");
375
376    private static final String KILL_APP_REASON_GIDS_CHANGED =
377            "permission grant or revoke changed gids";
378
379    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
380            "permissions revoked";
381
382    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
383
384    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
385
386    /** Permission grant: not grant the permission. */
387    private static final int GRANT_DENIED = 1;
388
389    /** Permission grant: grant the permission as an install permission. */
390    private static final int GRANT_INSTALL = 2;
391
392    /** Permission grant: grant the permission as an install permission for a legacy app. */
393    private static final int GRANT_INSTALL_LEGACY = 3;
394
395    /** Permission grant: grant the permission as a runtime one. */
396    private static final int GRANT_RUNTIME = 4;
397
398    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
399    private static final int GRANT_UPGRADE = 5;
400
401    /** Canonical intent used to identify what counts as a "web browser" app */
402    private static final Intent sBrowserIntent;
403    static {
404        sBrowserIntent = new Intent();
405        sBrowserIntent.setAction(Intent.ACTION_VIEW);
406        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
407        sBrowserIntent.setData(Uri.parse("http:"));
408    }
409
410    final ServiceThread mHandlerThread;
411
412    final PackageHandler mHandler;
413
414    /**
415     * Messages for {@link #mHandler} that need to wait for system ready before
416     * being dispatched.
417     */
418    private ArrayList<Message> mPostSystemReadyMessages;
419
420    final int mSdkVersion = Build.VERSION.SDK_INT;
421
422    final Context mContext;
423    final boolean mFactoryTest;
424    final boolean mOnlyCore;
425    final boolean mLazyDexOpt;
426    final long mDexOptLRUThresholdInMills;
427    final DisplayMetrics mMetrics;
428    final int mDefParseFlags;
429    final String[] mSeparateProcesses;
430    final boolean mIsUpgrade;
431
432    // This is where all application persistent data goes.
433    final File mAppDataDir;
434
435    // This is where all application persistent data goes for secondary users.
436    final File mUserAppDataDir;
437
438    /** The location for ASEC container files on internal storage. */
439    final String mAsecInternalPath;
440
441    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
442    // LOCK HELD.  Can be called with mInstallLock held.
443    @GuardedBy("mInstallLock")
444    final Installer mInstaller;
445
446    /** Directory where installed third-party apps stored */
447    final File mAppInstallDir;
448
449    /**
450     * Directory to which applications installed internally have their
451     * 32 bit native libraries copied.
452     */
453    private File mAppLib32InstallDir;
454
455    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
456    // apps.
457    final File mDrmAppPrivateInstallDir;
458
459    // ----------------------------------------------------------------
460
461    // Lock for state used when installing and doing other long running
462    // operations.  Methods that must be called with this lock held have
463    // the suffix "LI".
464    final Object mInstallLock = new Object();
465
466    // ----------------------------------------------------------------
467
468    // Keys are String (package name), values are Package.  This also serves
469    // as the lock for the global state.  Methods that must be called with
470    // this lock held have the prefix "LP".
471    @GuardedBy("mPackages")
472    final ArrayMap<String, PackageParser.Package> mPackages =
473            new ArrayMap<String, PackageParser.Package>();
474
475    // Tracks available target package names -> overlay package paths.
476    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
477        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
478
479    /**
480     * Tracks new system packages [receiving in an OTA] that we expect to
481     * find updated user-installed versions. Keys are package name, values
482     * are package location.
483     */
484    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
485
486    final Settings mSettings;
487    boolean mRestoredSettings;
488
489    // System configuration read by SystemConfig.
490    final int[] mGlobalGids;
491    final SparseArray<ArraySet<String>> mSystemPermissions;
492    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
493
494    // If mac_permissions.xml was found for seinfo labeling.
495    boolean mFoundPolicyFile;
496
497    // If a recursive restorecon of /data/data/<pkg> is needed.
498    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
499
500    public static final class SharedLibraryEntry {
501        public final String path;
502        public final String apk;
503
504        SharedLibraryEntry(String _path, String _apk) {
505            path = _path;
506            apk = _apk;
507        }
508    }
509
510    // Currently known shared libraries.
511    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
512            new ArrayMap<String, SharedLibraryEntry>();
513
514    // All available activities, for your resolving pleasure.
515    final ActivityIntentResolver mActivities =
516            new ActivityIntentResolver();
517
518    // All available receivers, for your resolving pleasure.
519    final ActivityIntentResolver mReceivers =
520            new ActivityIntentResolver();
521
522    // All available services, for your resolving pleasure.
523    final ServiceIntentResolver mServices = new ServiceIntentResolver();
524
525    // All available providers, for your resolving pleasure.
526    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
527
528    // Mapping from provider base names (first directory in content URI codePath)
529    // to the provider information.
530    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
531            new ArrayMap<String, PackageParser.Provider>();
532
533    // Mapping from instrumentation class names to info about them.
534    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
535            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
536
537    // Mapping from permission names to info about them.
538    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
539            new ArrayMap<String, PackageParser.PermissionGroup>();
540
541    // Packages whose data we have transfered into another package, thus
542    // should no longer exist.
543    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
544
545    // Broadcast actions that are only available to the system.
546    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
547
548    /** List of packages waiting for verification. */
549    final SparseArray<PackageVerificationState> mPendingVerification
550            = new SparseArray<PackageVerificationState>();
551
552    /** Set of packages associated with each app op permission. */
553    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
554
555    final PackageInstallerService mInstallerService;
556
557    private final PackageDexOptimizer mPackageDexOptimizer;
558
559    private AtomicInteger mNextMoveId = new AtomicInteger();
560    private final MoveCallbacks mMoveCallbacks;
561
562    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
563
564    // Cache of users who need badging.
565    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
566
567    /** Token for keys in mPendingVerification. */
568    private int mPendingVerificationToken = 0;
569
570    volatile boolean mSystemReady;
571    volatile boolean mSafeMode;
572    volatile boolean mHasSystemUidErrors;
573
574    ApplicationInfo mAndroidApplication;
575    final ActivityInfo mResolveActivity = new ActivityInfo();
576    final ResolveInfo mResolveInfo = new ResolveInfo();
577    ComponentName mResolveComponentName;
578    PackageParser.Package mPlatformPackage;
579    ComponentName mCustomResolverComponentName;
580
581    boolean mResolverReplaced = false;
582
583    private final ComponentName mIntentFilterVerifierComponent;
584    private int mIntentFilterVerificationToken = 0;
585
586    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
587            = new SparseArray<IntentFilterVerificationState>();
588
589    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
590            new DefaultPermissionGrantPolicy(this);
591
592    private static class IFVerificationParams {
593        PackageParser.Package pkg;
594        boolean replacing;
595        int userId;
596        int verifierUid;
597
598        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
599                int _userId, int _verifierUid) {
600            pkg = _pkg;
601            replacing = _replacing;
602            userId = _userId;
603            replacing = _replacing;
604            verifierUid = _verifierUid;
605        }
606    }
607
608    private interface IntentFilterVerifier<T extends IntentFilter> {
609        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
610                                               T filter, String packageName);
611        void startVerifications(int userId);
612        void receiveVerificationResponse(int verificationId);
613    }
614
615    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
616        private Context mContext;
617        private ComponentName mIntentFilterVerifierComponent;
618        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
619
620        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
621            mContext = context;
622            mIntentFilterVerifierComponent = verifierComponent;
623        }
624
625        private String getDefaultScheme() {
626            return IntentFilter.SCHEME_HTTPS;
627        }
628
629        @Override
630        public void startVerifications(int userId) {
631            // Launch verifications requests
632            int count = mCurrentIntentFilterVerifications.size();
633            for (int n=0; n<count; n++) {
634                int verificationId = mCurrentIntentFilterVerifications.get(n);
635                final IntentFilterVerificationState ivs =
636                        mIntentFilterVerificationStates.get(verificationId);
637
638                String packageName = ivs.getPackageName();
639
640                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
641                final int filterCount = filters.size();
642                ArraySet<String> domainsSet = new ArraySet<>();
643                for (int m=0; m<filterCount; m++) {
644                    PackageParser.ActivityIntentInfo filter = filters.get(m);
645                    domainsSet.addAll(filter.getHostsList());
646                }
647                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
648                synchronized (mPackages) {
649                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
650                            packageName, domainsList) != null) {
651                        scheduleWriteSettingsLocked();
652                    }
653                }
654                sendVerificationRequest(userId, verificationId, ivs);
655            }
656            mCurrentIntentFilterVerifications.clear();
657        }
658
659        private void sendVerificationRequest(int userId, int verificationId,
660                IntentFilterVerificationState ivs) {
661
662            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
663            verificationIntent.putExtra(
664                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
665                    verificationId);
666            verificationIntent.putExtra(
667                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
668                    getDefaultScheme());
669            verificationIntent.putExtra(
670                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
671                    ivs.getHostsString());
672            verificationIntent.putExtra(
673                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
674                    ivs.getPackageName());
675            verificationIntent.setComponent(mIntentFilterVerifierComponent);
676            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
677
678            UserHandle user = new UserHandle(userId);
679            mContext.sendBroadcastAsUser(verificationIntent, user);
680            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
681                    "Sending IntentFilter verification broadcast");
682        }
683
684        public void receiveVerificationResponse(int verificationId) {
685            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
686
687            final boolean verified = ivs.isVerified();
688
689            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
690            final int count = filters.size();
691            if (DEBUG_DOMAIN_VERIFICATION) {
692                Slog.i(TAG, "Received verification response " + verificationId
693                        + " for " + count + " filters, verified=" + verified);
694            }
695            for (int n=0; n<count; n++) {
696                PackageParser.ActivityIntentInfo filter = filters.get(n);
697                filter.setVerified(verified);
698
699                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
700                        + " verified with result:" + verified + " and hosts:"
701                        + ivs.getHostsString());
702            }
703
704            mIntentFilterVerificationStates.remove(verificationId);
705
706            final String packageName = ivs.getPackageName();
707            IntentFilterVerificationInfo ivi = null;
708
709            synchronized (mPackages) {
710                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
711            }
712            if (ivi == null) {
713                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
714                        + verificationId + " packageName:" + packageName);
715                return;
716            }
717            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
718                    "Updating IntentFilterVerificationInfo for package " + packageName
719                            +" verificationId:" + verificationId);
720
721            synchronized (mPackages) {
722                if (verified) {
723                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
724                } else {
725                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
726                }
727                scheduleWriteSettingsLocked();
728
729                final int userId = ivs.getUserId();
730                if (userId != UserHandle.USER_ALL) {
731                    final int userStatus =
732                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
733
734                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
735                    boolean needUpdate = false;
736
737                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
738                    // already been set by the User thru the Disambiguation dialog
739                    switch (userStatus) {
740                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
741                            if (verified) {
742                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
743                            } else {
744                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
745                            }
746                            needUpdate = true;
747                            break;
748
749                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
750                            if (verified) {
751                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
752                                needUpdate = true;
753                            }
754                            break;
755
756                        default:
757                            // Nothing to do
758                    }
759
760                    if (needUpdate) {
761                        mSettings.updateIntentFilterVerificationStatusLPw(
762                                packageName, updatedStatus, userId);
763                        scheduleWritePackageRestrictionsLocked(userId);
764                    }
765                }
766            }
767        }
768
769        @Override
770        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
771                    ActivityIntentInfo filter, String packageName) {
772            if (!hasValidDomains(filter)) {
773                return false;
774            }
775            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
776            if (ivs == null) {
777                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
778                        packageName);
779            }
780            if (DEBUG_DOMAIN_VERIFICATION) {
781                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
782            }
783            ivs.addFilter(filter);
784            return true;
785        }
786
787        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
788                int userId, int verificationId, String packageName) {
789            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
790                    verifierUid, userId, packageName);
791            ivs.setPendingState();
792            synchronized (mPackages) {
793                mIntentFilterVerificationStates.append(verificationId, ivs);
794                mCurrentIntentFilterVerifications.add(verificationId);
795            }
796            return ivs;
797        }
798    }
799
800    private static boolean hasValidDomains(ActivityIntentInfo filter) {
801        boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
802                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS);
803        if (!hasHTTPorHTTPS) {
804            return false;
805        }
806        return true;
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,
1343                                        args.user.getIdentifier());
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            // Remove any apps installed on the forgotten volume
1659            synchronized (mPackages) {
1660                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1661                for (PackageSetting ps : packages) {
1662                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1663                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1664                            UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS);
1665                }
1666
1667                mSettings.writeLPr();
1668            }
1669        }
1670    };
1671
1672    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) {
1673        if (userId >= UserHandle.USER_OWNER) {
1674            grantRequestedRuntimePermissionsForUser(pkg, userId);
1675        } else if (userId == UserHandle.USER_ALL) {
1676            for (int someUserId : UserManagerService.getInstance().getUserIds()) {
1677                grantRequestedRuntimePermissionsForUser(pkg, someUserId);
1678            }
1679        }
1680
1681        // We could have touched GID membership, so flush out packages.list
1682        synchronized (mPackages) {
1683            mSettings.writePackageListLPr();
1684        }
1685    }
1686
1687    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) {
1688        SettingBase sb = (SettingBase) pkg.mExtras;
1689        if (sb == null) {
1690            return;
1691        }
1692
1693        PermissionsState permissionsState = sb.getPermissionsState();
1694
1695        for (String permission : pkg.requestedPermissions) {
1696            BasePermission bp = mSettings.mPermissions.get(permission);
1697            if (bp != null && bp.isRuntime()) {
1698                permissionsState.grantRuntimePermission(bp, userId);
1699            }
1700        }
1701    }
1702
1703    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1704        Bundle extras = null;
1705        switch (res.returnCode) {
1706            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1707                extras = new Bundle();
1708                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1709                        res.origPermission);
1710                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1711                        res.origPackage);
1712                break;
1713            }
1714            case PackageManager.INSTALL_SUCCEEDED: {
1715                extras = new Bundle();
1716                extras.putBoolean(Intent.EXTRA_REPLACING,
1717                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1718                break;
1719            }
1720        }
1721        return extras;
1722    }
1723
1724    void scheduleWriteSettingsLocked() {
1725        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1726            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1727        }
1728    }
1729
1730    void scheduleWritePackageRestrictionsLocked(int userId) {
1731        if (!sUserManager.exists(userId)) return;
1732        mDirtyUsers.add(userId);
1733        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1734            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1735        }
1736    }
1737
1738    public static PackageManagerService main(Context context, Installer installer,
1739            boolean factoryTest, boolean onlyCore) {
1740        PackageManagerService m = new PackageManagerService(context, installer,
1741                factoryTest, onlyCore);
1742        ServiceManager.addService("package", m);
1743        return m;
1744    }
1745
1746    static String[] splitString(String str, char sep) {
1747        int count = 1;
1748        int i = 0;
1749        while ((i=str.indexOf(sep, i)) >= 0) {
1750            count++;
1751            i++;
1752        }
1753
1754        String[] res = new String[count];
1755        i=0;
1756        count = 0;
1757        int lastI=0;
1758        while ((i=str.indexOf(sep, i)) >= 0) {
1759            res[count] = str.substring(lastI, i);
1760            count++;
1761            i++;
1762            lastI = i;
1763        }
1764        res[count] = str.substring(lastI, str.length());
1765        return res;
1766    }
1767
1768    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1769        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1770                Context.DISPLAY_SERVICE);
1771        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1772    }
1773
1774    public PackageManagerService(Context context, Installer installer,
1775            boolean factoryTest, boolean onlyCore) {
1776        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1777                SystemClock.uptimeMillis());
1778
1779        if (mSdkVersion <= 0) {
1780            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1781        }
1782
1783        mContext = context;
1784        mFactoryTest = factoryTest;
1785        mOnlyCore = onlyCore;
1786        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1787        mMetrics = new DisplayMetrics();
1788        mSettings = new Settings(mPackages);
1789        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1790                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1791        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1792                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1793        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1794                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1795        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1796                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1797        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1798                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1799        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1800                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1801
1802        // TODO: add a property to control this?
1803        long dexOptLRUThresholdInMinutes;
1804        if (mLazyDexOpt) {
1805            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1806        } else {
1807            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1808        }
1809        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1810
1811        String separateProcesses = SystemProperties.get("debug.separate_processes");
1812        if (separateProcesses != null && separateProcesses.length() > 0) {
1813            if ("*".equals(separateProcesses)) {
1814                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1815                mSeparateProcesses = null;
1816                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1817            } else {
1818                mDefParseFlags = 0;
1819                mSeparateProcesses = separateProcesses.split(",");
1820                Slog.w(TAG, "Running with debug.separate_processes: "
1821                        + separateProcesses);
1822            }
1823        } else {
1824            mDefParseFlags = 0;
1825            mSeparateProcesses = null;
1826        }
1827
1828        mInstaller = installer;
1829        mPackageDexOptimizer = new PackageDexOptimizer(this);
1830        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1831
1832        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1833                FgThread.get().getLooper());
1834
1835        getDefaultDisplayMetrics(context, mMetrics);
1836
1837        SystemConfig systemConfig = SystemConfig.getInstance();
1838        mGlobalGids = systemConfig.getGlobalGids();
1839        mSystemPermissions = systemConfig.getSystemPermissions();
1840        mAvailableFeatures = systemConfig.getAvailableFeatures();
1841
1842        synchronized (mInstallLock) {
1843        // writer
1844        synchronized (mPackages) {
1845            mHandlerThread = new ServiceThread(TAG,
1846                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1847            mHandlerThread.start();
1848            mHandler = new PackageHandler(mHandlerThread.getLooper());
1849            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1850
1851            File dataDir = Environment.getDataDirectory();
1852            mAppDataDir = new File(dataDir, "data");
1853            mAppInstallDir = new File(dataDir, "app");
1854            mAppLib32InstallDir = new File(dataDir, "app-lib");
1855            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1856            mUserAppDataDir = new File(dataDir, "user");
1857            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1858
1859            sUserManager = new UserManagerService(context, this,
1860                    mInstallLock, mPackages);
1861
1862            // Propagate permission configuration in to package manager.
1863            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1864                    = systemConfig.getPermissions();
1865            for (int i=0; i<permConfig.size(); i++) {
1866                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1867                BasePermission bp = mSettings.mPermissions.get(perm.name);
1868                if (bp == null) {
1869                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1870                    mSettings.mPermissions.put(perm.name, bp);
1871                }
1872                if (perm.gids != null) {
1873                    bp.setGids(perm.gids, perm.perUser);
1874                }
1875            }
1876
1877            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1878            for (int i=0; i<libConfig.size(); i++) {
1879                mSharedLibraries.put(libConfig.keyAt(i),
1880                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1881            }
1882
1883            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1884
1885            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1886                    mSdkVersion, mOnlyCore);
1887
1888            String customResolverActivity = Resources.getSystem().getString(
1889                    R.string.config_customResolverActivity);
1890            if (TextUtils.isEmpty(customResolverActivity)) {
1891                customResolverActivity = null;
1892            } else {
1893                mCustomResolverComponentName = ComponentName.unflattenFromString(
1894                        customResolverActivity);
1895            }
1896
1897            long startTime = SystemClock.uptimeMillis();
1898
1899            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1900                    startTime);
1901
1902            // Set flag to monitor and not change apk file paths when
1903            // scanning install directories.
1904            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
1905
1906            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1907
1908            /**
1909             * Add everything in the in the boot class path to the
1910             * list of process files because dexopt will have been run
1911             * if necessary during zygote startup.
1912             */
1913            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1914            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1915
1916            if (bootClassPath != null) {
1917                String[] bootClassPathElements = splitString(bootClassPath, ':');
1918                for (String element : bootClassPathElements) {
1919                    alreadyDexOpted.add(element);
1920                }
1921            } else {
1922                Slog.w(TAG, "No BOOTCLASSPATH found!");
1923            }
1924
1925            if (systemServerClassPath != null) {
1926                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1927                for (String element : systemServerClassPathElements) {
1928                    alreadyDexOpted.add(element);
1929                }
1930            } else {
1931                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1932            }
1933
1934            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1935            final String[] dexCodeInstructionSets =
1936                    getDexCodeInstructionSets(
1937                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1938
1939            /**
1940             * Ensure all external libraries have had dexopt run on them.
1941             */
1942            if (mSharedLibraries.size() > 0) {
1943                // NOTE: For now, we're compiling these system "shared libraries"
1944                // (and framework jars) into all available architectures. It's possible
1945                // to compile them only when we come across an app that uses them (there's
1946                // already logic for that in scanPackageLI) but that adds some complexity.
1947                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1948                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1949                        final String lib = libEntry.path;
1950                        if (lib == null) {
1951                            continue;
1952                        }
1953
1954                        try {
1955                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1956                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1957                                alreadyDexOpted.add(lib);
1958                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1959                            }
1960                        } catch (FileNotFoundException e) {
1961                            Slog.w(TAG, "Library not found: " + lib);
1962                        } catch (IOException e) {
1963                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1964                                    + e.getMessage());
1965                        }
1966                    }
1967                }
1968            }
1969
1970            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1971
1972            // Gross hack for now: we know this file doesn't contain any
1973            // code, so don't dexopt it to avoid the resulting log spew.
1974            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1975
1976            // Gross hack for now: we know this file is only part of
1977            // the boot class path for art, so don't dexopt it to
1978            // avoid the resulting log spew.
1979            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1980
1981            /**
1982             * There are a number of commands implemented in Java, which
1983             * we currently need to do the dexopt on so that they can be
1984             * run from a non-root shell.
1985             */
1986            String[] frameworkFiles = frameworkDir.list();
1987            if (frameworkFiles != null) {
1988                // TODO: We could compile these only for the most preferred ABI. We should
1989                // first double check that the dex files for these commands are not referenced
1990                // by other system apps.
1991                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1992                    for (int i=0; i<frameworkFiles.length; i++) {
1993                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1994                        String path = libPath.getPath();
1995                        // Skip the file if we already did it.
1996                        if (alreadyDexOpted.contains(path)) {
1997                            continue;
1998                        }
1999                        // Skip the file if it is not a type we want to dexopt.
2000                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
2001                            continue;
2002                        }
2003                        try {
2004                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
2005                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2006                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
2007                            }
2008                        } catch (FileNotFoundException e) {
2009                            Slog.w(TAG, "Jar not found: " + path);
2010                        } catch (IOException e) {
2011                            Slog.w(TAG, "Exception reading jar: " + path, e);
2012                        }
2013                    }
2014                }
2015            }
2016
2017            // Collect vendor overlay packages.
2018            // (Do this before scanning any apps.)
2019            // For security and version matching reason, only consider
2020            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2021            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2022            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2023                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2024
2025            // Find base frameworks (resource packages without code).
2026            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2027                    | PackageParser.PARSE_IS_SYSTEM_DIR
2028                    | PackageParser.PARSE_IS_PRIVILEGED,
2029                    scanFlags | SCAN_NO_DEX, 0);
2030
2031            // Collected privileged system packages.
2032            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2033            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2034                    | PackageParser.PARSE_IS_SYSTEM_DIR
2035                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2036
2037            // Collect ordinary system packages.
2038            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2039            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2040                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2041
2042            // Collect all vendor packages.
2043            File vendorAppDir = new File("/vendor/app");
2044            try {
2045                vendorAppDir = vendorAppDir.getCanonicalFile();
2046            } catch (IOException e) {
2047                // failed to look up canonical path, continue with original one
2048            }
2049            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2050                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2051
2052            // Collect all OEM packages.
2053            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2054            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2055                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2056
2057            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2058            mInstaller.moveFiles();
2059
2060            // Prune any system packages that no longer exist.
2061            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2062            if (!mOnlyCore) {
2063                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2064                while (psit.hasNext()) {
2065                    PackageSetting ps = psit.next();
2066
2067                    /*
2068                     * If this is not a system app, it can't be a
2069                     * disable system app.
2070                     */
2071                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2072                        continue;
2073                    }
2074
2075                    /*
2076                     * If the package is scanned, it's not erased.
2077                     */
2078                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2079                    if (scannedPkg != null) {
2080                        /*
2081                         * If the system app is both scanned and in the
2082                         * disabled packages list, then it must have been
2083                         * added via OTA. Remove it from the currently
2084                         * scanned package so the previously user-installed
2085                         * application can be scanned.
2086                         */
2087                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2088                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2089                                    + ps.name + "; removing system app.  Last known codePath="
2090                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2091                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2092                                    + scannedPkg.mVersionCode);
2093                            removePackageLI(ps, true);
2094                            mExpectingBetter.put(ps.name, ps.codePath);
2095                        }
2096
2097                        continue;
2098                    }
2099
2100                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2101                        psit.remove();
2102                        logCriticalInfo(Log.WARN, "System package " + ps.name
2103                                + " no longer exists; wiping its data");
2104                        removeDataDirsLI(null, ps.name);
2105                    } else {
2106                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2107                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2108                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2109                        }
2110                    }
2111                }
2112            }
2113
2114            //look for any incomplete package installations
2115            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2116            //clean up list
2117            for(int i = 0; i < deletePkgsList.size(); i++) {
2118                //clean up here
2119                cleanupInstallFailedPackage(deletePkgsList.get(i));
2120            }
2121            //delete tmp files
2122            deleteTempPackageFiles();
2123
2124            // Remove any shared userIDs that have no associated packages
2125            mSettings.pruneSharedUsersLPw();
2126
2127            if (!mOnlyCore) {
2128                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2129                        SystemClock.uptimeMillis());
2130                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2131
2132                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2133                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2134
2135                /**
2136                 * Remove disable package settings for any updated system
2137                 * apps that were removed via an OTA. If they're not a
2138                 * previously-updated app, remove them completely.
2139                 * Otherwise, just revoke their system-level permissions.
2140                 */
2141                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2142                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2143                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2144
2145                    String msg;
2146                    if (deletedPkg == null) {
2147                        msg = "Updated system package " + deletedAppName
2148                                + " no longer exists; wiping its data";
2149                        removeDataDirsLI(null, deletedAppName);
2150                    } else {
2151                        msg = "Updated system app + " + deletedAppName
2152                                + " no longer present; removing system privileges for "
2153                                + deletedAppName;
2154
2155                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2156
2157                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2158                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2159                    }
2160                    logCriticalInfo(Log.WARN, msg);
2161                }
2162
2163                /**
2164                 * Make sure all system apps that we expected to appear on
2165                 * the userdata partition actually showed up. If they never
2166                 * appeared, crawl back and revive the system version.
2167                 */
2168                for (int i = 0; i < mExpectingBetter.size(); i++) {
2169                    final String packageName = mExpectingBetter.keyAt(i);
2170                    if (!mPackages.containsKey(packageName)) {
2171                        final File scanFile = mExpectingBetter.valueAt(i);
2172
2173                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2174                                + " but never showed up; reverting to system");
2175
2176                        final int reparseFlags;
2177                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2178                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2179                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2180                                    | PackageParser.PARSE_IS_PRIVILEGED;
2181                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2182                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2183                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2184                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2185                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2186                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2187                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2188                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2189                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2190                        } else {
2191                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2192                            continue;
2193                        }
2194
2195                        mSettings.enableSystemPackageLPw(packageName);
2196
2197                        try {
2198                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2199                        } catch (PackageManagerException e) {
2200                            Slog.e(TAG, "Failed to parse original system package: "
2201                                    + e.getMessage());
2202                        }
2203                    }
2204                }
2205            }
2206            mExpectingBetter.clear();
2207
2208            // Now that we know all of the shared libraries, update all clients to have
2209            // the correct library paths.
2210            updateAllSharedLibrariesLPw();
2211
2212            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2213                // NOTE: We ignore potential failures here during a system scan (like
2214                // the rest of the commands above) because there's precious little we
2215                // can do about it. A settings error is reported, though.
2216                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2217                        false /* force dexopt */, false /* defer dexopt */);
2218            }
2219
2220            // Now that we know all the packages we are keeping,
2221            // read and update their last usage times.
2222            mPackageUsage.readLP();
2223
2224            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2225                    SystemClock.uptimeMillis());
2226            Slog.i(TAG, "Time to scan packages: "
2227                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2228                    + " seconds");
2229
2230            // If the platform SDK has changed since the last time we booted,
2231            // we need to re-grant app permission to catch any new ones that
2232            // appear.  This is really a hack, and means that apps can in some
2233            // cases get permissions that the user didn't initially explicitly
2234            // allow...  it would be nice to have some better way to handle
2235            // this situation.
2236            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
2237                    != mSdkVersion;
2238            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
2239                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
2240                    + "; regranting permissions for internal storage");
2241            mSettings.mInternalSdkPlatform = mSdkVersion;
2242
2243            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
2244                    | (regrantPermissions
2245                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
2246                            : 0));
2247
2248            // If this is the first boot, and it is a normal boot, then
2249            // we need to initialize the default preferred apps.
2250            if (!mRestoredSettings && !onlyCore) {
2251                mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER);
2252                applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER);
2253                primeDomainVerificationsLPw(UserHandle.USER_OWNER);
2254            }
2255
2256            // If this is first boot after an OTA, and a normal boot, then
2257            // we need to clear code cache directories.
2258            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
2259            if (mIsUpgrade && !onlyCore) {
2260                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2261                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2262                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2263                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2264                }
2265                mSettings.mFingerprint = Build.FINGERPRINT;
2266            }
2267
2268            checkDefaultBrowser();
2269
2270            // All the changes are done during package scanning.
2271            mSettings.updateInternalDatabaseVersion();
2272
2273            // can downgrade to reader
2274            mSettings.writeLPr();
2275
2276            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2277                    SystemClock.uptimeMillis());
2278
2279            mRequiredVerifierPackage = getRequiredVerifierLPr();
2280            mRequiredInstallerPackage = getRequiredInstallerLPr();
2281
2282            mInstallerService = new PackageInstallerService(context, this);
2283
2284            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2285            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2286                    mIntentFilterVerifierComponent);
2287
2288        } // synchronized (mPackages)
2289        } // synchronized (mInstallLock)
2290
2291        // Now after opening every single application zip, make sure they
2292        // are all flushed.  Not really needed, but keeps things nice and
2293        // tidy.
2294        Runtime.getRuntime().gc();
2295
2296        // Expose private service for system components to use.
2297        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2298    }
2299
2300    @Override
2301    public boolean isFirstBoot() {
2302        return !mRestoredSettings;
2303    }
2304
2305    @Override
2306    public boolean isOnlyCoreApps() {
2307        return mOnlyCore;
2308    }
2309
2310    @Override
2311    public boolean isUpgrade() {
2312        return mIsUpgrade;
2313    }
2314
2315    private String getRequiredVerifierLPr() {
2316        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2317        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2318                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2319
2320        String requiredVerifier = null;
2321
2322        final int N = receivers.size();
2323        for (int i = 0; i < N; i++) {
2324            final ResolveInfo info = receivers.get(i);
2325
2326            if (info.activityInfo == null) {
2327                continue;
2328            }
2329
2330            final String packageName = info.activityInfo.packageName;
2331
2332            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2333                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2334                continue;
2335            }
2336
2337            if (requiredVerifier != null) {
2338                throw new RuntimeException("There can be only one required verifier");
2339            }
2340
2341            requiredVerifier = packageName;
2342        }
2343
2344        return requiredVerifier;
2345    }
2346
2347    private String getRequiredInstallerLPr() {
2348        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2349        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2350        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2351
2352        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2353                PACKAGE_MIME_TYPE, 0, 0);
2354
2355        String requiredInstaller = null;
2356
2357        final int N = installers.size();
2358        for (int i = 0; i < N; i++) {
2359            final ResolveInfo info = installers.get(i);
2360            final String packageName = info.activityInfo.packageName;
2361
2362            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2363                continue;
2364            }
2365
2366            if (requiredInstaller != null) {
2367                throw new RuntimeException("There must be one required installer");
2368            }
2369
2370            requiredInstaller = packageName;
2371        }
2372
2373        if (requiredInstaller == null) {
2374            throw new RuntimeException("There must be one required installer");
2375        }
2376
2377        return requiredInstaller;
2378    }
2379
2380    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2381        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2382        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2383                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2384
2385        ComponentName verifierComponentName = null;
2386
2387        int priority = -1000;
2388        final int N = receivers.size();
2389        for (int i = 0; i < N; i++) {
2390            final ResolveInfo info = receivers.get(i);
2391
2392            if (info.activityInfo == null) {
2393                continue;
2394            }
2395
2396            final String packageName = info.activityInfo.packageName;
2397
2398            final PackageSetting ps = mSettings.mPackages.get(packageName);
2399            if (ps == null) {
2400                continue;
2401            }
2402
2403            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2404                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2405                continue;
2406            }
2407
2408            // Select the IntentFilterVerifier with the highest priority
2409            if (priority < info.priority) {
2410                priority = info.priority;
2411                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2412                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2413                        + verifierComponentName + " with priority: " + info.priority);
2414            }
2415        }
2416
2417        return verifierComponentName;
2418    }
2419
2420    private void primeDomainVerificationsLPw(int userId) {
2421        if (DEBUG_DOMAIN_VERIFICATION) {
2422            Slog.d(TAG, "Priming domain verifications in user " + userId);
2423        }
2424
2425        SystemConfig systemConfig = SystemConfig.getInstance();
2426        ArraySet<String> packages = systemConfig.getLinkedApps();
2427        ArraySet<String> domains = new ArraySet<String>();
2428
2429        for (String packageName : packages) {
2430            PackageParser.Package pkg = mPackages.get(packageName);
2431            if (pkg != null) {
2432                if (!pkg.isSystemApp()) {
2433                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2434                    continue;
2435                }
2436
2437                domains.clear();
2438                for (PackageParser.Activity a : pkg.activities) {
2439                    for (ActivityIntentInfo filter : a.intents) {
2440                        if (hasValidDomains(filter)) {
2441                            domains.addAll(filter.getHostsList());
2442                        }
2443                    }
2444                }
2445
2446                if (domains.size() > 0) {
2447                    if (DEBUG_DOMAIN_VERIFICATION) {
2448                        Slog.v(TAG, "      + " + packageName);
2449                    }
2450                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2451                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2452                    // and then 'always' in the per-user state actually used for intent resolution.
2453                    final IntentFilterVerificationInfo ivi;
2454                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2455                            new ArrayList<String>(domains));
2456                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2457                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2458                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2459                } else {
2460                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2461                            + "' does not handle web links");
2462                }
2463            } else {
2464                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2465            }
2466        }
2467
2468        scheduleWritePackageRestrictionsLocked(userId);
2469        scheduleWriteSettingsLocked();
2470    }
2471
2472    private void applyFactoryDefaultBrowserLPw(int userId) {
2473        // The default browser app's package name is stored in a string resource,
2474        // with a product-specific overlay used for vendor customization.
2475        String browserPkg = mContext.getResources().getString(
2476                com.android.internal.R.string.default_browser);
2477        if (!TextUtils.isEmpty(browserPkg)) {
2478            // non-empty string => required to be a known package
2479            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2480            if (ps == null) {
2481                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2482                browserPkg = null;
2483            } else {
2484                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2485            }
2486        }
2487
2488        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2489        // default.  If there's more than one, just leave everything alone.
2490        if (browserPkg == null) {
2491            calculateDefaultBrowserLPw(userId);
2492        }
2493    }
2494
2495    private void calculateDefaultBrowserLPw(int userId) {
2496        List<String> allBrowsers = resolveAllBrowserApps(userId);
2497        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2498        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2499    }
2500
2501    private List<String> resolveAllBrowserApps(int userId) {
2502        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2503        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2504                PackageManager.MATCH_ALL, userId);
2505
2506        final int count = list.size();
2507        List<String> result = new ArrayList<String>(count);
2508        for (int i=0; i<count; i++) {
2509            ResolveInfo info = list.get(i);
2510            if (info.activityInfo == null
2511                    || !info.handleAllWebDataURI
2512                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2513                    || result.contains(info.activityInfo.packageName)) {
2514                continue;
2515            }
2516            result.add(info.activityInfo.packageName);
2517        }
2518
2519        return result;
2520    }
2521
2522    private boolean packageIsBrowser(String packageName, int userId) {
2523        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2524                PackageManager.MATCH_ALL, userId);
2525        final int N = list.size();
2526        for (int i = 0; i < N; i++) {
2527            ResolveInfo info = list.get(i);
2528            if (packageName.equals(info.activityInfo.packageName)) {
2529                return true;
2530            }
2531        }
2532        return false;
2533    }
2534
2535    private void checkDefaultBrowser() {
2536        final int myUserId = UserHandle.myUserId();
2537        final String packageName = getDefaultBrowserPackageName(myUserId);
2538        if (packageName != null) {
2539            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2540            if (info == null) {
2541                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2542                synchronized (mPackages) {
2543                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2544                }
2545            }
2546        }
2547    }
2548
2549    @Override
2550    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2551            throws RemoteException {
2552        try {
2553            return super.onTransact(code, data, reply, flags);
2554        } catch (RuntimeException e) {
2555            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2556                Slog.wtf(TAG, "Package Manager Crash", e);
2557            }
2558            throw e;
2559        }
2560    }
2561
2562    void cleanupInstallFailedPackage(PackageSetting ps) {
2563        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2564
2565        removeDataDirsLI(ps.volumeUuid, ps.name);
2566        if (ps.codePath != null) {
2567            if (ps.codePath.isDirectory()) {
2568                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2569            } else {
2570                ps.codePath.delete();
2571            }
2572        }
2573        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2574            if (ps.resourcePath.isDirectory()) {
2575                FileUtils.deleteContents(ps.resourcePath);
2576            }
2577            ps.resourcePath.delete();
2578        }
2579        mSettings.removePackageLPw(ps.name);
2580    }
2581
2582    static int[] appendInts(int[] cur, int[] add) {
2583        if (add == null) return cur;
2584        if (cur == null) return add;
2585        final int N = add.length;
2586        for (int i=0; i<N; i++) {
2587            cur = appendInt(cur, add[i]);
2588        }
2589        return cur;
2590    }
2591
2592    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2593        if (!sUserManager.exists(userId)) return null;
2594        final PackageSetting ps = (PackageSetting) p.mExtras;
2595        if (ps == null) {
2596            return null;
2597        }
2598
2599        final PermissionsState permissionsState = ps.getPermissionsState();
2600
2601        final int[] gids = permissionsState.computeGids(userId);
2602        final Set<String> permissions = permissionsState.getPermissions(userId);
2603        final PackageUserState state = ps.readUserState(userId);
2604
2605        return PackageParser.generatePackageInfo(p, gids, flags,
2606                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2607    }
2608
2609    @Override
2610    public boolean isPackageFrozen(String packageName) {
2611        synchronized (mPackages) {
2612            final PackageSetting ps = mSettings.mPackages.get(packageName);
2613            if (ps != null) {
2614                return ps.frozen;
2615            }
2616        }
2617        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2618        return true;
2619    }
2620
2621    @Override
2622    public boolean isPackageAvailable(String packageName, int userId) {
2623        if (!sUserManager.exists(userId)) return false;
2624        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2625        synchronized (mPackages) {
2626            PackageParser.Package p = mPackages.get(packageName);
2627            if (p != null) {
2628                final PackageSetting ps = (PackageSetting) p.mExtras;
2629                if (ps != null) {
2630                    final PackageUserState state = ps.readUserState(userId);
2631                    if (state != null) {
2632                        return PackageParser.isAvailable(state);
2633                    }
2634                }
2635            }
2636        }
2637        return false;
2638    }
2639
2640    @Override
2641    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2642        if (!sUserManager.exists(userId)) return null;
2643        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2644        // reader
2645        synchronized (mPackages) {
2646            PackageParser.Package p = mPackages.get(packageName);
2647            if (DEBUG_PACKAGE_INFO)
2648                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2649            if (p != null) {
2650                return generatePackageInfo(p, flags, userId);
2651            }
2652            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2653                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2654            }
2655        }
2656        return null;
2657    }
2658
2659    @Override
2660    public String[] currentToCanonicalPackageNames(String[] names) {
2661        String[] out = new String[names.length];
2662        // reader
2663        synchronized (mPackages) {
2664            for (int i=names.length-1; i>=0; i--) {
2665                PackageSetting ps = mSettings.mPackages.get(names[i]);
2666                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2667            }
2668        }
2669        return out;
2670    }
2671
2672    @Override
2673    public String[] canonicalToCurrentPackageNames(String[] names) {
2674        String[] out = new String[names.length];
2675        // reader
2676        synchronized (mPackages) {
2677            for (int i=names.length-1; i>=0; i--) {
2678                String cur = mSettings.mRenamedPackages.get(names[i]);
2679                out[i] = cur != null ? cur : names[i];
2680            }
2681        }
2682        return out;
2683    }
2684
2685    @Override
2686    public int getPackageUid(String packageName, int userId) {
2687        if (!sUserManager.exists(userId)) return -1;
2688        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2689
2690        // reader
2691        synchronized (mPackages) {
2692            PackageParser.Package p = mPackages.get(packageName);
2693            if(p != null) {
2694                return UserHandle.getUid(userId, p.applicationInfo.uid);
2695            }
2696            PackageSetting ps = mSettings.mPackages.get(packageName);
2697            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2698                return -1;
2699            }
2700            p = ps.pkg;
2701            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2702        }
2703    }
2704
2705    @Override
2706    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2707        if (!sUserManager.exists(userId)) {
2708            return null;
2709        }
2710
2711        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2712                "getPackageGids");
2713
2714        // reader
2715        synchronized (mPackages) {
2716            PackageParser.Package p = mPackages.get(packageName);
2717            if (DEBUG_PACKAGE_INFO) {
2718                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2719            }
2720            if (p != null) {
2721                PackageSetting ps = (PackageSetting) p.mExtras;
2722                return ps.getPermissionsState().computeGids(userId);
2723            }
2724        }
2725
2726        return null;
2727    }
2728
2729    @Override
2730    public int getMountExternalMode(int uid) {
2731        if (Process.isIsolated(uid)) {
2732            return Zygote.MOUNT_EXTERNAL_NONE;
2733        } else {
2734            if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
2735                return Zygote.MOUNT_EXTERNAL_DEFAULT;
2736            } else if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) {
2737                return Zygote.MOUNT_EXTERNAL_WRITE;
2738            } else if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) {
2739                return Zygote.MOUNT_EXTERNAL_READ;
2740            } else {
2741                return Zygote.MOUNT_EXTERNAL_DEFAULT;
2742            }
2743        }
2744    }
2745
2746    static PermissionInfo generatePermissionInfo(
2747            BasePermission bp, int flags) {
2748        if (bp.perm != null) {
2749            return PackageParser.generatePermissionInfo(bp.perm, flags);
2750        }
2751        PermissionInfo pi = new PermissionInfo();
2752        pi.name = bp.name;
2753        pi.packageName = bp.sourcePackage;
2754        pi.nonLocalizedLabel = bp.name;
2755        pi.protectionLevel = bp.protectionLevel;
2756        return pi;
2757    }
2758
2759    @Override
2760    public PermissionInfo getPermissionInfo(String name, int flags) {
2761        // reader
2762        synchronized (mPackages) {
2763            final BasePermission p = mSettings.mPermissions.get(name);
2764            if (p != null) {
2765                return generatePermissionInfo(p, flags);
2766            }
2767            return null;
2768        }
2769    }
2770
2771    @Override
2772    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2773        // reader
2774        synchronized (mPackages) {
2775            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2776            for (BasePermission p : mSettings.mPermissions.values()) {
2777                if (group == null) {
2778                    if (p.perm == null || p.perm.info.group == null) {
2779                        out.add(generatePermissionInfo(p, flags));
2780                    }
2781                } else {
2782                    if (p.perm != null && group.equals(p.perm.info.group)) {
2783                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2784                    }
2785                }
2786            }
2787
2788            if (out.size() > 0) {
2789                return out;
2790            }
2791            return mPermissionGroups.containsKey(group) ? out : null;
2792        }
2793    }
2794
2795    @Override
2796    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2797        // reader
2798        synchronized (mPackages) {
2799            return PackageParser.generatePermissionGroupInfo(
2800                    mPermissionGroups.get(name), flags);
2801        }
2802    }
2803
2804    @Override
2805    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2806        // reader
2807        synchronized (mPackages) {
2808            final int N = mPermissionGroups.size();
2809            ArrayList<PermissionGroupInfo> out
2810                    = new ArrayList<PermissionGroupInfo>(N);
2811            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2812                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2813            }
2814            return out;
2815        }
2816    }
2817
2818    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2819            int userId) {
2820        if (!sUserManager.exists(userId)) return null;
2821        PackageSetting ps = mSettings.mPackages.get(packageName);
2822        if (ps != null) {
2823            if (ps.pkg == null) {
2824                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2825                        flags, userId);
2826                if (pInfo != null) {
2827                    return pInfo.applicationInfo;
2828                }
2829                return null;
2830            }
2831            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2832                    ps.readUserState(userId), userId);
2833        }
2834        return null;
2835    }
2836
2837    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2838            int userId) {
2839        if (!sUserManager.exists(userId)) return null;
2840        PackageSetting ps = mSettings.mPackages.get(packageName);
2841        if (ps != null) {
2842            PackageParser.Package pkg = ps.pkg;
2843            if (pkg == null) {
2844                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2845                    return null;
2846                }
2847                // Only data remains, so we aren't worried about code paths
2848                pkg = new PackageParser.Package(packageName);
2849                pkg.applicationInfo.packageName = packageName;
2850                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2851                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2852                pkg.applicationInfo.dataDir = Environment
2853                        .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName)
2854                        .getAbsolutePath();
2855                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2856                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2857            }
2858            return generatePackageInfo(pkg, flags, userId);
2859        }
2860        return null;
2861    }
2862
2863    @Override
2864    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2865        if (!sUserManager.exists(userId)) return null;
2866        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2867        // writer
2868        synchronized (mPackages) {
2869            PackageParser.Package p = mPackages.get(packageName);
2870            if (DEBUG_PACKAGE_INFO) Log.v(
2871                    TAG, "getApplicationInfo " + packageName
2872                    + ": " + p);
2873            if (p != null) {
2874                PackageSetting ps = mSettings.mPackages.get(packageName);
2875                if (ps == null) return null;
2876                // Note: isEnabledLP() does not apply here - always return info
2877                return PackageParser.generateApplicationInfo(
2878                        p, flags, ps.readUserState(userId), userId);
2879            }
2880            if ("android".equals(packageName)||"system".equals(packageName)) {
2881                return mAndroidApplication;
2882            }
2883            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2884                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2885            }
2886        }
2887        return null;
2888    }
2889
2890    @Override
2891    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2892            final IPackageDataObserver observer) {
2893        mContext.enforceCallingOrSelfPermission(
2894                android.Manifest.permission.CLEAR_APP_CACHE, null);
2895        // Queue up an async operation since clearing cache may take a little while.
2896        mHandler.post(new Runnable() {
2897            public void run() {
2898                mHandler.removeCallbacks(this);
2899                int retCode = -1;
2900                synchronized (mInstallLock) {
2901                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2902                    if (retCode < 0) {
2903                        Slog.w(TAG, "Couldn't clear application caches");
2904                    }
2905                }
2906                if (observer != null) {
2907                    try {
2908                        observer.onRemoveCompleted(null, (retCode >= 0));
2909                    } catch (RemoteException e) {
2910                        Slog.w(TAG, "RemoveException when invoking call back");
2911                    }
2912                }
2913            }
2914        });
2915    }
2916
2917    @Override
2918    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2919            final IntentSender pi) {
2920        mContext.enforceCallingOrSelfPermission(
2921                android.Manifest.permission.CLEAR_APP_CACHE, null);
2922        // Queue up an async operation since clearing cache may take a little while.
2923        mHandler.post(new Runnable() {
2924            public void run() {
2925                mHandler.removeCallbacks(this);
2926                int retCode = -1;
2927                synchronized (mInstallLock) {
2928                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2929                    if (retCode < 0) {
2930                        Slog.w(TAG, "Couldn't clear application caches");
2931                    }
2932                }
2933                if(pi != null) {
2934                    try {
2935                        // Callback via pending intent
2936                        int code = (retCode >= 0) ? 1 : 0;
2937                        pi.sendIntent(null, code, null,
2938                                null, null);
2939                    } catch (SendIntentException e1) {
2940                        Slog.i(TAG, "Failed to send pending intent");
2941                    }
2942                }
2943            }
2944        });
2945    }
2946
2947    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2948        synchronized (mInstallLock) {
2949            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2950                throw new IOException("Failed to free enough space");
2951            }
2952        }
2953    }
2954
2955    @Override
2956    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2957        if (!sUserManager.exists(userId)) return null;
2958        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2959        synchronized (mPackages) {
2960            PackageParser.Activity a = mActivities.mActivities.get(component);
2961
2962            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2963            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2964                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2965                if (ps == null) return null;
2966                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2967                        userId);
2968            }
2969            if (mResolveComponentName.equals(component)) {
2970                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2971                        new PackageUserState(), userId);
2972            }
2973        }
2974        return null;
2975    }
2976
2977    @Override
2978    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2979            String resolvedType) {
2980        synchronized (mPackages) {
2981            PackageParser.Activity a = mActivities.mActivities.get(component);
2982            if (a == null) {
2983                return false;
2984            }
2985            for (int i=0; i<a.intents.size(); i++) {
2986                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2987                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2988                    return true;
2989                }
2990            }
2991            return false;
2992        }
2993    }
2994
2995    @Override
2996    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2997        if (!sUserManager.exists(userId)) return null;
2998        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2999        synchronized (mPackages) {
3000            PackageParser.Activity a = mReceivers.mActivities.get(component);
3001            if (DEBUG_PACKAGE_INFO) Log.v(
3002                TAG, "getReceiverInfo " + component + ": " + a);
3003            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
3004                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3005                if (ps == null) return null;
3006                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3007                        userId);
3008            }
3009        }
3010        return null;
3011    }
3012
3013    @Override
3014    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3015        if (!sUserManager.exists(userId)) return null;
3016        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3017        synchronized (mPackages) {
3018            PackageParser.Service s = mServices.mServices.get(component);
3019            if (DEBUG_PACKAGE_INFO) Log.v(
3020                TAG, "getServiceInfo " + component + ": " + s);
3021            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
3022                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3023                if (ps == null) return null;
3024                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3025                        userId);
3026            }
3027        }
3028        return null;
3029    }
3030
3031    @Override
3032    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3033        if (!sUserManager.exists(userId)) return null;
3034        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3035        synchronized (mPackages) {
3036            PackageParser.Provider p = mProviders.mProviders.get(component);
3037            if (DEBUG_PACKAGE_INFO) Log.v(
3038                TAG, "getProviderInfo " + component + ": " + p);
3039            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
3040                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3041                if (ps == null) return null;
3042                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3043                        userId);
3044            }
3045        }
3046        return null;
3047    }
3048
3049    @Override
3050    public String[] getSystemSharedLibraryNames() {
3051        Set<String> libSet;
3052        synchronized (mPackages) {
3053            libSet = mSharedLibraries.keySet();
3054            int size = libSet.size();
3055            if (size > 0) {
3056                String[] libs = new String[size];
3057                libSet.toArray(libs);
3058                return libs;
3059            }
3060        }
3061        return null;
3062    }
3063
3064    /**
3065     * @hide
3066     */
3067    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3068        synchronized (mPackages) {
3069            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3070            if (lib != null && lib.apk != null) {
3071                return mPackages.get(lib.apk);
3072            }
3073        }
3074        return null;
3075    }
3076
3077    @Override
3078    public FeatureInfo[] getSystemAvailableFeatures() {
3079        Collection<FeatureInfo> featSet;
3080        synchronized (mPackages) {
3081            featSet = mAvailableFeatures.values();
3082            int size = featSet.size();
3083            if (size > 0) {
3084                FeatureInfo[] features = new FeatureInfo[size+1];
3085                featSet.toArray(features);
3086                FeatureInfo fi = new FeatureInfo();
3087                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3088                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3089                features[size] = fi;
3090                return features;
3091            }
3092        }
3093        return null;
3094    }
3095
3096    @Override
3097    public boolean hasSystemFeature(String name) {
3098        synchronized (mPackages) {
3099            return mAvailableFeatures.containsKey(name);
3100        }
3101    }
3102
3103    private void checkValidCaller(int uid, int userId) {
3104        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3105            return;
3106
3107        throw new SecurityException("Caller uid=" + uid
3108                + " is not privileged to communicate with user=" + userId);
3109    }
3110
3111    @Override
3112    public int checkPermission(String permName, String pkgName, int userId) {
3113        if (!sUserManager.exists(userId)) {
3114            return PackageManager.PERMISSION_DENIED;
3115        }
3116
3117        synchronized (mPackages) {
3118            final PackageParser.Package p = mPackages.get(pkgName);
3119            if (p != null && p.mExtras != null) {
3120                final PackageSetting ps = (PackageSetting) p.mExtras;
3121                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3122                    return PackageManager.PERMISSION_GRANTED;
3123                }
3124            }
3125        }
3126
3127        return PackageManager.PERMISSION_DENIED;
3128    }
3129
3130    @Override
3131    public int checkUidPermission(String permName, int uid) {
3132        final int userId = UserHandle.getUserId(uid);
3133
3134        if (!sUserManager.exists(userId)) {
3135            return PackageManager.PERMISSION_DENIED;
3136        }
3137
3138        synchronized (mPackages) {
3139            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3140            if (obj != null) {
3141                final SettingBase ps = (SettingBase) obj;
3142                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3143                    return PackageManager.PERMISSION_GRANTED;
3144                }
3145            } else {
3146                ArraySet<String> perms = mSystemPermissions.get(uid);
3147                if (perms != null && perms.contains(permName)) {
3148                    return PackageManager.PERMISSION_GRANTED;
3149                }
3150            }
3151        }
3152
3153        return PackageManager.PERMISSION_DENIED;
3154    }
3155
3156    @Override
3157    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3158        if (UserHandle.getCallingUserId() != userId) {
3159            mContext.enforceCallingPermission(
3160                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3161                    "isPermissionRevokedByPolicy for user " + userId);
3162        }
3163
3164        if (checkPermission(permission, packageName, userId)
3165                == PackageManager.PERMISSION_GRANTED) {
3166            return false;
3167        }
3168
3169        final long identity = Binder.clearCallingIdentity();
3170        try {
3171            final int flags = getPermissionFlags(permission, packageName, userId);
3172            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3173        } finally {
3174            Binder.restoreCallingIdentity(identity);
3175        }
3176    }
3177
3178    /**
3179     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3180     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3181     * @param checkShell TODO(yamasani):
3182     * @param message the message to log on security exception
3183     */
3184    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3185            boolean checkShell, String message) {
3186        if (userId < 0) {
3187            throw new IllegalArgumentException("Invalid userId " + userId);
3188        }
3189        if (checkShell) {
3190            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3191        }
3192        if (userId == UserHandle.getUserId(callingUid)) return;
3193        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3194            if (requireFullPermission) {
3195                mContext.enforceCallingOrSelfPermission(
3196                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3197            } else {
3198                try {
3199                    mContext.enforceCallingOrSelfPermission(
3200                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3201                } catch (SecurityException se) {
3202                    mContext.enforceCallingOrSelfPermission(
3203                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3204                }
3205            }
3206        }
3207    }
3208
3209    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3210        if (callingUid == Process.SHELL_UID) {
3211            if (userHandle >= 0
3212                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3213                throw new SecurityException("Shell does not have permission to access user "
3214                        + userHandle);
3215            } else if (userHandle < 0) {
3216                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3217                        + Debug.getCallers(3));
3218            }
3219        }
3220    }
3221
3222    private BasePermission findPermissionTreeLP(String permName) {
3223        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3224            if (permName.startsWith(bp.name) &&
3225                    permName.length() > bp.name.length() &&
3226                    permName.charAt(bp.name.length()) == '.') {
3227                return bp;
3228            }
3229        }
3230        return null;
3231    }
3232
3233    private BasePermission checkPermissionTreeLP(String permName) {
3234        if (permName != null) {
3235            BasePermission bp = findPermissionTreeLP(permName);
3236            if (bp != null) {
3237                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3238                    return bp;
3239                }
3240                throw new SecurityException("Calling uid "
3241                        + Binder.getCallingUid()
3242                        + " is not allowed to add to permission tree "
3243                        + bp.name + " owned by uid " + bp.uid);
3244            }
3245        }
3246        throw new SecurityException("No permission tree found for " + permName);
3247    }
3248
3249    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3250        if (s1 == null) {
3251            return s2 == null;
3252        }
3253        if (s2 == null) {
3254            return false;
3255        }
3256        if (s1.getClass() != s2.getClass()) {
3257            return false;
3258        }
3259        return s1.equals(s2);
3260    }
3261
3262    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3263        if (pi1.icon != pi2.icon) return false;
3264        if (pi1.logo != pi2.logo) return false;
3265        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3266        if (!compareStrings(pi1.name, pi2.name)) return false;
3267        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3268        // We'll take care of setting this one.
3269        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3270        // These are not currently stored in settings.
3271        //if (!compareStrings(pi1.group, pi2.group)) return false;
3272        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3273        //if (pi1.labelRes != pi2.labelRes) return false;
3274        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3275        return true;
3276    }
3277
3278    int permissionInfoFootprint(PermissionInfo info) {
3279        int size = info.name.length();
3280        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3281        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3282        return size;
3283    }
3284
3285    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3286        int size = 0;
3287        for (BasePermission perm : mSettings.mPermissions.values()) {
3288            if (perm.uid == tree.uid) {
3289                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3290            }
3291        }
3292        return size;
3293    }
3294
3295    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3296        // We calculate the max size of permissions defined by this uid and throw
3297        // if that plus the size of 'info' would exceed our stated maximum.
3298        if (tree.uid != Process.SYSTEM_UID) {
3299            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3300            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3301                throw new SecurityException("Permission tree size cap exceeded");
3302            }
3303        }
3304    }
3305
3306    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3307        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3308            throw new SecurityException("Label must be specified in permission");
3309        }
3310        BasePermission tree = checkPermissionTreeLP(info.name);
3311        BasePermission bp = mSettings.mPermissions.get(info.name);
3312        boolean added = bp == null;
3313        boolean changed = true;
3314        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3315        if (added) {
3316            enforcePermissionCapLocked(info, tree);
3317            bp = new BasePermission(info.name, tree.sourcePackage,
3318                    BasePermission.TYPE_DYNAMIC);
3319        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3320            throw new SecurityException(
3321                    "Not allowed to modify non-dynamic permission "
3322                    + info.name);
3323        } else {
3324            if (bp.protectionLevel == fixedLevel
3325                    && bp.perm.owner.equals(tree.perm.owner)
3326                    && bp.uid == tree.uid
3327                    && comparePermissionInfos(bp.perm.info, info)) {
3328                changed = false;
3329            }
3330        }
3331        bp.protectionLevel = fixedLevel;
3332        info = new PermissionInfo(info);
3333        info.protectionLevel = fixedLevel;
3334        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3335        bp.perm.info.packageName = tree.perm.info.packageName;
3336        bp.uid = tree.uid;
3337        if (added) {
3338            mSettings.mPermissions.put(info.name, bp);
3339        }
3340        if (changed) {
3341            if (!async) {
3342                mSettings.writeLPr();
3343            } else {
3344                scheduleWriteSettingsLocked();
3345            }
3346        }
3347        return added;
3348    }
3349
3350    @Override
3351    public boolean addPermission(PermissionInfo info) {
3352        synchronized (mPackages) {
3353            return addPermissionLocked(info, false);
3354        }
3355    }
3356
3357    @Override
3358    public boolean addPermissionAsync(PermissionInfo info) {
3359        synchronized (mPackages) {
3360            return addPermissionLocked(info, true);
3361        }
3362    }
3363
3364    @Override
3365    public void removePermission(String name) {
3366        synchronized (mPackages) {
3367            checkPermissionTreeLP(name);
3368            BasePermission bp = mSettings.mPermissions.get(name);
3369            if (bp != null) {
3370                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3371                    throw new SecurityException(
3372                            "Not allowed to modify non-dynamic permission "
3373                            + name);
3374                }
3375                mSettings.mPermissions.remove(name);
3376                mSettings.writeLPr();
3377            }
3378        }
3379    }
3380
3381    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3382            BasePermission bp) {
3383        int index = pkg.requestedPermissions.indexOf(bp.name);
3384        if (index == -1) {
3385            throw new SecurityException("Package " + pkg.packageName
3386                    + " has not requested permission " + bp.name);
3387        }
3388        if (!bp.isRuntime()) {
3389            throw new SecurityException("Permission " + bp.name
3390                    + " is not a changeable permission type");
3391        }
3392    }
3393
3394    @Override
3395    public void grantRuntimePermission(String packageName, String name, final int userId) {
3396        if (!sUserManager.exists(userId)) {
3397            Log.e(TAG, "No such user:" + userId);
3398            return;
3399        }
3400
3401        mContext.enforceCallingOrSelfPermission(
3402                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3403                "grantRuntimePermission");
3404
3405        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3406                "grantRuntimePermission");
3407
3408        final int uid;
3409        final SettingBase sb;
3410
3411        synchronized (mPackages) {
3412            final PackageParser.Package pkg = mPackages.get(packageName);
3413            if (pkg == null) {
3414                throw new IllegalArgumentException("Unknown package: " + packageName);
3415            }
3416
3417            final BasePermission bp = mSettings.mPermissions.get(name);
3418            if (bp == null) {
3419                throw new IllegalArgumentException("Unknown permission: " + name);
3420            }
3421
3422            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3423
3424            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3425            sb = (SettingBase) pkg.mExtras;
3426            if (sb == null) {
3427                throw new IllegalArgumentException("Unknown package: " + packageName);
3428            }
3429
3430            final PermissionsState permissionsState = sb.getPermissionsState();
3431
3432            final int flags = permissionsState.getPermissionFlags(name, userId);
3433            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3434                throw new SecurityException("Cannot grant system fixed permission: "
3435                        + name + " for package: " + packageName);
3436            }
3437
3438            final int result = permissionsState.grantRuntimePermission(bp, userId);
3439            switch (result) {
3440                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3441                    return;
3442                }
3443
3444                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3445                    mHandler.post(new Runnable() {
3446                        @Override
3447                        public void run() {
3448                            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3449                        }
3450                    });
3451                } break;
3452            }
3453
3454            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3455
3456            // Not critical if that is lost - app has to request again.
3457            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3458        }
3459
3460        // Only need to do this if user is initialized. Otherwise it's a new user
3461        // and there are no processes running as the user yet and there's no need
3462        // to make an expensive call to remount processes for the changed permissions.
3463        if (READ_EXTERNAL_STORAGE.equals(name)
3464                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3465            final long token = Binder.clearCallingIdentity();
3466            try {
3467                if (sUserManager.isInitialized(userId)) {
3468                    final StorageManager storage = mContext.getSystemService(StorageManager.class);
3469                    storage.remountUid(uid);
3470                }
3471            } finally {
3472                Binder.restoreCallingIdentity(token);
3473            }
3474        }
3475    }
3476
3477    @Override
3478    public void revokeRuntimePermission(String packageName, String name, int userId) {
3479        if (!sUserManager.exists(userId)) {
3480            Log.e(TAG, "No such user:" + userId);
3481            return;
3482        }
3483
3484        mContext.enforceCallingOrSelfPermission(
3485                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3486                "revokeRuntimePermission");
3487
3488        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3489                "revokeRuntimePermission");
3490
3491        final SettingBase sb;
3492
3493        synchronized (mPackages) {
3494            final PackageParser.Package pkg = mPackages.get(packageName);
3495            if (pkg == null) {
3496                throw new IllegalArgumentException("Unknown package: " + packageName);
3497            }
3498
3499            final BasePermission bp = mSettings.mPermissions.get(name);
3500            if (bp == null) {
3501                throw new IllegalArgumentException("Unknown permission: " + name);
3502            }
3503
3504            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3505
3506            sb = (SettingBase) pkg.mExtras;
3507            if (sb == null) {
3508                throw new IllegalArgumentException("Unknown package: " + packageName);
3509            }
3510
3511            final PermissionsState permissionsState = sb.getPermissionsState();
3512
3513            final int flags = permissionsState.getPermissionFlags(name, userId);
3514            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3515                throw new SecurityException("Cannot revoke system fixed permission: "
3516                        + name + " for package: " + packageName);
3517            }
3518
3519            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3520                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3521                return;
3522            }
3523
3524            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3525
3526            // Critical, after this call app should never have the permission.
3527            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3528        }
3529
3530        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3531    }
3532
3533    @Override
3534    public void resetRuntimePermissions() {
3535        mContext.enforceCallingOrSelfPermission(
3536                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3537                "revokeRuntimePermission");
3538
3539        int callingUid = Binder.getCallingUid();
3540        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3541            mContext.enforceCallingOrSelfPermission(
3542                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3543                    "resetRuntimePermissions");
3544        }
3545
3546        final int[] userIds;
3547
3548        synchronized (mPackages) {
3549            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3550            final int userCount = UserManagerService.getInstance().getUserIds().length;
3551            userIds = Arrays.copyOf(UserManagerService.getInstance().getUserIds(), userCount);
3552        }
3553
3554        for (int userId : userIds) {
3555            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
3556        }
3557    }
3558
3559    @Override
3560    public int getPermissionFlags(String name, String packageName, int userId) {
3561        if (!sUserManager.exists(userId)) {
3562            return 0;
3563        }
3564
3565        mContext.enforceCallingOrSelfPermission(
3566                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3567                "getPermissionFlags");
3568
3569        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3570                "getPermissionFlags");
3571
3572        synchronized (mPackages) {
3573            final PackageParser.Package pkg = mPackages.get(packageName);
3574            if (pkg == null) {
3575                throw new IllegalArgumentException("Unknown package: " + packageName);
3576            }
3577
3578            final BasePermission bp = mSettings.mPermissions.get(name);
3579            if (bp == null) {
3580                throw new IllegalArgumentException("Unknown permission: " + name);
3581            }
3582
3583            SettingBase sb = (SettingBase) pkg.mExtras;
3584            if (sb == null) {
3585                throw new IllegalArgumentException("Unknown package: " + packageName);
3586            }
3587
3588            PermissionsState permissionsState = sb.getPermissionsState();
3589            return permissionsState.getPermissionFlags(name, userId);
3590        }
3591    }
3592
3593    @Override
3594    public void updatePermissionFlags(String name, String packageName, int flagMask,
3595            int flagValues, int userId) {
3596        if (!sUserManager.exists(userId)) {
3597            return;
3598        }
3599
3600        mContext.enforceCallingOrSelfPermission(
3601                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3602                "updatePermissionFlags");
3603
3604        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3605                "updatePermissionFlags");
3606
3607        // Only the system can change system fixed flags.
3608        if (getCallingUid() != Process.SYSTEM_UID) {
3609            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3610            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3611        }
3612
3613        synchronized (mPackages) {
3614            final PackageParser.Package pkg = mPackages.get(packageName);
3615            if (pkg == null) {
3616                throw new IllegalArgumentException("Unknown package: " + packageName);
3617            }
3618
3619            final BasePermission bp = mSettings.mPermissions.get(name);
3620            if (bp == null) {
3621                throw new IllegalArgumentException("Unknown permission: " + name);
3622            }
3623
3624            SettingBase sb = (SettingBase) pkg.mExtras;
3625            if (sb == null) {
3626                throw new IllegalArgumentException("Unknown package: " + packageName);
3627            }
3628
3629            PermissionsState permissionsState = sb.getPermissionsState();
3630
3631            // Only the package manager can change flags for system component permissions.
3632            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3633            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3634                return;
3635            }
3636
3637            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3638
3639            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3640                // Install and runtime permissions are stored in different places,
3641                // so figure out what permission changed and persist the change.
3642                if (permissionsState.getInstallPermissionState(name) != null) {
3643                    scheduleWriteSettingsLocked();
3644                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3645                        || hadState) {
3646                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3647                }
3648            }
3649        }
3650    }
3651
3652    /**
3653     * Update the permission flags for all packages and runtime permissions of a user in order
3654     * to allow device or profile owner to remove POLICY_FIXED.
3655     */
3656    @Override
3657    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3658        if (!sUserManager.exists(userId)) {
3659            return;
3660        }
3661
3662        mContext.enforceCallingOrSelfPermission(
3663                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3664                "updatePermissionFlagsForAllApps");
3665
3666        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3667                "updatePermissionFlagsForAllApps");
3668
3669        // Only the system can change system fixed flags.
3670        if (getCallingUid() != Process.SYSTEM_UID) {
3671            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3672            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3673        }
3674
3675        synchronized (mPackages) {
3676            boolean changed = false;
3677            final int packageCount = mPackages.size();
3678            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3679                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3680                SettingBase sb = (SettingBase) pkg.mExtras;
3681                if (sb == null) {
3682                    continue;
3683                }
3684                PermissionsState permissionsState = sb.getPermissionsState();
3685                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3686                        userId, flagMask, flagValues);
3687            }
3688            if (changed) {
3689                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3690            }
3691        }
3692    }
3693
3694    @Override
3695    public boolean shouldShowRequestPermissionRationale(String permissionName,
3696            String packageName, int userId) {
3697        if (UserHandle.getCallingUserId() != userId) {
3698            mContext.enforceCallingPermission(
3699                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3700                    "canShowRequestPermissionRationale for user " + userId);
3701        }
3702
3703        final int uid = getPackageUid(packageName, userId);
3704        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3705            return false;
3706        }
3707
3708        if (checkPermission(permissionName, packageName, userId)
3709                == PackageManager.PERMISSION_GRANTED) {
3710            return false;
3711        }
3712
3713        final int flags;
3714
3715        final long identity = Binder.clearCallingIdentity();
3716        try {
3717            flags = getPermissionFlags(permissionName,
3718                    packageName, userId);
3719        } finally {
3720            Binder.restoreCallingIdentity(identity);
3721        }
3722
3723        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3724                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3725                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3726
3727        if ((flags & fixedFlags) != 0) {
3728            return false;
3729        }
3730
3731        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3732    }
3733
3734    void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) {
3735        BasePermission bp = mSettings.mPermissions.get(permission);
3736        if (bp == null) {
3737            throw new SecurityException("Missing " + permission + " permission");
3738        }
3739
3740        SettingBase sb = (SettingBase) pkg.mExtras;
3741        PermissionsState permissionsState = sb.getPermissionsState();
3742
3743        if (permissionsState.grantInstallPermission(bp) !=
3744                PermissionsState.PERMISSION_OPERATION_FAILURE) {
3745            scheduleWriteSettingsLocked();
3746        }
3747    }
3748
3749    @Override
3750    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3751        mContext.enforceCallingOrSelfPermission(
3752                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3753                "addOnPermissionsChangeListener");
3754
3755        synchronized (mPackages) {
3756            mOnPermissionChangeListeners.addListenerLocked(listener);
3757        }
3758    }
3759
3760    @Override
3761    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3762        synchronized (mPackages) {
3763            mOnPermissionChangeListeners.removeListenerLocked(listener);
3764        }
3765    }
3766
3767    @Override
3768    public boolean isProtectedBroadcast(String actionName) {
3769        synchronized (mPackages) {
3770            return mProtectedBroadcasts.contains(actionName);
3771        }
3772    }
3773
3774    @Override
3775    public int checkSignatures(String pkg1, String pkg2) {
3776        synchronized (mPackages) {
3777            final PackageParser.Package p1 = mPackages.get(pkg1);
3778            final PackageParser.Package p2 = mPackages.get(pkg2);
3779            if (p1 == null || p1.mExtras == null
3780                    || p2 == null || p2.mExtras == null) {
3781                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3782            }
3783            return compareSignatures(p1.mSignatures, p2.mSignatures);
3784        }
3785    }
3786
3787    @Override
3788    public int checkUidSignatures(int uid1, int uid2) {
3789        // Map to base uids.
3790        uid1 = UserHandle.getAppId(uid1);
3791        uid2 = UserHandle.getAppId(uid2);
3792        // reader
3793        synchronized (mPackages) {
3794            Signature[] s1;
3795            Signature[] s2;
3796            Object obj = mSettings.getUserIdLPr(uid1);
3797            if (obj != null) {
3798                if (obj instanceof SharedUserSetting) {
3799                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3800                } else if (obj instanceof PackageSetting) {
3801                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3802                } else {
3803                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3804                }
3805            } else {
3806                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3807            }
3808            obj = mSettings.getUserIdLPr(uid2);
3809            if (obj != null) {
3810                if (obj instanceof SharedUserSetting) {
3811                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3812                } else if (obj instanceof PackageSetting) {
3813                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3814                } else {
3815                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3816                }
3817            } else {
3818                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3819            }
3820            return compareSignatures(s1, s2);
3821        }
3822    }
3823
3824    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3825        final long identity = Binder.clearCallingIdentity();
3826        try {
3827            if (sb instanceof SharedUserSetting) {
3828                SharedUserSetting sus = (SharedUserSetting) sb;
3829                final int packageCount = sus.packages.size();
3830                for (int i = 0; i < packageCount; i++) {
3831                    PackageSetting susPs = sus.packages.valueAt(i);
3832                    if (userId == UserHandle.USER_ALL) {
3833                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3834                    } else {
3835                        final int uid = UserHandle.getUid(userId, susPs.appId);
3836                        killUid(uid, reason);
3837                    }
3838                }
3839            } else if (sb instanceof PackageSetting) {
3840                PackageSetting ps = (PackageSetting) sb;
3841                if (userId == UserHandle.USER_ALL) {
3842                    killApplication(ps.pkg.packageName, ps.appId, reason);
3843                } else {
3844                    final int uid = UserHandle.getUid(userId, ps.appId);
3845                    killUid(uid, reason);
3846                }
3847            }
3848        } finally {
3849            Binder.restoreCallingIdentity(identity);
3850        }
3851    }
3852
3853    private static void killUid(int uid, String reason) {
3854        IActivityManager am = ActivityManagerNative.getDefault();
3855        if (am != null) {
3856            try {
3857                am.killUid(uid, reason);
3858            } catch (RemoteException e) {
3859                /* ignore - same process */
3860            }
3861        }
3862    }
3863
3864    /**
3865     * Compares two sets of signatures. Returns:
3866     * <br />
3867     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3868     * <br />
3869     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3870     * <br />
3871     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3872     * <br />
3873     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3874     * <br />
3875     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3876     */
3877    static int compareSignatures(Signature[] s1, Signature[] s2) {
3878        if (s1 == null) {
3879            return s2 == null
3880                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3881                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3882        }
3883
3884        if (s2 == null) {
3885            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3886        }
3887
3888        if (s1.length != s2.length) {
3889            return PackageManager.SIGNATURE_NO_MATCH;
3890        }
3891
3892        // Since both signature sets are of size 1, we can compare without HashSets.
3893        if (s1.length == 1) {
3894            return s1[0].equals(s2[0]) ?
3895                    PackageManager.SIGNATURE_MATCH :
3896                    PackageManager.SIGNATURE_NO_MATCH;
3897        }
3898
3899        ArraySet<Signature> set1 = new ArraySet<Signature>();
3900        for (Signature sig : s1) {
3901            set1.add(sig);
3902        }
3903        ArraySet<Signature> set2 = new ArraySet<Signature>();
3904        for (Signature sig : s2) {
3905            set2.add(sig);
3906        }
3907        // Make sure s2 contains all signatures in s1.
3908        if (set1.equals(set2)) {
3909            return PackageManager.SIGNATURE_MATCH;
3910        }
3911        return PackageManager.SIGNATURE_NO_MATCH;
3912    }
3913
3914    /**
3915     * If the database version for this type of package (internal storage or
3916     * external storage) is less than the version where package signatures
3917     * were updated, return true.
3918     */
3919    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3920        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3921                DatabaseVersion.SIGNATURE_END_ENTITY))
3922                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3923                        DatabaseVersion.SIGNATURE_END_ENTITY));
3924    }
3925
3926    /**
3927     * Used for backward compatibility to make sure any packages with
3928     * certificate chains get upgraded to the new style. {@code existingSigs}
3929     * will be in the old format (since they were stored on disk from before the
3930     * system upgrade) and {@code scannedSigs} will be in the newer format.
3931     */
3932    private int compareSignaturesCompat(PackageSignatures existingSigs,
3933            PackageParser.Package scannedPkg) {
3934        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3935            return PackageManager.SIGNATURE_NO_MATCH;
3936        }
3937
3938        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3939        for (Signature sig : existingSigs.mSignatures) {
3940            existingSet.add(sig);
3941        }
3942        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3943        for (Signature sig : scannedPkg.mSignatures) {
3944            try {
3945                Signature[] chainSignatures = sig.getChainSignatures();
3946                for (Signature chainSig : chainSignatures) {
3947                    scannedCompatSet.add(chainSig);
3948                }
3949            } catch (CertificateEncodingException e) {
3950                scannedCompatSet.add(sig);
3951            }
3952        }
3953        /*
3954         * Make sure the expanded scanned set contains all signatures in the
3955         * existing one.
3956         */
3957        if (scannedCompatSet.equals(existingSet)) {
3958            // Migrate the old signatures to the new scheme.
3959            existingSigs.assignSignatures(scannedPkg.mSignatures);
3960            // The new KeySets will be re-added later in the scanning process.
3961            synchronized (mPackages) {
3962                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3963            }
3964            return PackageManager.SIGNATURE_MATCH;
3965        }
3966        return PackageManager.SIGNATURE_NO_MATCH;
3967    }
3968
3969    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3970        if (isExternal(scannedPkg)) {
3971            return mSettings.isExternalDatabaseVersionOlderThan(
3972                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3973        } else {
3974            return mSettings.isInternalDatabaseVersionOlderThan(
3975                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3976        }
3977    }
3978
3979    private int compareSignaturesRecover(PackageSignatures existingSigs,
3980            PackageParser.Package scannedPkg) {
3981        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3982            return PackageManager.SIGNATURE_NO_MATCH;
3983        }
3984
3985        String msg = null;
3986        try {
3987            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3988                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3989                        + scannedPkg.packageName);
3990                return PackageManager.SIGNATURE_MATCH;
3991            }
3992        } catch (CertificateException e) {
3993            msg = e.getMessage();
3994        }
3995
3996        logCriticalInfo(Log.INFO,
3997                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3998        return PackageManager.SIGNATURE_NO_MATCH;
3999    }
4000
4001    @Override
4002    public String[] getPackagesForUid(int uid) {
4003        uid = UserHandle.getAppId(uid);
4004        // reader
4005        synchronized (mPackages) {
4006            Object obj = mSettings.getUserIdLPr(uid);
4007            if (obj instanceof SharedUserSetting) {
4008                final SharedUserSetting sus = (SharedUserSetting) obj;
4009                final int N = sus.packages.size();
4010                final String[] res = new String[N];
4011                final Iterator<PackageSetting> it = sus.packages.iterator();
4012                int i = 0;
4013                while (it.hasNext()) {
4014                    res[i++] = it.next().name;
4015                }
4016                return res;
4017            } else if (obj instanceof PackageSetting) {
4018                final PackageSetting ps = (PackageSetting) obj;
4019                return new String[] { ps.name };
4020            }
4021        }
4022        return null;
4023    }
4024
4025    @Override
4026    public String getNameForUid(int uid) {
4027        // reader
4028        synchronized (mPackages) {
4029            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4030            if (obj instanceof SharedUserSetting) {
4031                final SharedUserSetting sus = (SharedUserSetting) obj;
4032                return sus.name + ":" + sus.userId;
4033            } else if (obj instanceof PackageSetting) {
4034                final PackageSetting ps = (PackageSetting) obj;
4035                return ps.name;
4036            }
4037        }
4038        return null;
4039    }
4040
4041    @Override
4042    public int getUidForSharedUser(String sharedUserName) {
4043        if(sharedUserName == null) {
4044            return -1;
4045        }
4046        // reader
4047        synchronized (mPackages) {
4048            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4049            if (suid == null) {
4050                return -1;
4051            }
4052            return suid.userId;
4053        }
4054    }
4055
4056    @Override
4057    public int getFlagsForUid(int uid) {
4058        synchronized (mPackages) {
4059            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4060            if (obj instanceof SharedUserSetting) {
4061                final SharedUserSetting sus = (SharedUserSetting) obj;
4062                return sus.pkgFlags;
4063            } else if (obj instanceof PackageSetting) {
4064                final PackageSetting ps = (PackageSetting) obj;
4065                return ps.pkgFlags;
4066            }
4067        }
4068        return 0;
4069    }
4070
4071    @Override
4072    public int getPrivateFlagsForUid(int uid) {
4073        synchronized (mPackages) {
4074            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4075            if (obj instanceof SharedUserSetting) {
4076                final SharedUserSetting sus = (SharedUserSetting) obj;
4077                return sus.pkgPrivateFlags;
4078            } else if (obj instanceof PackageSetting) {
4079                final PackageSetting ps = (PackageSetting) obj;
4080                return ps.pkgPrivateFlags;
4081            }
4082        }
4083        return 0;
4084    }
4085
4086    @Override
4087    public boolean isUidPrivileged(int uid) {
4088        uid = UserHandle.getAppId(uid);
4089        // reader
4090        synchronized (mPackages) {
4091            Object obj = mSettings.getUserIdLPr(uid);
4092            if (obj instanceof SharedUserSetting) {
4093                final SharedUserSetting sus = (SharedUserSetting) obj;
4094                final Iterator<PackageSetting> it = sus.packages.iterator();
4095                while (it.hasNext()) {
4096                    if (it.next().isPrivileged()) {
4097                        return true;
4098                    }
4099                }
4100            } else if (obj instanceof PackageSetting) {
4101                final PackageSetting ps = (PackageSetting) obj;
4102                return ps.isPrivileged();
4103            }
4104        }
4105        return false;
4106    }
4107
4108    @Override
4109    public String[] getAppOpPermissionPackages(String permissionName) {
4110        synchronized (mPackages) {
4111            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4112            if (pkgs == null) {
4113                return null;
4114            }
4115            return pkgs.toArray(new String[pkgs.size()]);
4116        }
4117    }
4118
4119    @Override
4120    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4121            int flags, int userId) {
4122        if (!sUserManager.exists(userId)) return null;
4123        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4124        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4125        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4126    }
4127
4128    @Override
4129    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4130            IntentFilter filter, int match, ComponentName activity) {
4131        final int userId = UserHandle.getCallingUserId();
4132        if (DEBUG_PREFERRED) {
4133            Log.v(TAG, "setLastChosenActivity intent=" + intent
4134                + " resolvedType=" + resolvedType
4135                + " flags=" + flags
4136                + " filter=" + filter
4137                + " match=" + match
4138                + " activity=" + activity);
4139            filter.dump(new PrintStreamPrinter(System.out), "    ");
4140        }
4141        intent.setComponent(null);
4142        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4143        // Find any earlier preferred or last chosen entries and nuke them
4144        findPreferredActivity(intent, resolvedType,
4145                flags, query, 0, false, true, false, userId);
4146        // Add the new activity as the last chosen for this filter
4147        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4148                "Setting last chosen");
4149    }
4150
4151    @Override
4152    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4153        final int userId = UserHandle.getCallingUserId();
4154        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4155        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4156        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4157                false, false, false, userId);
4158    }
4159
4160    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4161            int flags, List<ResolveInfo> query, int userId) {
4162        if (query != null) {
4163            final int N = query.size();
4164            if (N == 1) {
4165                return query.get(0);
4166            } else if (N > 1) {
4167                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4168                // If there is more than one activity with the same priority,
4169                // then let the user decide between them.
4170                ResolveInfo r0 = query.get(0);
4171                ResolveInfo r1 = query.get(1);
4172                if (DEBUG_INTENT_MATCHING || debug) {
4173                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4174                            + r1.activityInfo.name + "=" + r1.priority);
4175                }
4176                // If the first activity has a higher priority, or a different
4177                // default, then it is always desireable to pick it.
4178                if (r0.priority != r1.priority
4179                        || r0.preferredOrder != r1.preferredOrder
4180                        || r0.isDefault != r1.isDefault) {
4181                    return query.get(0);
4182                }
4183                // If we have saved a preference for a preferred activity for
4184                // this Intent, use that.
4185                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4186                        flags, query, r0.priority, true, false, debug, userId);
4187                if (ri != null) {
4188                    return ri;
4189                }
4190                if (userId != 0) {
4191                    ri = new ResolveInfo(mResolveInfo);
4192                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
4193                    ri.activityInfo.applicationInfo = new ApplicationInfo(
4194                            ri.activityInfo.applicationInfo);
4195                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4196                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4197                    return ri;
4198                }
4199                return mResolveInfo;
4200            }
4201        }
4202        return null;
4203    }
4204
4205    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4206            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4207        final int N = query.size();
4208        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4209                .get(userId);
4210        // Get the list of persistent preferred activities that handle the intent
4211        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4212        List<PersistentPreferredActivity> pprefs = ppir != null
4213                ? ppir.queryIntent(intent, resolvedType,
4214                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4215                : null;
4216        if (pprefs != null && pprefs.size() > 0) {
4217            final int M = pprefs.size();
4218            for (int i=0; i<M; i++) {
4219                final PersistentPreferredActivity ppa = pprefs.get(i);
4220                if (DEBUG_PREFERRED || debug) {
4221                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4222                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4223                            + "\n  component=" + ppa.mComponent);
4224                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4225                }
4226                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4227                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4228                if (DEBUG_PREFERRED || debug) {
4229                    Slog.v(TAG, "Found persistent preferred activity:");
4230                    if (ai != null) {
4231                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4232                    } else {
4233                        Slog.v(TAG, "  null");
4234                    }
4235                }
4236                if (ai == null) {
4237                    // This previously registered persistent preferred activity
4238                    // component is no longer known. Ignore it and do NOT remove it.
4239                    continue;
4240                }
4241                for (int j=0; j<N; j++) {
4242                    final ResolveInfo ri = query.get(j);
4243                    if (!ri.activityInfo.applicationInfo.packageName
4244                            .equals(ai.applicationInfo.packageName)) {
4245                        continue;
4246                    }
4247                    if (!ri.activityInfo.name.equals(ai.name)) {
4248                        continue;
4249                    }
4250                    //  Found a persistent preference that can handle the intent.
4251                    if (DEBUG_PREFERRED || debug) {
4252                        Slog.v(TAG, "Returning persistent preferred activity: " +
4253                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4254                    }
4255                    return ri;
4256                }
4257            }
4258        }
4259        return null;
4260    }
4261
4262    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4263            List<ResolveInfo> query, int priority, boolean always,
4264            boolean removeMatches, boolean debug, int userId) {
4265        if (!sUserManager.exists(userId)) return null;
4266        // writer
4267        synchronized (mPackages) {
4268            if (intent.getSelector() != null) {
4269                intent = intent.getSelector();
4270            }
4271            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4272
4273            // Try to find a matching persistent preferred activity.
4274            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4275                    debug, userId);
4276
4277            // If a persistent preferred activity matched, use it.
4278            if (pri != null) {
4279                return pri;
4280            }
4281
4282            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4283            // Get the list of preferred activities that handle the intent
4284            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4285            List<PreferredActivity> prefs = pir != null
4286                    ? pir.queryIntent(intent, resolvedType,
4287                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4288                    : null;
4289            if (prefs != null && prefs.size() > 0) {
4290                boolean changed = false;
4291                try {
4292                    // First figure out how good the original match set is.
4293                    // We will only allow preferred activities that came
4294                    // from the same match quality.
4295                    int match = 0;
4296
4297                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4298
4299                    final int N = query.size();
4300                    for (int j=0; j<N; j++) {
4301                        final ResolveInfo ri = query.get(j);
4302                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4303                                + ": 0x" + Integer.toHexString(match));
4304                        if (ri.match > match) {
4305                            match = ri.match;
4306                        }
4307                    }
4308
4309                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4310                            + Integer.toHexString(match));
4311
4312                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4313                    final int M = prefs.size();
4314                    for (int i=0; i<M; i++) {
4315                        final PreferredActivity pa = prefs.get(i);
4316                        if (DEBUG_PREFERRED || debug) {
4317                            Slog.v(TAG, "Checking PreferredActivity ds="
4318                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4319                                    + "\n  component=" + pa.mPref.mComponent);
4320                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4321                        }
4322                        if (pa.mPref.mMatch != match) {
4323                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4324                                    + Integer.toHexString(pa.mPref.mMatch));
4325                            continue;
4326                        }
4327                        // If it's not an "always" type preferred activity and that's what we're
4328                        // looking for, skip it.
4329                        if (always && !pa.mPref.mAlways) {
4330                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4331                            continue;
4332                        }
4333                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4334                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4335                        if (DEBUG_PREFERRED || debug) {
4336                            Slog.v(TAG, "Found preferred activity:");
4337                            if (ai != null) {
4338                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4339                            } else {
4340                                Slog.v(TAG, "  null");
4341                            }
4342                        }
4343                        if (ai == null) {
4344                            // This previously registered preferred activity
4345                            // component is no longer known.  Most likely an update
4346                            // to the app was installed and in the new version this
4347                            // component no longer exists.  Clean it up by removing
4348                            // it from the preferred activities list, and skip it.
4349                            Slog.w(TAG, "Removing dangling preferred activity: "
4350                                    + pa.mPref.mComponent);
4351                            pir.removeFilter(pa);
4352                            changed = true;
4353                            continue;
4354                        }
4355                        for (int j=0; j<N; j++) {
4356                            final ResolveInfo ri = query.get(j);
4357                            if (!ri.activityInfo.applicationInfo.packageName
4358                                    .equals(ai.applicationInfo.packageName)) {
4359                                continue;
4360                            }
4361                            if (!ri.activityInfo.name.equals(ai.name)) {
4362                                continue;
4363                            }
4364
4365                            if (removeMatches) {
4366                                pir.removeFilter(pa);
4367                                changed = true;
4368                                if (DEBUG_PREFERRED) {
4369                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4370                                }
4371                                break;
4372                            }
4373
4374                            // Okay we found a previously set preferred or last chosen app.
4375                            // If the result set is different from when this
4376                            // was created, we need to clear it and re-ask the
4377                            // user their preference, if we're looking for an "always" type entry.
4378                            if (always && !pa.mPref.sameSet(query)) {
4379                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4380                                        + intent + " type " + resolvedType);
4381                                if (DEBUG_PREFERRED) {
4382                                    Slog.v(TAG, "Removing preferred activity since set changed "
4383                                            + pa.mPref.mComponent);
4384                                }
4385                                pir.removeFilter(pa);
4386                                // Re-add the filter as a "last chosen" entry (!always)
4387                                PreferredActivity lastChosen = new PreferredActivity(
4388                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4389                                pir.addFilter(lastChosen);
4390                                changed = true;
4391                                return null;
4392                            }
4393
4394                            // Yay! Either the set matched or we're looking for the last chosen
4395                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4396                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4397                            return ri;
4398                        }
4399                    }
4400                } finally {
4401                    if (changed) {
4402                        if (DEBUG_PREFERRED) {
4403                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4404                        }
4405                        scheduleWritePackageRestrictionsLocked(userId);
4406                    }
4407                }
4408            }
4409        }
4410        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4411        return null;
4412    }
4413
4414    /*
4415     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4416     */
4417    @Override
4418    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4419            int targetUserId) {
4420        mContext.enforceCallingOrSelfPermission(
4421                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4422        List<CrossProfileIntentFilter> matches =
4423                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4424        if (matches != null) {
4425            int size = matches.size();
4426            for (int i = 0; i < size; i++) {
4427                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4428            }
4429        }
4430        if (hasWebURI(intent)) {
4431            // cross-profile app linking works only towards the parent.
4432            final UserInfo parent = getProfileParent(sourceUserId);
4433            synchronized(mPackages) {
4434                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4435                        intent, resolvedType, 0, sourceUserId, parent.id);
4436                return xpDomainInfo != null
4437                        && xpDomainInfo.bestDomainVerificationStatus !=
4438                                INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
4439            }
4440        }
4441        return false;
4442    }
4443
4444    private UserInfo getProfileParent(int userId) {
4445        final long identity = Binder.clearCallingIdentity();
4446        try {
4447            return sUserManager.getProfileParent(userId);
4448        } finally {
4449            Binder.restoreCallingIdentity(identity);
4450        }
4451    }
4452
4453    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4454            String resolvedType, int userId) {
4455        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4456        if (resolver != null) {
4457            return resolver.queryIntent(intent, resolvedType, false, userId);
4458        }
4459        return null;
4460    }
4461
4462    @Override
4463    public List<ResolveInfo> queryIntentActivities(Intent intent,
4464            String resolvedType, int flags, int userId) {
4465        if (!sUserManager.exists(userId)) return Collections.emptyList();
4466        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4467        ComponentName comp = intent.getComponent();
4468        if (comp == null) {
4469            if (intent.getSelector() != null) {
4470                intent = intent.getSelector();
4471                comp = intent.getComponent();
4472            }
4473        }
4474
4475        if (comp != null) {
4476            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4477            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4478            if (ai != null) {
4479                final ResolveInfo ri = new ResolveInfo();
4480                ri.activityInfo = ai;
4481                list.add(ri);
4482            }
4483            return list;
4484        }
4485
4486        // reader
4487        synchronized (mPackages) {
4488            final String pkgName = intent.getPackage();
4489            if (pkgName == null) {
4490                List<CrossProfileIntentFilter> matchingFilters =
4491                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4492                // Check for results that need to skip the current profile.
4493                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4494                        resolvedType, flags, userId);
4495                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4496                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4497                    result.add(xpResolveInfo);
4498                    return filterIfNotPrimaryUser(result, userId);
4499                }
4500
4501                // Check for results in the current profile.
4502                List<ResolveInfo> result = mActivities.queryIntent(
4503                        intent, resolvedType, flags, userId);
4504
4505                // Check for cross profile results.
4506                xpResolveInfo = queryCrossProfileIntents(
4507                        matchingFilters, intent, resolvedType, flags, userId);
4508                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4509                    result.add(xpResolveInfo);
4510                    Collections.sort(result, mResolvePrioritySorter);
4511                }
4512                result = filterIfNotPrimaryUser(result, userId);
4513                if (hasWebURI(intent)) {
4514                    CrossProfileDomainInfo xpDomainInfo = null;
4515                    final UserInfo parent = getProfileParent(userId);
4516                    if (parent != null) {
4517                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4518                                flags, userId, parent.id);
4519                    }
4520                    if (xpDomainInfo != null) {
4521                        if (xpResolveInfo != null) {
4522                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4523                            // in the result.
4524                            result.remove(xpResolveInfo);
4525                        }
4526                        if (result.size() == 0) {
4527                            result.add(xpDomainInfo.resolveInfo);
4528                            return result;
4529                        }
4530                    } else if (result.size() <= 1) {
4531                        return result;
4532                    }
4533                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4534                            xpDomainInfo, userId);
4535                    Collections.sort(result, mResolvePrioritySorter);
4536                }
4537                return result;
4538            }
4539            final PackageParser.Package pkg = mPackages.get(pkgName);
4540            if (pkg != null) {
4541                return filterIfNotPrimaryUser(
4542                        mActivities.queryIntentForPackage(
4543                                intent, resolvedType, flags, pkg.activities, userId),
4544                        userId);
4545            }
4546            return new ArrayList<ResolveInfo>();
4547        }
4548    }
4549
4550    private static class CrossProfileDomainInfo {
4551        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4552        ResolveInfo resolveInfo;
4553        /* Best domain verification status of the activities found in the other profile */
4554        int bestDomainVerificationStatus;
4555    }
4556
4557    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4558            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4559        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4560                sourceUserId)) {
4561            return null;
4562        }
4563        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4564                resolvedType, flags, parentUserId);
4565
4566        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4567            return null;
4568        }
4569        CrossProfileDomainInfo result = null;
4570        int size = resultTargetUser.size();
4571        for (int i = 0; i < size; i++) {
4572            ResolveInfo riTargetUser = resultTargetUser.get(i);
4573            // Intent filter verification is only for filters that specify a host. So don't return
4574            // those that handle all web uris.
4575            if (riTargetUser.handleAllWebDataURI) {
4576                continue;
4577            }
4578            String packageName = riTargetUser.activityInfo.packageName;
4579            PackageSetting ps = mSettings.mPackages.get(packageName);
4580            if (ps == null) {
4581                continue;
4582            }
4583            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4584            int status = (int)(verificationState >> 32);
4585            if (result == null) {
4586                result = new CrossProfileDomainInfo();
4587                result.resolveInfo =
4588                        createForwardingResolveInfo(null, sourceUserId, parentUserId);
4589                result.bestDomainVerificationStatus = status;
4590            } else {
4591                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4592                        result.bestDomainVerificationStatus);
4593            }
4594        }
4595        return result;
4596    }
4597
4598    /**
4599     * Verification statuses are ordered from the worse to the best, except for
4600     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4601     */
4602    private int bestDomainVerificationStatus(int status1, int status2) {
4603        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4604            return status2;
4605        }
4606        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4607            return status1;
4608        }
4609        return (int) MathUtils.max(status1, status2);
4610    }
4611
4612    private boolean isUserEnabled(int userId) {
4613        long callingId = Binder.clearCallingIdentity();
4614        try {
4615            UserInfo userInfo = sUserManager.getUserInfo(userId);
4616            return userInfo != null && userInfo.isEnabled();
4617        } finally {
4618            Binder.restoreCallingIdentity(callingId);
4619        }
4620    }
4621
4622    /**
4623     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4624     *
4625     * @return filtered list
4626     */
4627    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4628        if (userId == UserHandle.USER_OWNER) {
4629            return resolveInfos;
4630        }
4631        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4632            ResolveInfo info = resolveInfos.get(i);
4633            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4634                resolveInfos.remove(i);
4635            }
4636        }
4637        return resolveInfos;
4638    }
4639
4640    private static boolean hasWebURI(Intent intent) {
4641        if (intent.getData() == null) {
4642            return false;
4643        }
4644        final String scheme = intent.getScheme();
4645        if (TextUtils.isEmpty(scheme)) {
4646            return false;
4647        }
4648        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4649    }
4650
4651    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
4652            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
4653            int userId) {
4654        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
4655
4656        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4657            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
4658                    candidates.size());
4659        }
4660
4661        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4662        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4663        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4664        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4665        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4666
4667        synchronized (mPackages) {
4668            final int count = candidates.size();
4669            // First, try to use linked apps. Partition the candidates into four lists:
4670            // one for the final results, one for the "do not use ever", one for "undefined status"
4671            // and finally one for "browser app type".
4672            for (int n=0; n<count; n++) {
4673                ResolveInfo info = candidates.get(n);
4674                String packageName = info.activityInfo.packageName;
4675                PackageSetting ps = mSettings.mPackages.get(packageName);
4676                if (ps != null) {
4677                    // Add to the special match all list (Browser use case)
4678                    if (info.handleAllWebDataURI) {
4679                        matchAllList.add(info);
4680                        continue;
4681                    }
4682                    // Try to get the status from User settings first
4683                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4684                    int status = (int)(packedStatus >> 32);
4685                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
4686                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4687                        if (DEBUG_DOMAIN_VERIFICATION) {
4688                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
4689                                    + " : linkgen=" + linkGeneration);
4690                        }
4691                        // Use link-enabled generation as preferredOrder, i.e.
4692                        // prefer newly-enabled over earlier-enabled.
4693                        info.preferredOrder = linkGeneration;
4694                        alwaysList.add(info);
4695                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4696                        if (DEBUG_DOMAIN_VERIFICATION) {
4697                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4698                        }
4699                        neverList.add(info);
4700                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4701                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4702                        if (DEBUG_DOMAIN_VERIFICATION) {
4703                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4704                        }
4705                        undefinedList.add(info);
4706                    }
4707                }
4708            }
4709            // First try to add the "always" resolution(s) for the current user, if any
4710            if (alwaysList.size() > 0) {
4711                result.addAll(alwaysList);
4712            // if there is an "always" for the parent user, add it.
4713            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4714                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4715                result.add(xpDomainInfo.resolveInfo);
4716            } else {
4717                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4718                result.addAll(undefinedList);
4719                if (xpDomainInfo != null && (
4720                        xpDomainInfo.bestDomainVerificationStatus
4721                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4722                        || xpDomainInfo.bestDomainVerificationStatus
4723                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4724                    result.add(xpDomainInfo.resolveInfo);
4725                }
4726                // Also add Browsers (all of them or only the default one)
4727                if ((matchFlags & MATCH_ALL) != 0) {
4728                    result.addAll(matchAllList);
4729                } else {
4730                    // Browser/generic handling case.  If there's a default browser, go straight
4731                    // to that (but only if there is no other higher-priority match).
4732                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(
4733                            UserHandle.myUserId());
4734                    int maxMatchPrio = 0;
4735                    ResolveInfo defaultBrowserMatch = null;
4736                    final int numCandidates = matchAllList.size();
4737                    for (int n = 0; n < numCandidates; n++) {
4738                        ResolveInfo info = matchAllList.get(n);
4739                        // track the highest overall match priority...
4740                        if (info.priority > maxMatchPrio) {
4741                            maxMatchPrio = info.priority;
4742                        }
4743                        // ...and the highest-priority default browser match
4744                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4745                            if (defaultBrowserMatch == null
4746                                    || (defaultBrowserMatch.priority < info.priority)) {
4747                                if (debug) {
4748                                    Slog.v(TAG, "Considering default browser match " + info);
4749                                }
4750                                defaultBrowserMatch = info;
4751                            }
4752                        }
4753                    }
4754                    if (defaultBrowserMatch != null
4755                            && defaultBrowserMatch.priority >= maxMatchPrio
4756                            && !TextUtils.isEmpty(defaultBrowserPackageName))
4757                    {
4758                        if (debug) {
4759                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
4760                        }
4761                        result.add(defaultBrowserMatch);
4762                    } else {
4763                        result.addAll(matchAllList);
4764                    }
4765                }
4766
4767                // If there is nothing selected, add all candidates and remove the ones that the user
4768                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4769                if (result.size() == 0) {
4770                    result.addAll(candidates);
4771                    result.removeAll(neverList);
4772                }
4773            }
4774        }
4775        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4776            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4777                    result.size());
4778            for (ResolveInfo info : result) {
4779                Slog.v(TAG, "  + " + info.activityInfo);
4780            }
4781        }
4782        return result;
4783    }
4784
4785    // Returns a packed value as a long:
4786    //
4787    // high 'int'-sized word: link status: undefined/ask/never/always.
4788    // low 'int'-sized word: relative priority among 'always' results.
4789    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4790        long result = ps.getDomainVerificationStatusForUser(userId);
4791        // if none available, get the master status
4792        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4793            if (ps.getIntentFilterVerificationInfo() != null) {
4794                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
4795            }
4796        }
4797        return result;
4798    }
4799
4800    private ResolveInfo querySkipCurrentProfileIntents(
4801            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4802            int flags, int sourceUserId) {
4803        if (matchingFilters != null) {
4804            int size = matchingFilters.size();
4805            for (int i = 0; i < size; i ++) {
4806                CrossProfileIntentFilter filter = matchingFilters.get(i);
4807                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4808                    // Checking if there are activities in the target user that can handle the
4809                    // intent.
4810                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4811                            flags, sourceUserId);
4812                    if (resolveInfo != null) {
4813                        return resolveInfo;
4814                    }
4815                }
4816            }
4817        }
4818        return null;
4819    }
4820
4821    // Return matching ResolveInfo if any for skip current profile intent filters.
4822    private ResolveInfo queryCrossProfileIntents(
4823            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4824            int flags, int sourceUserId) {
4825        if (matchingFilters != null) {
4826            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4827            // match the same intent. For performance reasons, it is better not to
4828            // run queryIntent twice for the same userId
4829            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4830            int size = matchingFilters.size();
4831            for (int i = 0; i < size; i++) {
4832                CrossProfileIntentFilter filter = matchingFilters.get(i);
4833                int targetUserId = filter.getTargetUserId();
4834                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4835                        && !alreadyTriedUserIds.get(targetUserId)) {
4836                    // Checking if there are activities in the target user that can handle the
4837                    // intent.
4838                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4839                            flags, sourceUserId);
4840                    if (resolveInfo != null) return resolveInfo;
4841                    alreadyTriedUserIds.put(targetUserId, true);
4842                }
4843            }
4844        }
4845        return null;
4846    }
4847
4848    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4849            String resolvedType, int flags, int sourceUserId) {
4850        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4851                resolvedType, flags, filter.getTargetUserId());
4852        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4853            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4854        }
4855        return null;
4856    }
4857
4858    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4859            int sourceUserId, int targetUserId) {
4860        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4861        String className;
4862        if (targetUserId == UserHandle.USER_OWNER) {
4863            className = FORWARD_INTENT_TO_USER_OWNER;
4864        } else {
4865            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4866        }
4867        ComponentName forwardingActivityComponentName = new ComponentName(
4868                mAndroidApplication.packageName, className);
4869        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4870                sourceUserId);
4871        if (targetUserId == UserHandle.USER_OWNER) {
4872            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4873            forwardingResolveInfo.noResourceId = true;
4874        }
4875        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4876        forwardingResolveInfo.priority = 0;
4877        forwardingResolveInfo.preferredOrder = 0;
4878        forwardingResolveInfo.match = 0;
4879        forwardingResolveInfo.isDefault = true;
4880        forwardingResolveInfo.filter = filter;
4881        forwardingResolveInfo.targetUserId = targetUserId;
4882        return forwardingResolveInfo;
4883    }
4884
4885    @Override
4886    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4887            Intent[] specifics, String[] specificTypes, Intent intent,
4888            String resolvedType, int flags, int userId) {
4889        if (!sUserManager.exists(userId)) return Collections.emptyList();
4890        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4891                false, "query intent activity options");
4892        final String resultsAction = intent.getAction();
4893
4894        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4895                | PackageManager.GET_RESOLVED_FILTER, userId);
4896
4897        if (DEBUG_INTENT_MATCHING) {
4898            Log.v(TAG, "Query " + intent + ": " + results);
4899        }
4900
4901        int specificsPos = 0;
4902        int N;
4903
4904        // todo: note that the algorithm used here is O(N^2).  This
4905        // isn't a problem in our current environment, but if we start running
4906        // into situations where we have more than 5 or 10 matches then this
4907        // should probably be changed to something smarter...
4908
4909        // First we go through and resolve each of the specific items
4910        // that were supplied, taking care of removing any corresponding
4911        // duplicate items in the generic resolve list.
4912        if (specifics != null) {
4913            for (int i=0; i<specifics.length; i++) {
4914                final Intent sintent = specifics[i];
4915                if (sintent == null) {
4916                    continue;
4917                }
4918
4919                if (DEBUG_INTENT_MATCHING) {
4920                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4921                }
4922
4923                String action = sintent.getAction();
4924                if (resultsAction != null && resultsAction.equals(action)) {
4925                    // If this action was explicitly requested, then don't
4926                    // remove things that have it.
4927                    action = null;
4928                }
4929
4930                ResolveInfo ri = null;
4931                ActivityInfo ai = null;
4932
4933                ComponentName comp = sintent.getComponent();
4934                if (comp == null) {
4935                    ri = resolveIntent(
4936                        sintent,
4937                        specificTypes != null ? specificTypes[i] : null,
4938                            flags, userId);
4939                    if (ri == null) {
4940                        continue;
4941                    }
4942                    if (ri == mResolveInfo) {
4943                        // ACK!  Must do something better with this.
4944                    }
4945                    ai = ri.activityInfo;
4946                    comp = new ComponentName(ai.applicationInfo.packageName,
4947                            ai.name);
4948                } else {
4949                    ai = getActivityInfo(comp, flags, userId);
4950                    if (ai == null) {
4951                        continue;
4952                    }
4953                }
4954
4955                // Look for any generic query activities that are duplicates
4956                // of this specific one, and remove them from the results.
4957                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4958                N = results.size();
4959                int j;
4960                for (j=specificsPos; j<N; j++) {
4961                    ResolveInfo sri = results.get(j);
4962                    if ((sri.activityInfo.name.equals(comp.getClassName())
4963                            && sri.activityInfo.applicationInfo.packageName.equals(
4964                                    comp.getPackageName()))
4965                        || (action != null && sri.filter.matchAction(action))) {
4966                        results.remove(j);
4967                        if (DEBUG_INTENT_MATCHING) Log.v(
4968                            TAG, "Removing duplicate item from " + j
4969                            + " due to specific " + specificsPos);
4970                        if (ri == null) {
4971                            ri = sri;
4972                        }
4973                        j--;
4974                        N--;
4975                    }
4976                }
4977
4978                // Add this specific item to its proper place.
4979                if (ri == null) {
4980                    ri = new ResolveInfo();
4981                    ri.activityInfo = ai;
4982                }
4983                results.add(specificsPos, ri);
4984                ri.specificIndex = i;
4985                specificsPos++;
4986            }
4987        }
4988
4989        // Now we go through the remaining generic results and remove any
4990        // duplicate actions that are found here.
4991        N = results.size();
4992        for (int i=specificsPos; i<N-1; i++) {
4993            final ResolveInfo rii = results.get(i);
4994            if (rii.filter == null) {
4995                continue;
4996            }
4997
4998            // Iterate over all of the actions of this result's intent
4999            // filter...  typically this should be just one.
5000            final Iterator<String> it = rii.filter.actionsIterator();
5001            if (it == null) {
5002                continue;
5003            }
5004            while (it.hasNext()) {
5005                final String action = it.next();
5006                if (resultsAction != null && resultsAction.equals(action)) {
5007                    // If this action was explicitly requested, then don't
5008                    // remove things that have it.
5009                    continue;
5010                }
5011                for (int j=i+1; j<N; j++) {
5012                    final ResolveInfo rij = results.get(j);
5013                    if (rij.filter != null && rij.filter.hasAction(action)) {
5014                        results.remove(j);
5015                        if (DEBUG_INTENT_MATCHING) Log.v(
5016                            TAG, "Removing duplicate item from " + j
5017                            + " due to action " + action + " at " + i);
5018                        j--;
5019                        N--;
5020                    }
5021                }
5022            }
5023
5024            // If the caller didn't request filter information, drop it now
5025            // so we don't have to marshall/unmarshall it.
5026            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5027                rii.filter = null;
5028            }
5029        }
5030
5031        // Filter out the caller activity if so requested.
5032        if (caller != null) {
5033            N = results.size();
5034            for (int i=0; i<N; i++) {
5035                ActivityInfo ainfo = results.get(i).activityInfo;
5036                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5037                        && caller.getClassName().equals(ainfo.name)) {
5038                    results.remove(i);
5039                    break;
5040                }
5041            }
5042        }
5043
5044        // If the caller didn't request filter information,
5045        // drop them now so we don't have to
5046        // marshall/unmarshall it.
5047        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5048            N = results.size();
5049            for (int i=0; i<N; i++) {
5050                results.get(i).filter = null;
5051            }
5052        }
5053
5054        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5055        return results;
5056    }
5057
5058    @Override
5059    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5060            int userId) {
5061        if (!sUserManager.exists(userId)) return Collections.emptyList();
5062        ComponentName comp = intent.getComponent();
5063        if (comp == null) {
5064            if (intent.getSelector() != null) {
5065                intent = intent.getSelector();
5066                comp = intent.getComponent();
5067            }
5068        }
5069        if (comp != null) {
5070            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5071            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5072            if (ai != null) {
5073                ResolveInfo ri = new ResolveInfo();
5074                ri.activityInfo = ai;
5075                list.add(ri);
5076            }
5077            return list;
5078        }
5079
5080        // reader
5081        synchronized (mPackages) {
5082            String pkgName = intent.getPackage();
5083            if (pkgName == null) {
5084                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5085            }
5086            final PackageParser.Package pkg = mPackages.get(pkgName);
5087            if (pkg != null) {
5088                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5089                        userId);
5090            }
5091            return null;
5092        }
5093    }
5094
5095    @Override
5096    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5097        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5098        if (!sUserManager.exists(userId)) return null;
5099        if (query != null) {
5100            if (query.size() >= 1) {
5101                // If there is more than one service with the same priority,
5102                // just arbitrarily pick the first one.
5103                return query.get(0);
5104            }
5105        }
5106        return null;
5107    }
5108
5109    @Override
5110    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5111            int userId) {
5112        if (!sUserManager.exists(userId)) return Collections.emptyList();
5113        ComponentName comp = intent.getComponent();
5114        if (comp == null) {
5115            if (intent.getSelector() != null) {
5116                intent = intent.getSelector();
5117                comp = intent.getComponent();
5118            }
5119        }
5120        if (comp != null) {
5121            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5122            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5123            if (si != null) {
5124                final ResolveInfo ri = new ResolveInfo();
5125                ri.serviceInfo = si;
5126                list.add(ri);
5127            }
5128            return list;
5129        }
5130
5131        // reader
5132        synchronized (mPackages) {
5133            String pkgName = intent.getPackage();
5134            if (pkgName == null) {
5135                return mServices.queryIntent(intent, resolvedType, flags, userId);
5136            }
5137            final PackageParser.Package pkg = mPackages.get(pkgName);
5138            if (pkg != null) {
5139                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5140                        userId);
5141            }
5142            return null;
5143        }
5144    }
5145
5146    @Override
5147    public List<ResolveInfo> queryIntentContentProviders(
5148            Intent intent, String resolvedType, int flags, int userId) {
5149        if (!sUserManager.exists(userId)) return Collections.emptyList();
5150        ComponentName comp = intent.getComponent();
5151        if (comp == null) {
5152            if (intent.getSelector() != null) {
5153                intent = intent.getSelector();
5154                comp = intent.getComponent();
5155            }
5156        }
5157        if (comp != null) {
5158            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5159            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5160            if (pi != null) {
5161                final ResolveInfo ri = new ResolveInfo();
5162                ri.providerInfo = pi;
5163                list.add(ri);
5164            }
5165            return list;
5166        }
5167
5168        // reader
5169        synchronized (mPackages) {
5170            String pkgName = intent.getPackage();
5171            if (pkgName == null) {
5172                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5173            }
5174            final PackageParser.Package pkg = mPackages.get(pkgName);
5175            if (pkg != null) {
5176                return mProviders.queryIntentForPackage(
5177                        intent, resolvedType, flags, pkg.providers, userId);
5178            }
5179            return null;
5180        }
5181    }
5182
5183    @Override
5184    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5185        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5186
5187        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5188
5189        // writer
5190        synchronized (mPackages) {
5191            ArrayList<PackageInfo> list;
5192            if (listUninstalled) {
5193                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5194                for (PackageSetting ps : mSettings.mPackages.values()) {
5195                    PackageInfo pi;
5196                    if (ps.pkg != null) {
5197                        pi = generatePackageInfo(ps.pkg, flags, userId);
5198                    } else {
5199                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5200                    }
5201                    if (pi != null) {
5202                        list.add(pi);
5203                    }
5204                }
5205            } else {
5206                list = new ArrayList<PackageInfo>(mPackages.size());
5207                for (PackageParser.Package p : mPackages.values()) {
5208                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5209                    if (pi != null) {
5210                        list.add(pi);
5211                    }
5212                }
5213            }
5214
5215            return new ParceledListSlice<PackageInfo>(list);
5216        }
5217    }
5218
5219    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5220            String[] permissions, boolean[] tmp, int flags, int userId) {
5221        int numMatch = 0;
5222        final PermissionsState permissionsState = ps.getPermissionsState();
5223        for (int i=0; i<permissions.length; i++) {
5224            final String permission = permissions[i];
5225            if (permissionsState.hasPermission(permission, userId)) {
5226                tmp[i] = true;
5227                numMatch++;
5228            } else {
5229                tmp[i] = false;
5230            }
5231        }
5232        if (numMatch == 0) {
5233            return;
5234        }
5235        PackageInfo pi;
5236        if (ps.pkg != null) {
5237            pi = generatePackageInfo(ps.pkg, flags, userId);
5238        } else {
5239            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5240        }
5241        // The above might return null in cases of uninstalled apps or install-state
5242        // skew across users/profiles.
5243        if (pi != null) {
5244            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5245                if (numMatch == permissions.length) {
5246                    pi.requestedPermissions = permissions;
5247                } else {
5248                    pi.requestedPermissions = new String[numMatch];
5249                    numMatch = 0;
5250                    for (int i=0; i<permissions.length; i++) {
5251                        if (tmp[i]) {
5252                            pi.requestedPermissions[numMatch] = permissions[i];
5253                            numMatch++;
5254                        }
5255                    }
5256                }
5257            }
5258            list.add(pi);
5259        }
5260    }
5261
5262    @Override
5263    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5264            String[] permissions, int flags, int userId) {
5265        if (!sUserManager.exists(userId)) return null;
5266        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5267
5268        // writer
5269        synchronized (mPackages) {
5270            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5271            boolean[] tmpBools = new boolean[permissions.length];
5272            if (listUninstalled) {
5273                for (PackageSetting ps : mSettings.mPackages.values()) {
5274                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5275                }
5276            } else {
5277                for (PackageParser.Package pkg : mPackages.values()) {
5278                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5279                    if (ps != null) {
5280                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5281                                userId);
5282                    }
5283                }
5284            }
5285
5286            return new ParceledListSlice<PackageInfo>(list);
5287        }
5288    }
5289
5290    @Override
5291    public ParceledListSlice<ApplicationInfo> getInstalledApplications(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<ApplicationInfo> list;
5298            if (listUninstalled) {
5299                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5300                for (PackageSetting ps : mSettings.mPackages.values()) {
5301                    ApplicationInfo ai;
5302                    if (ps.pkg != null) {
5303                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5304                                ps.readUserState(userId), userId);
5305                    } else {
5306                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5307                    }
5308                    if (ai != null) {
5309                        list.add(ai);
5310                    }
5311                }
5312            } else {
5313                list = new ArrayList<ApplicationInfo>(mPackages.size());
5314                for (PackageParser.Package p : mPackages.values()) {
5315                    if (p.mExtras != null) {
5316                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5317                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5318                        if (ai != null) {
5319                            list.add(ai);
5320                        }
5321                    }
5322                }
5323            }
5324
5325            return new ParceledListSlice<ApplicationInfo>(list);
5326        }
5327    }
5328
5329    public List<ApplicationInfo> getPersistentApplications(int flags) {
5330        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5331
5332        // reader
5333        synchronized (mPackages) {
5334            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5335            final int userId = UserHandle.getCallingUserId();
5336            while (i.hasNext()) {
5337                final PackageParser.Package p = i.next();
5338                if (p.applicationInfo != null
5339                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5340                        && (!mSafeMode || isSystemApp(p))) {
5341                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5342                    if (ps != null) {
5343                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5344                                ps.readUserState(userId), userId);
5345                        if (ai != null) {
5346                            finalList.add(ai);
5347                        }
5348                    }
5349                }
5350            }
5351        }
5352
5353        return finalList;
5354    }
5355
5356    @Override
5357    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5358        if (!sUserManager.exists(userId)) return null;
5359        // reader
5360        synchronized (mPackages) {
5361            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5362            PackageSetting ps = provider != null
5363                    ? mSettings.mPackages.get(provider.owner.packageName)
5364                    : null;
5365            return ps != null
5366                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5367                    && (!mSafeMode || (provider.info.applicationInfo.flags
5368                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5369                    ? PackageParser.generateProviderInfo(provider, flags,
5370                            ps.readUserState(userId), userId)
5371                    : null;
5372        }
5373    }
5374
5375    /**
5376     * @deprecated
5377     */
5378    @Deprecated
5379    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5380        // reader
5381        synchronized (mPackages) {
5382            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5383                    .entrySet().iterator();
5384            final int userId = UserHandle.getCallingUserId();
5385            while (i.hasNext()) {
5386                Map.Entry<String, PackageParser.Provider> entry = i.next();
5387                PackageParser.Provider p = entry.getValue();
5388                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5389
5390                if (ps != null && p.syncable
5391                        && (!mSafeMode || (p.info.applicationInfo.flags
5392                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5393                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5394                            ps.readUserState(userId), userId);
5395                    if (info != null) {
5396                        outNames.add(entry.getKey());
5397                        outInfo.add(info);
5398                    }
5399                }
5400            }
5401        }
5402    }
5403
5404    @Override
5405    public List<ProviderInfo> queryContentProviders(String processName,
5406            int uid, int flags) {
5407        ArrayList<ProviderInfo> finalList = null;
5408        // reader
5409        synchronized (mPackages) {
5410            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5411            final int userId = processName != null ?
5412                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5413            while (i.hasNext()) {
5414                final PackageParser.Provider p = i.next();
5415                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5416                if (ps != null && p.info.authority != null
5417                        && (processName == null
5418                                || (p.info.processName.equals(processName)
5419                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5420                        && mSettings.isEnabledLPr(p.info, flags, userId)
5421                        && (!mSafeMode
5422                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5423                    if (finalList == null) {
5424                        finalList = new ArrayList<ProviderInfo>(3);
5425                    }
5426                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5427                            ps.readUserState(userId), userId);
5428                    if (info != null) {
5429                        finalList.add(info);
5430                    }
5431                }
5432            }
5433        }
5434
5435        if (finalList != null) {
5436            Collections.sort(finalList, mProviderInitOrderSorter);
5437        }
5438
5439        return finalList;
5440    }
5441
5442    @Override
5443    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5444            int flags) {
5445        // reader
5446        synchronized (mPackages) {
5447            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5448            return PackageParser.generateInstrumentationInfo(i, flags);
5449        }
5450    }
5451
5452    @Override
5453    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5454            int flags) {
5455        ArrayList<InstrumentationInfo> finalList =
5456            new ArrayList<InstrumentationInfo>();
5457
5458        // reader
5459        synchronized (mPackages) {
5460            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5461            while (i.hasNext()) {
5462                final PackageParser.Instrumentation p = i.next();
5463                if (targetPackage == null
5464                        || targetPackage.equals(p.info.targetPackage)) {
5465                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5466                            flags);
5467                    if (ii != null) {
5468                        finalList.add(ii);
5469                    }
5470                }
5471            }
5472        }
5473
5474        return finalList;
5475    }
5476
5477    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5478        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5479        if (overlays == null) {
5480            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5481            return;
5482        }
5483        for (PackageParser.Package opkg : overlays.values()) {
5484            // Not much to do if idmap fails: we already logged the error
5485            // and we certainly don't want to abort installation of pkg simply
5486            // because an overlay didn't fit properly. For these reasons,
5487            // ignore the return value of createIdmapForPackagePairLI.
5488            createIdmapForPackagePairLI(pkg, opkg);
5489        }
5490    }
5491
5492    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5493            PackageParser.Package opkg) {
5494        if (!opkg.mTrustedOverlay) {
5495            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5496                    opkg.baseCodePath + ": overlay not trusted");
5497            return false;
5498        }
5499        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5500        if (overlaySet == null) {
5501            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5502                    opkg.baseCodePath + " but target package has no known overlays");
5503            return false;
5504        }
5505        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5506        // TODO: generate idmap for split APKs
5507        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5508            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5509                    + opkg.baseCodePath);
5510            return false;
5511        }
5512        PackageParser.Package[] overlayArray =
5513            overlaySet.values().toArray(new PackageParser.Package[0]);
5514        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5515            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5516                return p1.mOverlayPriority - p2.mOverlayPriority;
5517            }
5518        };
5519        Arrays.sort(overlayArray, cmp);
5520
5521        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5522        int i = 0;
5523        for (PackageParser.Package p : overlayArray) {
5524            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5525        }
5526        return true;
5527    }
5528
5529    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5530        final File[] files = dir.listFiles();
5531        if (ArrayUtils.isEmpty(files)) {
5532            Log.d(TAG, "No files in app dir " + dir);
5533            return;
5534        }
5535
5536        if (DEBUG_PACKAGE_SCANNING) {
5537            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5538                    + " flags=0x" + Integer.toHexString(parseFlags));
5539        }
5540
5541        for (File file : files) {
5542            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5543                    && !PackageInstallerService.isStageName(file.getName());
5544            if (!isPackage) {
5545                // Ignore entries which are not packages
5546                continue;
5547            }
5548            try {
5549                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5550                        scanFlags, currentTime, null);
5551            } catch (PackageManagerException e) {
5552                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5553
5554                // Delete invalid userdata apps
5555                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5556                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5557                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5558                    if (file.isDirectory()) {
5559                        mInstaller.rmPackageDir(file.getAbsolutePath());
5560                    } else {
5561                        file.delete();
5562                    }
5563                }
5564            }
5565        }
5566    }
5567
5568    private static File getSettingsProblemFile() {
5569        File dataDir = Environment.getDataDirectory();
5570        File systemDir = new File(dataDir, "system");
5571        File fname = new File(systemDir, "uiderrors.txt");
5572        return fname;
5573    }
5574
5575    static void reportSettingsProblem(int priority, String msg) {
5576        logCriticalInfo(priority, msg);
5577    }
5578
5579    static void logCriticalInfo(int priority, String msg) {
5580        Slog.println(priority, TAG, msg);
5581        EventLogTags.writePmCriticalInfo(msg);
5582        try {
5583            File fname = getSettingsProblemFile();
5584            FileOutputStream out = new FileOutputStream(fname, true);
5585            PrintWriter pw = new FastPrintWriter(out);
5586            SimpleDateFormat formatter = new SimpleDateFormat();
5587            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5588            pw.println(dateString + ": " + msg);
5589            pw.close();
5590            FileUtils.setPermissions(
5591                    fname.toString(),
5592                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5593                    -1, -1);
5594        } catch (java.io.IOException e) {
5595        }
5596    }
5597
5598    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5599            PackageParser.Package pkg, File srcFile, int parseFlags)
5600            throws PackageManagerException {
5601        if (ps != null
5602                && ps.codePath.equals(srcFile)
5603                && ps.timeStamp == srcFile.lastModified()
5604                && !isCompatSignatureUpdateNeeded(pkg)
5605                && !isRecoverSignatureUpdateNeeded(pkg)) {
5606            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5607            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5608            ArraySet<PublicKey> signingKs;
5609            synchronized (mPackages) {
5610                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5611            }
5612            if (ps.signatures.mSignatures != null
5613                    && ps.signatures.mSignatures.length != 0
5614                    && signingKs != null) {
5615                // Optimization: reuse the existing cached certificates
5616                // if the package appears to be unchanged.
5617                pkg.mSignatures = ps.signatures.mSignatures;
5618                pkg.mSigningKeys = signingKs;
5619                return;
5620            }
5621
5622            Slog.w(TAG, "PackageSetting for " + ps.name
5623                    + " is missing signatures.  Collecting certs again to recover them.");
5624        } else {
5625            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5626        }
5627
5628        try {
5629            pp.collectCertificates(pkg, parseFlags);
5630            pp.collectManifestDigest(pkg);
5631        } catch (PackageParserException e) {
5632            throw PackageManagerException.from(e);
5633        }
5634    }
5635
5636    /*
5637     *  Scan a package and return the newly parsed package.
5638     *  Returns null in case of errors and the error code is stored in mLastScanError
5639     */
5640    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5641            long currentTime, UserHandle user) throws PackageManagerException {
5642        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5643        parseFlags |= mDefParseFlags;
5644        PackageParser pp = new PackageParser();
5645        pp.setSeparateProcesses(mSeparateProcesses);
5646        pp.setOnlyCoreApps(mOnlyCore);
5647        pp.setDisplayMetrics(mMetrics);
5648
5649        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5650            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5651        }
5652
5653        final PackageParser.Package pkg;
5654        try {
5655            pkg = pp.parsePackage(scanFile, parseFlags);
5656        } catch (PackageParserException e) {
5657            throw PackageManagerException.from(e);
5658        }
5659
5660        PackageSetting ps = null;
5661        PackageSetting updatedPkg;
5662        // reader
5663        synchronized (mPackages) {
5664            // Look to see if we already know about this package.
5665            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5666            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5667                // This package has been renamed to its original name.  Let's
5668                // use that.
5669                ps = mSettings.peekPackageLPr(oldName);
5670            }
5671            // If there was no original package, see one for the real package name.
5672            if (ps == null) {
5673                ps = mSettings.peekPackageLPr(pkg.packageName);
5674            }
5675            // Check to see if this package could be hiding/updating a system
5676            // package.  Must look for it either under the original or real
5677            // package name depending on our state.
5678            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5679            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5680        }
5681        boolean updatedPkgBetter = false;
5682        // First check if this is a system package that may involve an update
5683        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5684            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5685            // it needs to drop FLAG_PRIVILEGED.
5686            if (locationIsPrivileged(scanFile)) {
5687                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5688            } else {
5689                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5690            }
5691
5692            if (ps != null && !ps.codePath.equals(scanFile)) {
5693                // The path has changed from what was last scanned...  check the
5694                // version of the new path against what we have stored to determine
5695                // what to do.
5696                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5697                if (pkg.mVersionCode <= ps.versionCode) {
5698                    // The system package has been updated and the code path does not match
5699                    // Ignore entry. Skip it.
5700                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5701                            + " ignored: updated version " + ps.versionCode
5702                            + " better than this " + pkg.mVersionCode);
5703                    if (!updatedPkg.codePath.equals(scanFile)) {
5704                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5705                                + ps.name + " changing from " + updatedPkg.codePathString
5706                                + " to " + scanFile);
5707                        updatedPkg.codePath = scanFile;
5708                        updatedPkg.codePathString = scanFile.toString();
5709                        updatedPkg.resourcePath = scanFile;
5710                        updatedPkg.resourcePathString = scanFile.toString();
5711                    }
5712                    updatedPkg.pkg = pkg;
5713                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5714                            "Package " + ps.name + " at " + scanFile
5715                                    + " ignored: updated version " + ps.versionCode
5716                                    + " better than this " + pkg.mVersionCode);
5717                } else {
5718                    // The current app on the system partition is better than
5719                    // what we have updated to on the data partition; switch
5720                    // back to the system partition version.
5721                    // At this point, its safely assumed that package installation for
5722                    // apps in system partition will go through. If not there won't be a working
5723                    // version of the app
5724                    // writer
5725                    synchronized (mPackages) {
5726                        // Just remove the loaded entries from package lists.
5727                        mPackages.remove(ps.name);
5728                    }
5729
5730                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5731                            + " reverting from " + ps.codePathString
5732                            + ": new version " + pkg.mVersionCode
5733                            + " better than installed " + ps.versionCode);
5734
5735                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5736                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5737                    synchronized (mInstallLock) {
5738                        args.cleanUpResourcesLI();
5739                    }
5740                    synchronized (mPackages) {
5741                        mSettings.enableSystemPackageLPw(ps.name);
5742                    }
5743                    updatedPkgBetter = true;
5744                }
5745            }
5746        }
5747
5748        if (updatedPkg != null) {
5749            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5750            // initially
5751            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5752
5753            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5754            // flag set initially
5755            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5756                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5757            }
5758        }
5759
5760        // Verify certificates against what was last scanned
5761        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5762
5763        /*
5764         * A new system app appeared, but we already had a non-system one of the
5765         * same name installed earlier.
5766         */
5767        boolean shouldHideSystemApp = false;
5768        if (updatedPkg == null && ps != null
5769                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5770            /*
5771             * Check to make sure the signatures match first. If they don't,
5772             * wipe the installed application and its data.
5773             */
5774            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5775                    != PackageManager.SIGNATURE_MATCH) {
5776                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5777                        + " signatures don't match existing userdata copy; removing");
5778                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5779                ps = null;
5780            } else {
5781                /*
5782                 * If the newly-added system app is an older version than the
5783                 * already installed version, hide it. It will be scanned later
5784                 * and re-added like an update.
5785                 */
5786                if (pkg.mVersionCode <= ps.versionCode) {
5787                    shouldHideSystemApp = true;
5788                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5789                            + " but new version " + pkg.mVersionCode + " better than installed "
5790                            + ps.versionCode + "; hiding system");
5791                } else {
5792                    /*
5793                     * The newly found system app is a newer version that the
5794                     * one previously installed. Simply remove the
5795                     * already-installed application and replace it with our own
5796                     * while keeping the application data.
5797                     */
5798                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5799                            + " reverting from " + ps.codePathString + ": new version "
5800                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5801                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5802                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5803                    synchronized (mInstallLock) {
5804                        args.cleanUpResourcesLI();
5805                    }
5806                }
5807            }
5808        }
5809
5810        // The apk is forward locked (not public) if its code and resources
5811        // are kept in different files. (except for app in either system or
5812        // vendor path).
5813        // TODO grab this value from PackageSettings
5814        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5815            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5816                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5817            }
5818        }
5819
5820        // TODO: extend to support forward-locked splits
5821        String resourcePath = null;
5822        String baseResourcePath = null;
5823        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5824            if (ps != null && ps.resourcePathString != null) {
5825                resourcePath = ps.resourcePathString;
5826                baseResourcePath = ps.resourcePathString;
5827            } else {
5828                // Should not happen at all. Just log an error.
5829                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5830            }
5831        } else {
5832            resourcePath = pkg.codePath;
5833            baseResourcePath = pkg.baseCodePath;
5834        }
5835
5836        // Set application objects path explicitly.
5837        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5838        pkg.applicationInfo.setCodePath(pkg.codePath);
5839        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5840        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5841        pkg.applicationInfo.setResourcePath(resourcePath);
5842        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5843        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5844
5845        // Note that we invoke the following method only if we are about to unpack an application
5846        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5847                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5848
5849        /*
5850         * If the system app should be overridden by a previously installed
5851         * data, hide the system app now and let the /data/app scan pick it up
5852         * again.
5853         */
5854        if (shouldHideSystemApp) {
5855            synchronized (mPackages) {
5856                /*
5857                 * We have to grant systems permissions before we hide, because
5858                 * grantPermissions will assume the package update is trying to
5859                 * expand its permissions.
5860                 */
5861                grantPermissionsLPw(pkg, true, pkg.packageName);
5862                mSettings.disableSystemPackageLPw(pkg.packageName);
5863            }
5864        }
5865
5866        return scannedPkg;
5867    }
5868
5869    private static String fixProcessName(String defProcessName,
5870            String processName, int uid) {
5871        if (processName == null) {
5872            return defProcessName;
5873        }
5874        return processName;
5875    }
5876
5877    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5878            throws PackageManagerException {
5879        if (pkgSetting.signatures.mSignatures != null) {
5880            // Already existing package. Make sure signatures match
5881            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5882                    == PackageManager.SIGNATURE_MATCH;
5883            if (!match) {
5884                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5885                        == PackageManager.SIGNATURE_MATCH;
5886            }
5887            if (!match) {
5888                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5889                        == PackageManager.SIGNATURE_MATCH;
5890            }
5891            if (!match) {
5892                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5893                        + pkg.packageName + " signatures do not match the "
5894                        + "previously installed version; ignoring!");
5895            }
5896        }
5897
5898        // Check for shared user signatures
5899        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5900            // Already existing package. Make sure signatures match
5901            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5902                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5903            if (!match) {
5904                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5905                        == PackageManager.SIGNATURE_MATCH;
5906            }
5907            if (!match) {
5908                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5909                        == PackageManager.SIGNATURE_MATCH;
5910            }
5911            if (!match) {
5912                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5913                        "Package " + pkg.packageName
5914                        + " has no signatures that match those in shared user "
5915                        + pkgSetting.sharedUser.name + "; ignoring!");
5916            }
5917        }
5918    }
5919
5920    /**
5921     * Enforces that only the system UID or root's UID can call a method exposed
5922     * via Binder.
5923     *
5924     * @param message used as message if SecurityException is thrown
5925     * @throws SecurityException if the caller is not system or root
5926     */
5927    private static final void enforceSystemOrRoot(String message) {
5928        final int uid = Binder.getCallingUid();
5929        if (uid != Process.SYSTEM_UID && uid != 0) {
5930            throw new SecurityException(message);
5931        }
5932    }
5933
5934    @Override
5935    public void performBootDexOpt() {
5936        enforceSystemOrRoot("Only the system can request dexopt be performed");
5937
5938        // Before everything else, see whether we need to fstrim.
5939        try {
5940            IMountService ms = PackageHelper.getMountService();
5941            if (ms != null) {
5942                final boolean isUpgrade = isUpgrade();
5943                boolean doTrim = isUpgrade;
5944                if (doTrim) {
5945                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5946                } else {
5947                    final long interval = android.provider.Settings.Global.getLong(
5948                            mContext.getContentResolver(),
5949                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5950                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5951                    if (interval > 0) {
5952                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5953                        if (timeSinceLast > interval) {
5954                            doTrim = true;
5955                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5956                                    + "; running immediately");
5957                        }
5958                    }
5959                }
5960                if (doTrim) {
5961                    if (!isFirstBoot()) {
5962                        try {
5963                            ActivityManagerNative.getDefault().showBootMessage(
5964                                    mContext.getResources().getString(
5965                                            R.string.android_upgrading_fstrim), true);
5966                        } catch (RemoteException e) {
5967                        }
5968                    }
5969                    ms.runMaintenance();
5970                }
5971            } else {
5972                Slog.e(TAG, "Mount service unavailable!");
5973            }
5974        } catch (RemoteException e) {
5975            // Can't happen; MountService is local
5976        }
5977
5978        final ArraySet<PackageParser.Package> pkgs;
5979        synchronized (mPackages) {
5980            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5981        }
5982
5983        if (pkgs != null) {
5984            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5985            // in case the device runs out of space.
5986            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5987            // Give priority to core apps.
5988            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5989                PackageParser.Package pkg = it.next();
5990                if (pkg.coreApp) {
5991                    if (DEBUG_DEXOPT) {
5992                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5993                    }
5994                    sortedPkgs.add(pkg);
5995                    it.remove();
5996                }
5997            }
5998            // Give priority to system apps that listen for pre boot complete.
5999            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
6000            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
6001            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6002                PackageParser.Package pkg = it.next();
6003                if (pkgNames.contains(pkg.packageName)) {
6004                    if (DEBUG_DEXOPT) {
6005                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
6006                    }
6007                    sortedPkgs.add(pkg);
6008                    it.remove();
6009                }
6010            }
6011            // Give priority to system apps.
6012            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6013                PackageParser.Package pkg = it.next();
6014                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
6015                    if (DEBUG_DEXOPT) {
6016                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
6017                    }
6018                    sortedPkgs.add(pkg);
6019                    it.remove();
6020                }
6021            }
6022            // Give priority to updated system apps.
6023            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6024                PackageParser.Package pkg = it.next();
6025                if (pkg.isUpdatedSystemApp()) {
6026                    if (DEBUG_DEXOPT) {
6027                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
6028                    }
6029                    sortedPkgs.add(pkg);
6030                    it.remove();
6031                }
6032            }
6033            // Give priority to apps that listen for boot complete.
6034            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
6035            pkgNames = getPackageNamesForIntent(intent);
6036            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6037                PackageParser.Package pkg = it.next();
6038                if (pkgNames.contains(pkg.packageName)) {
6039                    if (DEBUG_DEXOPT) {
6040                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
6041                    }
6042                    sortedPkgs.add(pkg);
6043                    it.remove();
6044                }
6045            }
6046            // Filter out packages that aren't recently used.
6047            filterRecentlyUsedApps(pkgs);
6048            // Add all remaining apps.
6049            for (PackageParser.Package pkg : pkgs) {
6050                if (DEBUG_DEXOPT) {
6051                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
6052                }
6053                sortedPkgs.add(pkg);
6054            }
6055
6056            // If we want to be lazy, filter everything that wasn't recently used.
6057            if (mLazyDexOpt) {
6058                filterRecentlyUsedApps(sortedPkgs);
6059            }
6060
6061            int i = 0;
6062            int total = sortedPkgs.size();
6063            File dataDir = Environment.getDataDirectory();
6064            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
6065            if (lowThreshold == 0) {
6066                throw new IllegalStateException("Invalid low memory threshold");
6067            }
6068            for (PackageParser.Package pkg : sortedPkgs) {
6069                long usableSpace = dataDir.getUsableSpace();
6070                if (usableSpace < lowThreshold) {
6071                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
6072                    break;
6073                }
6074                performBootDexOpt(pkg, ++i, total);
6075            }
6076        }
6077    }
6078
6079    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
6080        // Filter out packages that aren't recently used.
6081        //
6082        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
6083        // should do a full dexopt.
6084        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
6085            int total = pkgs.size();
6086            int skipped = 0;
6087            long now = System.currentTimeMillis();
6088            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
6089                PackageParser.Package pkg = i.next();
6090                long then = pkg.mLastPackageUsageTimeInMills;
6091                if (then + mDexOptLRUThresholdInMills < now) {
6092                    if (DEBUG_DEXOPT) {
6093                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
6094                              ((then == 0) ? "never" : new Date(then)));
6095                    }
6096                    i.remove();
6097                    skipped++;
6098                }
6099            }
6100            if (DEBUG_DEXOPT) {
6101                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
6102            }
6103        }
6104    }
6105
6106    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
6107        List<ResolveInfo> ris = null;
6108        try {
6109            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6110                    intent, null, 0, UserHandle.USER_OWNER);
6111        } catch (RemoteException e) {
6112        }
6113        ArraySet<String> pkgNames = new ArraySet<String>();
6114        if (ris != null) {
6115            for (ResolveInfo ri : ris) {
6116                pkgNames.add(ri.activityInfo.packageName);
6117            }
6118        }
6119        return pkgNames;
6120    }
6121
6122    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6123        if (DEBUG_DEXOPT) {
6124            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6125        }
6126        if (!isFirstBoot()) {
6127            try {
6128                ActivityManagerNative.getDefault().showBootMessage(
6129                        mContext.getResources().getString(R.string.android_upgrading_apk,
6130                                curr, total), true);
6131            } catch (RemoteException e) {
6132            }
6133        }
6134        PackageParser.Package p = pkg;
6135        synchronized (mInstallLock) {
6136            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6137                    false /* force dex */, false /* defer */, true /* include dependencies */);
6138        }
6139    }
6140
6141    @Override
6142    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6143        return performDexOpt(packageName, instructionSet, false);
6144    }
6145
6146    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
6147        boolean dexopt = mLazyDexOpt || backgroundDexopt;
6148        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6149        if (!dexopt && !updateUsage) {
6150            // We aren't going to dexopt or update usage, so bail early.
6151            return false;
6152        }
6153        PackageParser.Package p;
6154        final String targetInstructionSet;
6155        synchronized (mPackages) {
6156            p = mPackages.get(packageName);
6157            if (p == null) {
6158                return false;
6159            }
6160            if (updateUsage) {
6161                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6162            }
6163            mPackageUsage.write(false);
6164            if (!dexopt) {
6165                // We aren't going to dexopt, so bail early.
6166                return false;
6167            }
6168
6169            targetInstructionSet = instructionSet != null ? instructionSet :
6170                    getPrimaryInstructionSet(p.applicationInfo);
6171            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6172                return false;
6173            }
6174        }
6175
6176        synchronized (mInstallLock) {
6177            final String[] instructionSets = new String[] { targetInstructionSet };
6178            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6179                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
6180            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6181        }
6182    }
6183
6184    public ArraySet<String> getPackagesThatNeedDexOpt() {
6185        ArraySet<String> pkgs = null;
6186        synchronized (mPackages) {
6187            for (PackageParser.Package p : mPackages.values()) {
6188                if (DEBUG_DEXOPT) {
6189                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6190                }
6191                if (!p.mDexOptPerformed.isEmpty()) {
6192                    continue;
6193                }
6194                if (pkgs == null) {
6195                    pkgs = new ArraySet<String>();
6196                }
6197                pkgs.add(p.packageName);
6198            }
6199        }
6200        return pkgs;
6201    }
6202
6203    public void shutdown() {
6204        mPackageUsage.write(true);
6205    }
6206
6207    @Override
6208    public void forceDexOpt(String packageName) {
6209        enforceSystemOrRoot("forceDexOpt");
6210
6211        PackageParser.Package pkg;
6212        synchronized (mPackages) {
6213            pkg = mPackages.get(packageName);
6214            if (pkg == null) {
6215                throw new IllegalArgumentException("Missing package: " + packageName);
6216            }
6217        }
6218
6219        synchronized (mInstallLock) {
6220            final String[] instructionSets = new String[] {
6221                    getPrimaryInstructionSet(pkg.applicationInfo) };
6222            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6223                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
6224            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6225                throw new IllegalStateException("Failed to dexopt: " + res);
6226            }
6227        }
6228    }
6229
6230    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6231        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6232            Slog.w(TAG, "Unable to update from " + oldPkg.name
6233                    + " to " + newPkg.packageName
6234                    + ": old package not in system partition");
6235            return false;
6236        } else if (mPackages.get(oldPkg.name) != null) {
6237            Slog.w(TAG, "Unable to update from " + oldPkg.name
6238                    + " to " + newPkg.packageName
6239                    + ": old package still exists");
6240            return false;
6241        }
6242        return true;
6243    }
6244
6245    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6246        int[] users = sUserManager.getUserIds();
6247        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6248        if (res < 0) {
6249            return res;
6250        }
6251        for (int user : users) {
6252            if (user != 0) {
6253                res = mInstaller.createUserData(volumeUuid, packageName,
6254                        UserHandle.getUid(user, uid), user, seinfo);
6255                if (res < 0) {
6256                    return res;
6257                }
6258            }
6259        }
6260        return res;
6261    }
6262
6263    private int removeDataDirsLI(String volumeUuid, String packageName) {
6264        int[] users = sUserManager.getUserIds();
6265        int res = 0;
6266        for (int user : users) {
6267            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6268            if (resInner < 0) {
6269                res = resInner;
6270            }
6271        }
6272
6273        return res;
6274    }
6275
6276    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6277        int[] users = sUserManager.getUserIds();
6278        int res = 0;
6279        for (int user : users) {
6280            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6281            if (resInner < 0) {
6282                res = resInner;
6283            }
6284        }
6285        return res;
6286    }
6287
6288    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6289            PackageParser.Package changingLib) {
6290        if (file.path != null) {
6291            usesLibraryFiles.add(file.path);
6292            return;
6293        }
6294        PackageParser.Package p = mPackages.get(file.apk);
6295        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6296            // If we are doing this while in the middle of updating a library apk,
6297            // then we need to make sure to use that new apk for determining the
6298            // dependencies here.  (We haven't yet finished committing the new apk
6299            // to the package manager state.)
6300            if (p == null || p.packageName.equals(changingLib.packageName)) {
6301                p = changingLib;
6302            }
6303        }
6304        if (p != null) {
6305            usesLibraryFiles.addAll(p.getAllCodePaths());
6306        }
6307    }
6308
6309    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6310            PackageParser.Package changingLib) throws PackageManagerException {
6311        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6312            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6313            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6314            for (int i=0; i<N; i++) {
6315                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6316                if (file == null) {
6317                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6318                            "Package " + pkg.packageName + " requires unavailable shared library "
6319                            + pkg.usesLibraries.get(i) + "; failing!");
6320                }
6321                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6322            }
6323            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6324            for (int i=0; i<N; i++) {
6325                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6326                if (file == null) {
6327                    Slog.w(TAG, "Package " + pkg.packageName
6328                            + " desires unavailable shared library "
6329                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6330                } else {
6331                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6332                }
6333            }
6334            N = usesLibraryFiles.size();
6335            if (N > 0) {
6336                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6337            } else {
6338                pkg.usesLibraryFiles = null;
6339            }
6340        }
6341    }
6342
6343    private static boolean hasString(List<String> list, List<String> which) {
6344        if (list == null) {
6345            return false;
6346        }
6347        for (int i=list.size()-1; i>=0; i--) {
6348            for (int j=which.size()-1; j>=0; j--) {
6349                if (which.get(j).equals(list.get(i))) {
6350                    return true;
6351                }
6352            }
6353        }
6354        return false;
6355    }
6356
6357    private void updateAllSharedLibrariesLPw() {
6358        for (PackageParser.Package pkg : mPackages.values()) {
6359            try {
6360                updateSharedLibrariesLPw(pkg, null);
6361            } catch (PackageManagerException e) {
6362                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6363            }
6364        }
6365    }
6366
6367    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6368            PackageParser.Package changingPkg) {
6369        ArrayList<PackageParser.Package> res = null;
6370        for (PackageParser.Package pkg : mPackages.values()) {
6371            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6372                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6373                if (res == null) {
6374                    res = new ArrayList<PackageParser.Package>();
6375                }
6376                res.add(pkg);
6377                try {
6378                    updateSharedLibrariesLPw(pkg, changingPkg);
6379                } catch (PackageManagerException e) {
6380                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6381                }
6382            }
6383        }
6384        return res;
6385    }
6386
6387    /**
6388     * Derive the value of the {@code cpuAbiOverride} based on the provided
6389     * value and an optional stored value from the package settings.
6390     */
6391    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6392        String cpuAbiOverride = null;
6393
6394        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6395            cpuAbiOverride = null;
6396        } else if (abiOverride != null) {
6397            cpuAbiOverride = abiOverride;
6398        } else if (settings != null) {
6399            cpuAbiOverride = settings.cpuAbiOverrideString;
6400        }
6401
6402        return cpuAbiOverride;
6403    }
6404
6405    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6406            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6407        boolean success = false;
6408        try {
6409            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6410                    currentTime, user);
6411            success = true;
6412            return res;
6413        } finally {
6414            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6415                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6416            }
6417        }
6418    }
6419
6420    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6421            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6422        final File scanFile = new File(pkg.codePath);
6423        if (pkg.applicationInfo.getCodePath() == null ||
6424                pkg.applicationInfo.getResourcePath() == null) {
6425            // Bail out. The resource and code paths haven't been set.
6426            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6427                    "Code and resource paths haven't been set correctly");
6428        }
6429
6430        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6431            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6432        } else {
6433            // Only allow system apps to be flagged as core apps.
6434            pkg.coreApp = false;
6435        }
6436
6437        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6438            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6439        }
6440
6441        if (mCustomResolverComponentName != null &&
6442                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6443            setUpCustomResolverActivity(pkg);
6444        }
6445
6446        if (pkg.packageName.equals("android")) {
6447            synchronized (mPackages) {
6448                if (mAndroidApplication != null) {
6449                    Slog.w(TAG, "*************************************************");
6450                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6451                    Slog.w(TAG, " file=" + scanFile);
6452                    Slog.w(TAG, "*************************************************");
6453                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6454                            "Core android package being redefined.  Skipping.");
6455                }
6456
6457                // Set up information for our fall-back user intent resolution activity.
6458                mPlatformPackage = pkg;
6459                pkg.mVersionCode = mSdkVersion;
6460                mAndroidApplication = pkg.applicationInfo;
6461
6462                if (!mResolverReplaced) {
6463                    mResolveActivity.applicationInfo = mAndroidApplication;
6464                    mResolveActivity.name = ResolverActivity.class.getName();
6465                    mResolveActivity.packageName = mAndroidApplication.packageName;
6466                    mResolveActivity.processName = "system:ui";
6467                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6468                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6469                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6470                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6471                    mResolveActivity.exported = true;
6472                    mResolveActivity.enabled = true;
6473                    mResolveInfo.activityInfo = mResolveActivity;
6474                    mResolveInfo.priority = 0;
6475                    mResolveInfo.preferredOrder = 0;
6476                    mResolveInfo.match = 0;
6477                    mResolveComponentName = new ComponentName(
6478                            mAndroidApplication.packageName, mResolveActivity.name);
6479                }
6480            }
6481        }
6482
6483        if (DEBUG_PACKAGE_SCANNING) {
6484            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6485                Log.d(TAG, "Scanning package " + pkg.packageName);
6486        }
6487
6488        if (mPackages.containsKey(pkg.packageName)
6489                || mSharedLibraries.containsKey(pkg.packageName)) {
6490            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6491                    "Application package " + pkg.packageName
6492                    + " already installed.  Skipping duplicate.");
6493        }
6494
6495        // If we're only installing presumed-existing packages, require that the
6496        // scanned APK is both already known and at the path previously established
6497        // for it.  Previously unknown packages we pick up normally, but if we have an
6498        // a priori expectation about this package's install presence, enforce it.
6499        // With a singular exception for new system packages. When an OTA contains
6500        // a new system package, we allow the codepath to change from a system location
6501        // to the user-installed location. If we don't allow this change, any newer,
6502        // user-installed version of the application will be ignored.
6503        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6504            if (mExpectingBetter.containsKey(pkg.packageName)) {
6505                logCriticalInfo(Log.WARN,
6506                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6507            } else {
6508                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6509                if (known != null) {
6510                    if (DEBUG_PACKAGE_SCANNING) {
6511                        Log.d(TAG, "Examining " + pkg.codePath
6512                                + " and requiring known paths " + known.codePathString
6513                                + " & " + known.resourcePathString);
6514                    }
6515                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6516                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6517                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6518                                "Application package " + pkg.packageName
6519                                + " found at " + pkg.applicationInfo.getCodePath()
6520                                + " but expected at " + known.codePathString + "; ignoring.");
6521                    }
6522                }
6523            }
6524        }
6525
6526        // Initialize package source and resource directories
6527        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6528        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6529
6530        SharedUserSetting suid = null;
6531        PackageSetting pkgSetting = null;
6532
6533        if (!isSystemApp(pkg)) {
6534            // Only system apps can use these features.
6535            pkg.mOriginalPackages = null;
6536            pkg.mRealPackage = null;
6537            pkg.mAdoptPermissions = null;
6538        }
6539
6540        // writer
6541        synchronized (mPackages) {
6542            if (pkg.mSharedUserId != null) {
6543                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6544                if (suid == null) {
6545                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6546                            "Creating application package " + pkg.packageName
6547                            + " for shared user failed");
6548                }
6549                if (DEBUG_PACKAGE_SCANNING) {
6550                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6551                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6552                                + "): packages=" + suid.packages);
6553                }
6554            }
6555
6556            // Check if we are renaming from an original package name.
6557            PackageSetting origPackage = null;
6558            String realName = null;
6559            if (pkg.mOriginalPackages != null) {
6560                // This package may need to be renamed to a previously
6561                // installed name.  Let's check on that...
6562                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6563                if (pkg.mOriginalPackages.contains(renamed)) {
6564                    // This package had originally been installed as the
6565                    // original name, and we have already taken care of
6566                    // transitioning to the new one.  Just update the new
6567                    // one to continue using the old name.
6568                    realName = pkg.mRealPackage;
6569                    if (!pkg.packageName.equals(renamed)) {
6570                        // Callers into this function may have already taken
6571                        // care of renaming the package; only do it here if
6572                        // it is not already done.
6573                        pkg.setPackageName(renamed);
6574                    }
6575
6576                } else {
6577                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6578                        if ((origPackage = mSettings.peekPackageLPr(
6579                                pkg.mOriginalPackages.get(i))) != null) {
6580                            // We do have the package already installed under its
6581                            // original name...  should we use it?
6582                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6583                                // New package is not compatible with original.
6584                                origPackage = null;
6585                                continue;
6586                            } else if (origPackage.sharedUser != null) {
6587                                // Make sure uid is compatible between packages.
6588                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6589                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6590                                            + " to " + pkg.packageName + ": old uid "
6591                                            + origPackage.sharedUser.name
6592                                            + " differs from " + pkg.mSharedUserId);
6593                                    origPackage = null;
6594                                    continue;
6595                                }
6596                            } else {
6597                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6598                                        + pkg.packageName + " to old name " + origPackage.name);
6599                            }
6600                            break;
6601                        }
6602                    }
6603                }
6604            }
6605
6606            if (mTransferedPackages.contains(pkg.packageName)) {
6607                Slog.w(TAG, "Package " + pkg.packageName
6608                        + " was transferred to another, but its .apk remains");
6609            }
6610
6611            // Just create the setting, don't add it yet. For already existing packages
6612            // the PkgSetting exists already and doesn't have to be created.
6613            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6614                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6615                    pkg.applicationInfo.primaryCpuAbi,
6616                    pkg.applicationInfo.secondaryCpuAbi,
6617                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6618                    user, false);
6619            if (pkgSetting == null) {
6620                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6621                        "Creating application package " + pkg.packageName + " failed");
6622            }
6623
6624            if (pkgSetting.origPackage != null) {
6625                // If we are first transitioning from an original package,
6626                // fix up the new package's name now.  We need to do this after
6627                // looking up the package under its new name, so getPackageLP
6628                // can take care of fiddling things correctly.
6629                pkg.setPackageName(origPackage.name);
6630
6631                // File a report about this.
6632                String msg = "New package " + pkgSetting.realName
6633                        + " renamed to replace old package " + pkgSetting.name;
6634                reportSettingsProblem(Log.WARN, msg);
6635
6636                // Make a note of it.
6637                mTransferedPackages.add(origPackage.name);
6638
6639                // No longer need to retain this.
6640                pkgSetting.origPackage = null;
6641            }
6642
6643            if (realName != null) {
6644                // Make a note of it.
6645                mTransferedPackages.add(pkg.packageName);
6646            }
6647
6648            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6649                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6650            }
6651
6652            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6653                // Check all shared libraries and map to their actual file path.
6654                // We only do this here for apps not on a system dir, because those
6655                // are the only ones that can fail an install due to this.  We
6656                // will take care of the system apps by updating all of their
6657                // library paths after the scan is done.
6658                updateSharedLibrariesLPw(pkg, null);
6659            }
6660
6661            if (mFoundPolicyFile) {
6662                SELinuxMMAC.assignSeinfoValue(pkg);
6663            }
6664
6665            pkg.applicationInfo.uid = pkgSetting.appId;
6666            pkg.mExtras = pkgSetting;
6667            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6668                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6669                    // We just determined the app is signed correctly, so bring
6670                    // over the latest parsed certs.
6671                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6672                } else {
6673                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6674                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6675                                "Package " + pkg.packageName + " upgrade keys do not match the "
6676                                + "previously installed version");
6677                    } else {
6678                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6679                        String msg = "System package " + pkg.packageName
6680                            + " signature changed; retaining data.";
6681                        reportSettingsProblem(Log.WARN, msg);
6682                    }
6683                }
6684            } else {
6685                try {
6686                    verifySignaturesLP(pkgSetting, pkg);
6687                    // We just determined the app is signed correctly, so bring
6688                    // over the latest parsed certs.
6689                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6690                } catch (PackageManagerException e) {
6691                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6692                        throw e;
6693                    }
6694                    // The signature has changed, but this package is in the system
6695                    // image...  let's recover!
6696                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6697                    // However...  if this package is part of a shared user, but it
6698                    // doesn't match the signature of the shared user, let's fail.
6699                    // What this means is that you can't change the signatures
6700                    // associated with an overall shared user, which doesn't seem all
6701                    // that unreasonable.
6702                    if (pkgSetting.sharedUser != null) {
6703                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6704                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6705                            throw new PackageManagerException(
6706                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6707                                            "Signature mismatch for shared user : "
6708                                            + pkgSetting.sharedUser);
6709                        }
6710                    }
6711                    // File a report about this.
6712                    String msg = "System package " + pkg.packageName
6713                        + " signature changed; retaining data.";
6714                    reportSettingsProblem(Log.WARN, msg);
6715                }
6716            }
6717            // Verify that this new package doesn't have any content providers
6718            // that conflict with existing packages.  Only do this if the
6719            // package isn't already installed, since we don't want to break
6720            // things that are installed.
6721            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6722                final int N = pkg.providers.size();
6723                int i;
6724                for (i=0; i<N; i++) {
6725                    PackageParser.Provider p = pkg.providers.get(i);
6726                    if (p.info.authority != null) {
6727                        String names[] = p.info.authority.split(";");
6728                        for (int j = 0; j < names.length; j++) {
6729                            if (mProvidersByAuthority.containsKey(names[j])) {
6730                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6731                                final String otherPackageName =
6732                                        ((other != null && other.getComponentName() != null) ?
6733                                                other.getComponentName().getPackageName() : "?");
6734                                throw new PackageManagerException(
6735                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6736                                                "Can't install because provider name " + names[j]
6737                                                + " (in package " + pkg.applicationInfo.packageName
6738                                                + ") is already used by " + otherPackageName);
6739                            }
6740                        }
6741                    }
6742                }
6743            }
6744
6745            if (pkg.mAdoptPermissions != null) {
6746                // This package wants to adopt ownership of permissions from
6747                // another package.
6748                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6749                    final String origName = pkg.mAdoptPermissions.get(i);
6750                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6751                    if (orig != null) {
6752                        if (verifyPackageUpdateLPr(orig, pkg)) {
6753                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6754                                    + pkg.packageName);
6755                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6756                        }
6757                    }
6758                }
6759            }
6760        }
6761
6762        final String pkgName = pkg.packageName;
6763
6764        final long scanFileTime = scanFile.lastModified();
6765        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6766        pkg.applicationInfo.processName = fixProcessName(
6767                pkg.applicationInfo.packageName,
6768                pkg.applicationInfo.processName,
6769                pkg.applicationInfo.uid);
6770
6771        File dataPath;
6772        if (mPlatformPackage == pkg) {
6773            // The system package is special.
6774            dataPath = new File(Environment.getDataDirectory(), "system");
6775
6776            pkg.applicationInfo.dataDir = dataPath.getPath();
6777
6778        } else {
6779            // This is a normal package, need to make its data directory.
6780            dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid,
6781                    UserHandle.USER_OWNER, pkg.packageName);
6782
6783            boolean uidError = false;
6784            if (dataPath.exists()) {
6785                int currentUid = 0;
6786                try {
6787                    StructStat stat = Os.stat(dataPath.getPath());
6788                    currentUid = stat.st_uid;
6789                } catch (ErrnoException e) {
6790                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6791                }
6792
6793                // If we have mismatched owners for the data path, we have a problem.
6794                if (currentUid != pkg.applicationInfo.uid) {
6795                    boolean recovered = false;
6796                    if (currentUid == 0) {
6797                        // The directory somehow became owned by root.  Wow.
6798                        // This is probably because the system was stopped while
6799                        // installd was in the middle of messing with its libs
6800                        // directory.  Ask installd to fix that.
6801                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6802                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6803                        if (ret >= 0) {
6804                            recovered = true;
6805                            String msg = "Package " + pkg.packageName
6806                                    + " unexpectedly changed to uid 0; recovered to " +
6807                                    + pkg.applicationInfo.uid;
6808                            reportSettingsProblem(Log.WARN, msg);
6809                        }
6810                    }
6811                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6812                            || (scanFlags&SCAN_BOOTING) != 0)) {
6813                        // If this is a system app, we can at least delete its
6814                        // current data so the application will still work.
6815                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6816                        if (ret >= 0) {
6817                            // TODO: Kill the processes first
6818                            // Old data gone!
6819                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6820                                    ? "System package " : "Third party package ";
6821                            String msg = prefix + pkg.packageName
6822                                    + " has changed from uid: "
6823                                    + currentUid + " to "
6824                                    + pkg.applicationInfo.uid + "; old data erased";
6825                            reportSettingsProblem(Log.WARN, msg);
6826                            recovered = true;
6827
6828                            // And now re-install the app.
6829                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6830                                    pkg.applicationInfo.seinfo);
6831                            if (ret == -1) {
6832                                // Ack should not happen!
6833                                msg = prefix + pkg.packageName
6834                                        + " could not have data directory re-created after delete.";
6835                                reportSettingsProblem(Log.WARN, msg);
6836                                throw new PackageManagerException(
6837                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6838                            }
6839                        }
6840                        if (!recovered) {
6841                            mHasSystemUidErrors = true;
6842                        }
6843                    } else if (!recovered) {
6844                        // If we allow this install to proceed, we will be broken.
6845                        // Abort, abort!
6846                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6847                                "scanPackageLI");
6848                    }
6849                    if (!recovered) {
6850                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6851                            + pkg.applicationInfo.uid + "/fs_"
6852                            + currentUid;
6853                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6854                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6855                        String msg = "Package " + pkg.packageName
6856                                + " has mismatched uid: "
6857                                + currentUid + " on disk, "
6858                                + pkg.applicationInfo.uid + " in settings";
6859                        // writer
6860                        synchronized (mPackages) {
6861                            mSettings.mReadMessages.append(msg);
6862                            mSettings.mReadMessages.append('\n');
6863                            uidError = true;
6864                            if (!pkgSetting.uidError) {
6865                                reportSettingsProblem(Log.ERROR, msg);
6866                            }
6867                        }
6868                    }
6869                }
6870                pkg.applicationInfo.dataDir = dataPath.getPath();
6871                if (mShouldRestoreconData) {
6872                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6873                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6874                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6875                }
6876            } else {
6877                if (DEBUG_PACKAGE_SCANNING) {
6878                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6879                        Log.v(TAG, "Want this data dir: " + dataPath);
6880                }
6881                //invoke installer to do the actual installation
6882                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6883                        pkg.applicationInfo.seinfo);
6884                if (ret < 0) {
6885                    // Error from installer
6886                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6887                            "Unable to create data dirs [errorCode=" + ret + "]");
6888                }
6889
6890                if (dataPath.exists()) {
6891                    pkg.applicationInfo.dataDir = dataPath.getPath();
6892                } else {
6893                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6894                    pkg.applicationInfo.dataDir = null;
6895                }
6896            }
6897
6898            pkgSetting.uidError = uidError;
6899        }
6900
6901        final String path = scanFile.getPath();
6902        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6903
6904        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6905            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6906
6907            // Some system apps still use directory structure for native libraries
6908            // in which case we might end up not detecting abi solely based on apk
6909            // structure. Try to detect abi based on directory structure.
6910            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6911                    pkg.applicationInfo.primaryCpuAbi == null) {
6912                setBundledAppAbisAndRoots(pkg, pkgSetting);
6913                setNativeLibraryPaths(pkg);
6914            }
6915
6916        } else {
6917            if ((scanFlags & SCAN_MOVE) != 0) {
6918                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6919                // but we already have this packages package info in the PackageSetting. We just
6920                // use that and derive the native library path based on the new codepath.
6921                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6922                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6923            }
6924
6925            // Set native library paths again. For moves, the path will be updated based on the
6926            // ABIs we've determined above. For non-moves, the path will be updated based on the
6927            // ABIs we determined during compilation, but the path will depend on the final
6928            // package path (after the rename away from the stage path).
6929            setNativeLibraryPaths(pkg);
6930        }
6931
6932        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6933        final int[] userIds = sUserManager.getUserIds();
6934        synchronized (mInstallLock) {
6935            // Make sure all user data directories are ready to roll; we're okay
6936            // if they already exist
6937            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
6938                for (int userId : userIds) {
6939                    if (userId != 0) {
6940                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
6941                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
6942                                pkg.applicationInfo.seinfo);
6943                    }
6944                }
6945            }
6946
6947            // Create a native library symlink only if we have native libraries
6948            // and if the native libraries are 32 bit libraries. We do not provide
6949            // this symlink for 64 bit libraries.
6950            if (pkg.applicationInfo.primaryCpuAbi != null &&
6951                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6952                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6953                for (int userId : userIds) {
6954                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6955                            nativeLibPath, userId) < 0) {
6956                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6957                                "Failed linking native library dir (user=" + userId + ")");
6958                    }
6959                }
6960            }
6961        }
6962
6963        // This is a special case for the "system" package, where the ABI is
6964        // dictated by the zygote configuration (and init.rc). We should keep track
6965        // of this ABI so that we can deal with "normal" applications that run under
6966        // the same UID correctly.
6967        if (mPlatformPackage == pkg) {
6968            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6969                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6970        }
6971
6972        // If there's a mismatch between the abi-override in the package setting
6973        // and the abiOverride specified for the install. Warn about this because we
6974        // would've already compiled the app without taking the package setting into
6975        // account.
6976        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
6977            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
6978                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
6979                        " for package: " + pkg.packageName);
6980            }
6981        }
6982
6983        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6984        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6985        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6986
6987        // Copy the derived override back to the parsed package, so that we can
6988        // update the package settings accordingly.
6989        pkg.cpuAbiOverride = cpuAbiOverride;
6990
6991        if (DEBUG_ABI_SELECTION) {
6992            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6993                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6994                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6995        }
6996
6997        // Push the derived path down into PackageSettings so we know what to
6998        // clean up at uninstall time.
6999        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7000
7001        if (DEBUG_ABI_SELECTION) {
7002            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7003                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7004                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7005        }
7006
7007        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7008            // We don't do this here during boot because we can do it all
7009            // at once after scanning all existing packages.
7010            //
7011            // We also do this *before* we perform dexopt on this package, so that
7012            // we can avoid redundant dexopts, and also to make sure we've got the
7013            // code and package path correct.
7014            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7015                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
7016        }
7017
7018        if ((scanFlags & SCAN_NO_DEX) == 0) {
7019            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
7020                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
7021            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7022                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
7023            }
7024        }
7025        if (mFactoryTest && pkg.requestedPermissions.contains(
7026                android.Manifest.permission.FACTORY_TEST)) {
7027            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7028        }
7029
7030        ArrayList<PackageParser.Package> clientLibPkgs = null;
7031
7032        // writer
7033        synchronized (mPackages) {
7034            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7035                // Only system apps can add new shared libraries.
7036                if (pkg.libraryNames != null) {
7037                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7038                        String name = pkg.libraryNames.get(i);
7039                        boolean allowed = false;
7040                        if (pkg.isUpdatedSystemApp()) {
7041                            // New library entries can only be added through the
7042                            // system image.  This is important to get rid of a lot
7043                            // of nasty edge cases: for example if we allowed a non-
7044                            // system update of the app to add a library, then uninstalling
7045                            // the update would make the library go away, and assumptions
7046                            // we made such as through app install filtering would now
7047                            // have allowed apps on the device which aren't compatible
7048                            // with it.  Better to just have the restriction here, be
7049                            // conservative, and create many fewer cases that can negatively
7050                            // impact the user experience.
7051                            final PackageSetting sysPs = mSettings
7052                                    .getDisabledSystemPkgLPr(pkg.packageName);
7053                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7054                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7055                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7056                                        allowed = true;
7057                                        allowed = true;
7058                                        break;
7059                                    }
7060                                }
7061                            }
7062                        } else {
7063                            allowed = true;
7064                        }
7065                        if (allowed) {
7066                            if (!mSharedLibraries.containsKey(name)) {
7067                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7068                            } else if (!name.equals(pkg.packageName)) {
7069                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7070                                        + name + " already exists; skipping");
7071                            }
7072                        } else {
7073                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7074                                    + name + " that is not declared on system image; skipping");
7075                        }
7076                    }
7077                    if ((scanFlags&SCAN_BOOTING) == 0) {
7078                        // If we are not booting, we need to update any applications
7079                        // that are clients of our shared library.  If we are booting,
7080                        // this will all be done once the scan is complete.
7081                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7082                    }
7083                }
7084            }
7085        }
7086
7087        // We also need to dexopt any apps that are dependent on this library.  Note that
7088        // if these fail, we should abort the install since installing the library will
7089        // result in some apps being broken.
7090        if (clientLibPkgs != null) {
7091            if ((scanFlags & SCAN_NO_DEX) == 0) {
7092                for (int i = 0; i < clientLibPkgs.size(); i++) {
7093                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
7094                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
7095                            null /* instruction sets */, forceDex,
7096                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
7097                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7098                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
7099                                "scanPackageLI failed to dexopt clientLibPkgs");
7100                    }
7101                }
7102            }
7103        }
7104
7105        // Also need to kill any apps that are dependent on the library.
7106        if (clientLibPkgs != null) {
7107            for (int i=0; i<clientLibPkgs.size(); i++) {
7108                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7109                killApplication(clientPkg.applicationInfo.packageName,
7110                        clientPkg.applicationInfo.uid, "update lib");
7111            }
7112        }
7113
7114        // Make sure we're not adding any bogus keyset info
7115        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7116        ksms.assertScannedPackageValid(pkg);
7117
7118        // writer
7119        synchronized (mPackages) {
7120            // We don't expect installation to fail beyond this point
7121
7122            // Add the new setting to mSettings
7123            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7124            // Add the new setting to mPackages
7125            mPackages.put(pkg.applicationInfo.packageName, pkg);
7126            // Make sure we don't accidentally delete its data.
7127            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7128            while (iter.hasNext()) {
7129                PackageCleanItem item = iter.next();
7130                if (pkgName.equals(item.packageName)) {
7131                    iter.remove();
7132                }
7133            }
7134
7135            // Take care of first install / last update times.
7136            if (currentTime != 0) {
7137                if (pkgSetting.firstInstallTime == 0) {
7138                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7139                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7140                    pkgSetting.lastUpdateTime = currentTime;
7141                }
7142            } else if (pkgSetting.firstInstallTime == 0) {
7143                // We need *something*.  Take time time stamp of the file.
7144                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7145            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7146                if (scanFileTime != pkgSetting.timeStamp) {
7147                    // A package on the system image has changed; consider this
7148                    // to be an update.
7149                    pkgSetting.lastUpdateTime = scanFileTime;
7150                }
7151            }
7152
7153            // Add the package's KeySets to the global KeySetManagerService
7154            ksms.addScannedPackageLPw(pkg);
7155
7156            int N = pkg.providers.size();
7157            StringBuilder r = null;
7158            int i;
7159            for (i=0; i<N; i++) {
7160                PackageParser.Provider p = pkg.providers.get(i);
7161                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7162                        p.info.processName, pkg.applicationInfo.uid);
7163                mProviders.addProvider(p);
7164                p.syncable = p.info.isSyncable;
7165                if (p.info.authority != null) {
7166                    String names[] = p.info.authority.split(";");
7167                    p.info.authority = null;
7168                    for (int j = 0; j < names.length; j++) {
7169                        if (j == 1 && p.syncable) {
7170                            // We only want the first authority for a provider to possibly be
7171                            // syncable, so if we already added this provider using a different
7172                            // authority clear the syncable flag. We copy the provider before
7173                            // changing it because the mProviders object contains a reference
7174                            // to a provider that we don't want to change.
7175                            // Only do this for the second authority since the resulting provider
7176                            // object can be the same for all future authorities for this provider.
7177                            p = new PackageParser.Provider(p);
7178                            p.syncable = false;
7179                        }
7180                        if (!mProvidersByAuthority.containsKey(names[j])) {
7181                            mProvidersByAuthority.put(names[j], p);
7182                            if (p.info.authority == null) {
7183                                p.info.authority = names[j];
7184                            } else {
7185                                p.info.authority = p.info.authority + ";" + names[j];
7186                            }
7187                            if (DEBUG_PACKAGE_SCANNING) {
7188                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7189                                    Log.d(TAG, "Registered content provider: " + names[j]
7190                                            + ", className = " + p.info.name + ", isSyncable = "
7191                                            + p.info.isSyncable);
7192                            }
7193                        } else {
7194                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7195                            Slog.w(TAG, "Skipping provider name " + names[j] +
7196                                    " (in package " + pkg.applicationInfo.packageName +
7197                                    "): name already used by "
7198                                    + ((other != null && other.getComponentName() != null)
7199                                            ? other.getComponentName().getPackageName() : "?"));
7200                        }
7201                    }
7202                }
7203                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7204                    if (r == null) {
7205                        r = new StringBuilder(256);
7206                    } else {
7207                        r.append(' ');
7208                    }
7209                    r.append(p.info.name);
7210                }
7211            }
7212            if (r != null) {
7213                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7214            }
7215
7216            N = pkg.services.size();
7217            r = null;
7218            for (i=0; i<N; i++) {
7219                PackageParser.Service s = pkg.services.get(i);
7220                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7221                        s.info.processName, pkg.applicationInfo.uid);
7222                mServices.addService(s);
7223                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7224                    if (r == null) {
7225                        r = new StringBuilder(256);
7226                    } else {
7227                        r.append(' ');
7228                    }
7229                    r.append(s.info.name);
7230                }
7231            }
7232            if (r != null) {
7233                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7234            }
7235
7236            N = pkg.receivers.size();
7237            r = null;
7238            for (i=0; i<N; i++) {
7239                PackageParser.Activity a = pkg.receivers.get(i);
7240                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7241                        a.info.processName, pkg.applicationInfo.uid);
7242                mReceivers.addActivity(a, "receiver");
7243                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7244                    if (r == null) {
7245                        r = new StringBuilder(256);
7246                    } else {
7247                        r.append(' ');
7248                    }
7249                    r.append(a.info.name);
7250                }
7251            }
7252            if (r != null) {
7253                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7254            }
7255
7256            N = pkg.activities.size();
7257            r = null;
7258            for (i=0; i<N; i++) {
7259                PackageParser.Activity a = pkg.activities.get(i);
7260                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7261                        a.info.processName, pkg.applicationInfo.uid);
7262                mActivities.addActivity(a, "activity");
7263                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7264                    if (r == null) {
7265                        r = new StringBuilder(256);
7266                    } else {
7267                        r.append(' ');
7268                    }
7269                    r.append(a.info.name);
7270                }
7271            }
7272            if (r != null) {
7273                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7274            }
7275
7276            N = pkg.permissionGroups.size();
7277            r = null;
7278            for (i=0; i<N; i++) {
7279                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7280                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7281                if (cur == null) {
7282                    mPermissionGroups.put(pg.info.name, pg);
7283                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7284                        if (r == null) {
7285                            r = new StringBuilder(256);
7286                        } else {
7287                            r.append(' ');
7288                        }
7289                        r.append(pg.info.name);
7290                    }
7291                } else {
7292                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7293                            + pg.info.packageName + " ignored: original from "
7294                            + cur.info.packageName);
7295                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7296                        if (r == null) {
7297                            r = new StringBuilder(256);
7298                        } else {
7299                            r.append(' ');
7300                        }
7301                        r.append("DUP:");
7302                        r.append(pg.info.name);
7303                    }
7304                }
7305            }
7306            if (r != null) {
7307                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7308            }
7309
7310            N = pkg.permissions.size();
7311            r = null;
7312            for (i=0; i<N; i++) {
7313                PackageParser.Permission p = pkg.permissions.get(i);
7314
7315                // Now that permission groups have a special meaning, we ignore permission
7316                // groups for legacy apps to prevent unexpected behavior. In particular,
7317                // permissions for one app being granted to someone just becuase they happen
7318                // to be in a group defined by another app (before this had no implications).
7319                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7320                    p.group = mPermissionGroups.get(p.info.group);
7321                    // Warn for a permission in an unknown group.
7322                    if (p.info.group != null && p.group == null) {
7323                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7324                                + p.info.packageName + " in an unknown group " + p.info.group);
7325                    }
7326                }
7327
7328                ArrayMap<String, BasePermission> permissionMap =
7329                        p.tree ? mSettings.mPermissionTrees
7330                                : mSettings.mPermissions;
7331                BasePermission bp = permissionMap.get(p.info.name);
7332
7333                // Allow system apps to redefine non-system permissions
7334                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7335                    final boolean currentOwnerIsSystem = (bp.perm != null
7336                            && isSystemApp(bp.perm.owner));
7337                    if (isSystemApp(p.owner)) {
7338                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7339                            // It's a built-in permission and no owner, take ownership now
7340                            bp.packageSetting = pkgSetting;
7341                            bp.perm = p;
7342                            bp.uid = pkg.applicationInfo.uid;
7343                            bp.sourcePackage = p.info.packageName;
7344                        } else if (!currentOwnerIsSystem) {
7345                            String msg = "New decl " + p.owner + " of permission  "
7346                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7347                            reportSettingsProblem(Log.WARN, msg);
7348                            bp = null;
7349                        }
7350                    }
7351                }
7352
7353                if (bp == null) {
7354                    bp = new BasePermission(p.info.name, p.info.packageName,
7355                            BasePermission.TYPE_NORMAL);
7356                    permissionMap.put(p.info.name, bp);
7357                }
7358
7359                if (bp.perm == null) {
7360                    if (bp.sourcePackage == null
7361                            || bp.sourcePackage.equals(p.info.packageName)) {
7362                        BasePermission tree = findPermissionTreeLP(p.info.name);
7363                        if (tree == null
7364                                || tree.sourcePackage.equals(p.info.packageName)) {
7365                            bp.packageSetting = pkgSetting;
7366                            bp.perm = p;
7367                            bp.uid = pkg.applicationInfo.uid;
7368                            bp.sourcePackage = p.info.packageName;
7369                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7370                                if (r == null) {
7371                                    r = new StringBuilder(256);
7372                                } else {
7373                                    r.append(' ');
7374                                }
7375                                r.append(p.info.name);
7376                            }
7377                        } else {
7378                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7379                                    + p.info.packageName + " ignored: base tree "
7380                                    + tree.name + " is from package "
7381                                    + tree.sourcePackage);
7382                        }
7383                    } else {
7384                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7385                                + p.info.packageName + " ignored: original from "
7386                                + bp.sourcePackage);
7387                    }
7388                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7389                    if (r == null) {
7390                        r = new StringBuilder(256);
7391                    } else {
7392                        r.append(' ');
7393                    }
7394                    r.append("DUP:");
7395                    r.append(p.info.name);
7396                }
7397                if (bp.perm == p) {
7398                    bp.protectionLevel = p.info.protectionLevel;
7399                }
7400            }
7401
7402            if (r != null) {
7403                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7404            }
7405
7406            N = pkg.instrumentation.size();
7407            r = null;
7408            for (i=0; i<N; i++) {
7409                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7410                a.info.packageName = pkg.applicationInfo.packageName;
7411                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7412                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7413                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7414                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7415                a.info.dataDir = pkg.applicationInfo.dataDir;
7416
7417                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7418                // need other information about the application, like the ABI and what not ?
7419                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7420                mInstrumentation.put(a.getComponentName(), a);
7421                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7422                    if (r == null) {
7423                        r = new StringBuilder(256);
7424                    } else {
7425                        r.append(' ');
7426                    }
7427                    r.append(a.info.name);
7428                }
7429            }
7430            if (r != null) {
7431                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7432            }
7433
7434            if (pkg.protectedBroadcasts != null) {
7435                N = pkg.protectedBroadcasts.size();
7436                for (i=0; i<N; i++) {
7437                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7438                }
7439            }
7440
7441            pkgSetting.setTimeStamp(scanFileTime);
7442
7443            // Create idmap files for pairs of (packages, overlay packages).
7444            // Note: "android", ie framework-res.apk, is handled by native layers.
7445            if (pkg.mOverlayTarget != null) {
7446                // This is an overlay package.
7447                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7448                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7449                        mOverlays.put(pkg.mOverlayTarget,
7450                                new ArrayMap<String, PackageParser.Package>());
7451                    }
7452                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7453                    map.put(pkg.packageName, pkg);
7454                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7455                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7456                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7457                                "scanPackageLI failed to createIdmap");
7458                    }
7459                }
7460            } else if (mOverlays.containsKey(pkg.packageName) &&
7461                    !pkg.packageName.equals("android")) {
7462                // This is a regular package, with one or more known overlay packages.
7463                createIdmapsForPackageLI(pkg);
7464            }
7465        }
7466
7467        return pkg;
7468    }
7469
7470    /**
7471     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7472     * is derived purely on the basis of the contents of {@code scanFile} and
7473     * {@code cpuAbiOverride}.
7474     *
7475     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7476     */
7477    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7478                                 String cpuAbiOverride, boolean extractLibs)
7479            throws PackageManagerException {
7480        // TODO: We can probably be smarter about this stuff. For installed apps,
7481        // we can calculate this information at install time once and for all. For
7482        // system apps, we can probably assume that this information doesn't change
7483        // after the first boot scan. As things stand, we do lots of unnecessary work.
7484
7485        // Give ourselves some initial paths; we'll come back for another
7486        // pass once we've determined ABI below.
7487        setNativeLibraryPaths(pkg);
7488
7489        // We would never need to extract libs for forward-locked and external packages,
7490        // since the container service will do it for us. We shouldn't attempt to
7491        // extract libs from system app when it was not updated.
7492        if (pkg.isForwardLocked() || isExternal(pkg) ||
7493            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7494            extractLibs = false;
7495        }
7496
7497        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7498        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7499
7500        NativeLibraryHelper.Handle handle = null;
7501        try {
7502            handle = NativeLibraryHelper.Handle.create(scanFile);
7503            // TODO(multiArch): This can be null for apps that didn't go through the
7504            // usual installation process. We can calculate it again, like we
7505            // do during install time.
7506            //
7507            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7508            // unnecessary.
7509            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7510
7511            // Null out the abis so that they can be recalculated.
7512            pkg.applicationInfo.primaryCpuAbi = null;
7513            pkg.applicationInfo.secondaryCpuAbi = null;
7514            if (isMultiArch(pkg.applicationInfo)) {
7515                // Warn if we've set an abiOverride for multi-lib packages..
7516                // By definition, we need to copy both 32 and 64 bit libraries for
7517                // such packages.
7518                if (pkg.cpuAbiOverride != null
7519                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7520                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7521                }
7522
7523                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7524                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7525                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7526                    if (extractLibs) {
7527                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7528                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7529                                useIsaSpecificSubdirs);
7530                    } else {
7531                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7532                    }
7533                }
7534
7535                maybeThrowExceptionForMultiArchCopy(
7536                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7537
7538                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7539                    if (extractLibs) {
7540                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7541                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7542                                useIsaSpecificSubdirs);
7543                    } else {
7544                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7545                    }
7546                }
7547
7548                maybeThrowExceptionForMultiArchCopy(
7549                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7550
7551                if (abi64 >= 0) {
7552                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7553                }
7554
7555                if (abi32 >= 0) {
7556                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7557                    if (abi64 >= 0) {
7558                        pkg.applicationInfo.secondaryCpuAbi = abi;
7559                    } else {
7560                        pkg.applicationInfo.primaryCpuAbi = abi;
7561                    }
7562                }
7563            } else {
7564                String[] abiList = (cpuAbiOverride != null) ?
7565                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7566
7567                // Enable gross and lame hacks for apps that are built with old
7568                // SDK tools. We must scan their APKs for renderscript bitcode and
7569                // not launch them if it's present. Don't bother checking on devices
7570                // that don't have 64 bit support.
7571                boolean needsRenderScriptOverride = false;
7572                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7573                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7574                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7575                    needsRenderScriptOverride = true;
7576                }
7577
7578                final int copyRet;
7579                if (extractLibs) {
7580                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7581                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7582                } else {
7583                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7584                }
7585
7586                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7587                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7588                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7589                }
7590
7591                if (copyRet >= 0) {
7592                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7593                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7594                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7595                } else if (needsRenderScriptOverride) {
7596                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7597                }
7598            }
7599        } catch (IOException ioe) {
7600            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7601        } finally {
7602            IoUtils.closeQuietly(handle);
7603        }
7604
7605        // Now that we've calculated the ABIs and determined if it's an internal app,
7606        // we will go ahead and populate the nativeLibraryPath.
7607        setNativeLibraryPaths(pkg);
7608    }
7609
7610    /**
7611     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7612     * i.e, so that all packages can be run inside a single process if required.
7613     *
7614     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7615     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7616     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7617     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7618     * updating a package that belongs to a shared user.
7619     *
7620     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7621     * adds unnecessary complexity.
7622     */
7623    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7624            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7625        String requiredInstructionSet = null;
7626        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7627            requiredInstructionSet = VMRuntime.getInstructionSet(
7628                     scannedPackage.applicationInfo.primaryCpuAbi);
7629        }
7630
7631        PackageSetting requirer = null;
7632        for (PackageSetting ps : packagesForUser) {
7633            // If packagesForUser contains scannedPackage, we skip it. This will happen
7634            // when scannedPackage is an update of an existing package. Without this check,
7635            // we will never be able to change the ABI of any package belonging to a shared
7636            // user, even if it's compatible with other packages.
7637            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7638                if (ps.primaryCpuAbiString == null) {
7639                    continue;
7640                }
7641
7642                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7643                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7644                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7645                    // this but there's not much we can do.
7646                    String errorMessage = "Instruction set mismatch, "
7647                            + ((requirer == null) ? "[caller]" : requirer)
7648                            + " requires " + requiredInstructionSet + " whereas " + ps
7649                            + " requires " + instructionSet;
7650                    Slog.w(TAG, errorMessage);
7651                }
7652
7653                if (requiredInstructionSet == null) {
7654                    requiredInstructionSet = instructionSet;
7655                    requirer = ps;
7656                }
7657            }
7658        }
7659
7660        if (requiredInstructionSet != null) {
7661            String adjustedAbi;
7662            if (requirer != null) {
7663                // requirer != null implies that either scannedPackage was null or that scannedPackage
7664                // did not require an ABI, in which case we have to adjust scannedPackage to match
7665                // the ABI of the set (which is the same as requirer's ABI)
7666                adjustedAbi = requirer.primaryCpuAbiString;
7667                if (scannedPackage != null) {
7668                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7669                }
7670            } else {
7671                // requirer == null implies that we're updating all ABIs in the set to
7672                // match scannedPackage.
7673                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7674            }
7675
7676            for (PackageSetting ps : packagesForUser) {
7677                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7678                    if (ps.primaryCpuAbiString != null) {
7679                        continue;
7680                    }
7681
7682                    ps.primaryCpuAbiString = adjustedAbi;
7683                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7684                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7685                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7686
7687                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7688                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7689                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7690                            ps.primaryCpuAbiString = null;
7691                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7692                            return;
7693                        } else {
7694                            mInstaller.rmdex(ps.codePathString,
7695                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7696                        }
7697                    }
7698                }
7699            }
7700        }
7701    }
7702
7703    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7704        synchronized (mPackages) {
7705            mResolverReplaced = true;
7706            // Set up information for custom user intent resolution activity.
7707            mResolveActivity.applicationInfo = pkg.applicationInfo;
7708            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7709            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7710            mResolveActivity.processName = pkg.applicationInfo.packageName;
7711            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7712            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7713                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7714            mResolveActivity.theme = 0;
7715            mResolveActivity.exported = true;
7716            mResolveActivity.enabled = true;
7717            mResolveInfo.activityInfo = mResolveActivity;
7718            mResolveInfo.priority = 0;
7719            mResolveInfo.preferredOrder = 0;
7720            mResolveInfo.match = 0;
7721            mResolveComponentName = mCustomResolverComponentName;
7722            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7723                    mResolveComponentName);
7724        }
7725    }
7726
7727    private static String calculateBundledApkRoot(final String codePathString) {
7728        final File codePath = new File(codePathString);
7729        final File codeRoot;
7730        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7731            codeRoot = Environment.getRootDirectory();
7732        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7733            codeRoot = Environment.getOemDirectory();
7734        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7735            codeRoot = Environment.getVendorDirectory();
7736        } else {
7737            // Unrecognized code path; take its top real segment as the apk root:
7738            // e.g. /something/app/blah.apk => /something
7739            try {
7740                File f = codePath.getCanonicalFile();
7741                File parent = f.getParentFile();    // non-null because codePath is a file
7742                File tmp;
7743                while ((tmp = parent.getParentFile()) != null) {
7744                    f = parent;
7745                    parent = tmp;
7746                }
7747                codeRoot = f;
7748                Slog.w(TAG, "Unrecognized code path "
7749                        + codePath + " - using " + codeRoot);
7750            } catch (IOException e) {
7751                // Can't canonicalize the code path -- shenanigans?
7752                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7753                return Environment.getRootDirectory().getPath();
7754            }
7755        }
7756        return codeRoot.getPath();
7757    }
7758
7759    /**
7760     * Derive and set the location of native libraries for the given package,
7761     * which varies depending on where and how the package was installed.
7762     */
7763    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7764        final ApplicationInfo info = pkg.applicationInfo;
7765        final String codePath = pkg.codePath;
7766        final File codeFile = new File(codePath);
7767        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7768        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7769
7770        info.nativeLibraryRootDir = null;
7771        info.nativeLibraryRootRequiresIsa = false;
7772        info.nativeLibraryDir = null;
7773        info.secondaryNativeLibraryDir = null;
7774
7775        if (isApkFile(codeFile)) {
7776            // Monolithic install
7777            if (bundledApp) {
7778                // If "/system/lib64/apkname" exists, assume that is the per-package
7779                // native library directory to use; otherwise use "/system/lib/apkname".
7780                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7781                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7782                        getPrimaryInstructionSet(info));
7783
7784                // This is a bundled system app so choose the path based on the ABI.
7785                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7786                // is just the default path.
7787                final String apkName = deriveCodePathName(codePath);
7788                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7789                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7790                        apkName).getAbsolutePath();
7791
7792                if (info.secondaryCpuAbi != null) {
7793                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7794                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7795                            secondaryLibDir, apkName).getAbsolutePath();
7796                }
7797            } else if (asecApp) {
7798                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7799                        .getAbsolutePath();
7800            } else {
7801                final String apkName = deriveCodePathName(codePath);
7802                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7803                        .getAbsolutePath();
7804            }
7805
7806            info.nativeLibraryRootRequiresIsa = false;
7807            info.nativeLibraryDir = info.nativeLibraryRootDir;
7808        } else {
7809            // Cluster install
7810            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7811            info.nativeLibraryRootRequiresIsa = true;
7812
7813            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7814                    getPrimaryInstructionSet(info)).getAbsolutePath();
7815
7816            if (info.secondaryCpuAbi != null) {
7817                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7818                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7819            }
7820        }
7821    }
7822
7823    /**
7824     * Calculate the abis and roots for a bundled app. These can uniquely
7825     * be determined from the contents of the system partition, i.e whether
7826     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7827     * of this information, and instead assume that the system was built
7828     * sensibly.
7829     */
7830    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7831                                           PackageSetting pkgSetting) {
7832        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7833
7834        // If "/system/lib64/apkname" exists, assume that is the per-package
7835        // native library directory to use; otherwise use "/system/lib/apkname".
7836        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7837        setBundledAppAbi(pkg, apkRoot, apkName);
7838        // pkgSetting might be null during rescan following uninstall of updates
7839        // to a bundled app, so accommodate that possibility.  The settings in
7840        // that case will be established later from the parsed package.
7841        //
7842        // If the settings aren't null, sync them up with what we've just derived.
7843        // note that apkRoot isn't stored in the package settings.
7844        if (pkgSetting != null) {
7845            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7846            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7847        }
7848    }
7849
7850    /**
7851     * Deduces the ABI of a bundled app and sets the relevant fields on the
7852     * parsed pkg object.
7853     *
7854     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7855     *        under which system libraries are installed.
7856     * @param apkName the name of the installed package.
7857     */
7858    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7859        final File codeFile = new File(pkg.codePath);
7860
7861        final boolean has64BitLibs;
7862        final boolean has32BitLibs;
7863        if (isApkFile(codeFile)) {
7864            // Monolithic install
7865            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7866            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7867        } else {
7868            // Cluster install
7869            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7870            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7871                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7872                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7873                has64BitLibs = (new File(rootDir, isa)).exists();
7874            } else {
7875                has64BitLibs = false;
7876            }
7877            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7878                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7879                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7880                has32BitLibs = (new File(rootDir, isa)).exists();
7881            } else {
7882                has32BitLibs = false;
7883            }
7884        }
7885
7886        if (has64BitLibs && !has32BitLibs) {
7887            // The package has 64 bit libs, but not 32 bit libs. Its primary
7888            // ABI should be 64 bit. We can safely assume here that the bundled
7889            // native libraries correspond to the most preferred ABI in the list.
7890
7891            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7892            pkg.applicationInfo.secondaryCpuAbi = null;
7893        } else if (has32BitLibs && !has64BitLibs) {
7894            // The package has 32 bit libs but not 64 bit libs. Its primary
7895            // ABI should be 32 bit.
7896
7897            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7898            pkg.applicationInfo.secondaryCpuAbi = null;
7899        } else if (has32BitLibs && has64BitLibs) {
7900            // The application has both 64 and 32 bit bundled libraries. We check
7901            // here that the app declares multiArch support, and warn if it doesn't.
7902            //
7903            // We will be lenient here and record both ABIs. The primary will be the
7904            // ABI that's higher on the list, i.e, a device that's configured to prefer
7905            // 64 bit apps will see a 64 bit primary ABI,
7906
7907            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7908                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7909            }
7910
7911            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7912                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7913                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7914            } else {
7915                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7916                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7917            }
7918        } else {
7919            pkg.applicationInfo.primaryCpuAbi = null;
7920            pkg.applicationInfo.secondaryCpuAbi = null;
7921        }
7922    }
7923
7924    private void killApplication(String pkgName, int appId, String reason) {
7925        // Request the ActivityManager to kill the process(only for existing packages)
7926        // so that we do not end up in a confused state while the user is still using the older
7927        // version of the application while the new one gets installed.
7928        IActivityManager am = ActivityManagerNative.getDefault();
7929        if (am != null) {
7930            try {
7931                am.killApplicationWithAppId(pkgName, appId, reason);
7932            } catch (RemoteException e) {
7933            }
7934        }
7935    }
7936
7937    void removePackageLI(PackageSetting ps, boolean chatty) {
7938        if (DEBUG_INSTALL) {
7939            if (chatty)
7940                Log.d(TAG, "Removing package " + ps.name);
7941        }
7942
7943        // writer
7944        synchronized (mPackages) {
7945            mPackages.remove(ps.name);
7946            final PackageParser.Package pkg = ps.pkg;
7947            if (pkg != null) {
7948                cleanPackageDataStructuresLILPw(pkg, chatty);
7949            }
7950        }
7951    }
7952
7953    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7954        if (DEBUG_INSTALL) {
7955            if (chatty)
7956                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7957        }
7958
7959        // writer
7960        synchronized (mPackages) {
7961            mPackages.remove(pkg.applicationInfo.packageName);
7962            cleanPackageDataStructuresLILPw(pkg, chatty);
7963        }
7964    }
7965
7966    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7967        int N = pkg.providers.size();
7968        StringBuilder r = null;
7969        int i;
7970        for (i=0; i<N; i++) {
7971            PackageParser.Provider p = pkg.providers.get(i);
7972            mProviders.removeProvider(p);
7973            if (p.info.authority == null) {
7974
7975                /* There was another ContentProvider with this authority when
7976                 * this app was installed so this authority is null,
7977                 * Ignore it as we don't have to unregister the provider.
7978                 */
7979                continue;
7980            }
7981            String names[] = p.info.authority.split(";");
7982            for (int j = 0; j < names.length; j++) {
7983                if (mProvidersByAuthority.get(names[j]) == p) {
7984                    mProvidersByAuthority.remove(names[j]);
7985                    if (DEBUG_REMOVE) {
7986                        if (chatty)
7987                            Log.d(TAG, "Unregistered content provider: " + names[j]
7988                                    + ", className = " + p.info.name + ", isSyncable = "
7989                                    + p.info.isSyncable);
7990                    }
7991                }
7992            }
7993            if (DEBUG_REMOVE && chatty) {
7994                if (r == null) {
7995                    r = new StringBuilder(256);
7996                } else {
7997                    r.append(' ');
7998                }
7999                r.append(p.info.name);
8000            }
8001        }
8002        if (r != null) {
8003            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8004        }
8005
8006        N = pkg.services.size();
8007        r = null;
8008        for (i=0; i<N; i++) {
8009            PackageParser.Service s = pkg.services.get(i);
8010            mServices.removeService(s);
8011            if (chatty) {
8012                if (r == null) {
8013                    r = new StringBuilder(256);
8014                } else {
8015                    r.append(' ');
8016                }
8017                r.append(s.info.name);
8018            }
8019        }
8020        if (r != null) {
8021            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8022        }
8023
8024        N = pkg.receivers.size();
8025        r = null;
8026        for (i=0; i<N; i++) {
8027            PackageParser.Activity a = pkg.receivers.get(i);
8028            mReceivers.removeActivity(a, "receiver");
8029            if (DEBUG_REMOVE && chatty) {
8030                if (r == null) {
8031                    r = new StringBuilder(256);
8032                } else {
8033                    r.append(' ');
8034                }
8035                r.append(a.info.name);
8036            }
8037        }
8038        if (r != null) {
8039            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8040        }
8041
8042        N = pkg.activities.size();
8043        r = null;
8044        for (i=0; i<N; i++) {
8045            PackageParser.Activity a = pkg.activities.get(i);
8046            mActivities.removeActivity(a, "activity");
8047            if (DEBUG_REMOVE && chatty) {
8048                if (r == null) {
8049                    r = new StringBuilder(256);
8050                } else {
8051                    r.append(' ');
8052                }
8053                r.append(a.info.name);
8054            }
8055        }
8056        if (r != null) {
8057            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8058        }
8059
8060        N = pkg.permissions.size();
8061        r = null;
8062        for (i=0; i<N; i++) {
8063            PackageParser.Permission p = pkg.permissions.get(i);
8064            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8065            if (bp == null) {
8066                bp = mSettings.mPermissionTrees.get(p.info.name);
8067            }
8068            if (bp != null && bp.perm == p) {
8069                bp.perm = null;
8070                if (DEBUG_REMOVE && chatty) {
8071                    if (r == null) {
8072                        r = new StringBuilder(256);
8073                    } else {
8074                        r.append(' ');
8075                    }
8076                    r.append(p.info.name);
8077                }
8078            }
8079            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8080                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8081                if (appOpPerms != null) {
8082                    appOpPerms.remove(pkg.packageName);
8083                }
8084            }
8085        }
8086        if (r != null) {
8087            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8088        }
8089
8090        N = pkg.requestedPermissions.size();
8091        r = null;
8092        for (i=0; i<N; i++) {
8093            String perm = pkg.requestedPermissions.get(i);
8094            BasePermission bp = mSettings.mPermissions.get(perm);
8095            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8096                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8097                if (appOpPerms != null) {
8098                    appOpPerms.remove(pkg.packageName);
8099                    if (appOpPerms.isEmpty()) {
8100                        mAppOpPermissionPackages.remove(perm);
8101                    }
8102                }
8103            }
8104        }
8105        if (r != null) {
8106            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8107        }
8108
8109        N = pkg.instrumentation.size();
8110        r = null;
8111        for (i=0; i<N; i++) {
8112            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8113            mInstrumentation.remove(a.getComponentName());
8114            if (DEBUG_REMOVE && chatty) {
8115                if (r == null) {
8116                    r = new StringBuilder(256);
8117                } else {
8118                    r.append(' ');
8119                }
8120                r.append(a.info.name);
8121            }
8122        }
8123        if (r != null) {
8124            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8125        }
8126
8127        r = null;
8128        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8129            // Only system apps can hold shared libraries.
8130            if (pkg.libraryNames != null) {
8131                for (i=0; i<pkg.libraryNames.size(); i++) {
8132                    String name = pkg.libraryNames.get(i);
8133                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8134                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8135                        mSharedLibraries.remove(name);
8136                        if (DEBUG_REMOVE && chatty) {
8137                            if (r == null) {
8138                                r = new StringBuilder(256);
8139                            } else {
8140                                r.append(' ');
8141                            }
8142                            r.append(name);
8143                        }
8144                    }
8145                }
8146            }
8147        }
8148        if (r != null) {
8149            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8150        }
8151    }
8152
8153    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8154        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8155            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8156                return true;
8157            }
8158        }
8159        return false;
8160    }
8161
8162    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8163    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8164    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8165
8166    private void updatePermissionsLPw(String changingPkg,
8167            PackageParser.Package pkgInfo, int flags) {
8168        // Make sure there are no dangling permission trees.
8169        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8170        while (it.hasNext()) {
8171            final BasePermission bp = it.next();
8172            if (bp.packageSetting == null) {
8173                // We may not yet have parsed the package, so just see if
8174                // we still know about its settings.
8175                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8176            }
8177            if (bp.packageSetting == null) {
8178                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8179                        + " from package " + bp.sourcePackage);
8180                it.remove();
8181            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8182                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8183                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8184                            + " from package " + bp.sourcePackage);
8185                    flags |= UPDATE_PERMISSIONS_ALL;
8186                    it.remove();
8187                }
8188            }
8189        }
8190
8191        // Make sure all dynamic permissions have been assigned to a package,
8192        // and make sure there are no dangling permissions.
8193        it = mSettings.mPermissions.values().iterator();
8194        while (it.hasNext()) {
8195            final BasePermission bp = it.next();
8196            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8197                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8198                        + bp.name + " pkg=" + bp.sourcePackage
8199                        + " info=" + bp.pendingInfo);
8200                if (bp.packageSetting == null && bp.pendingInfo != null) {
8201                    final BasePermission tree = findPermissionTreeLP(bp.name);
8202                    if (tree != null && tree.perm != null) {
8203                        bp.packageSetting = tree.packageSetting;
8204                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8205                                new PermissionInfo(bp.pendingInfo));
8206                        bp.perm.info.packageName = tree.perm.info.packageName;
8207                        bp.perm.info.name = bp.name;
8208                        bp.uid = tree.uid;
8209                    }
8210                }
8211            }
8212            if (bp.packageSetting == null) {
8213                // We may not yet have parsed the package, so just see if
8214                // we still know about its settings.
8215                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8216            }
8217            if (bp.packageSetting == null) {
8218                Slog.w(TAG, "Removing dangling permission: " + bp.name
8219                        + " from package " + bp.sourcePackage);
8220                it.remove();
8221            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8222                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8223                    Slog.i(TAG, "Removing old permission: " + bp.name
8224                            + " from package " + bp.sourcePackage);
8225                    flags |= UPDATE_PERMISSIONS_ALL;
8226                    it.remove();
8227                }
8228            }
8229        }
8230
8231        // Now update the permissions for all packages, in particular
8232        // replace the granted permissions of the system packages.
8233        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8234            for (PackageParser.Package pkg : mPackages.values()) {
8235                if (pkg != pkgInfo) {
8236                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8237                            changingPkg);
8238                }
8239            }
8240        }
8241
8242        if (pkgInfo != null) {
8243            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8244        }
8245    }
8246
8247    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8248            String packageOfInterest) {
8249        // IMPORTANT: There are two types of permissions: install and runtime.
8250        // Install time permissions are granted when the app is installed to
8251        // all device users and users added in the future. Runtime permissions
8252        // are granted at runtime explicitly to specific users. Normal and signature
8253        // protected permissions are install time permissions. Dangerous permissions
8254        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8255        // otherwise they are runtime permissions. This function does not manage
8256        // runtime permissions except for the case an app targeting Lollipop MR1
8257        // being upgraded to target a newer SDK, in which case dangerous permissions
8258        // are transformed from install time to runtime ones.
8259
8260        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8261        if (ps == null) {
8262            return;
8263        }
8264
8265        PermissionsState permissionsState = ps.getPermissionsState();
8266        PermissionsState origPermissions = permissionsState;
8267
8268        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8269
8270        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8271
8272        boolean changedInstallPermission = false;
8273
8274        if (replace) {
8275            ps.installPermissionsFixed = false;
8276            if (!ps.isSharedUser()) {
8277                origPermissions = new PermissionsState(permissionsState);
8278                permissionsState.reset();
8279            }
8280        }
8281
8282        permissionsState.setGlobalGids(mGlobalGids);
8283
8284        final int N = pkg.requestedPermissions.size();
8285        for (int i=0; i<N; i++) {
8286            final String name = pkg.requestedPermissions.get(i);
8287            final BasePermission bp = mSettings.mPermissions.get(name);
8288
8289            if (DEBUG_INSTALL) {
8290                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8291            }
8292
8293            if (bp == null || bp.packageSetting == null) {
8294                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8295                    Slog.w(TAG, "Unknown permission " + name
8296                            + " in package " + pkg.packageName);
8297                }
8298                continue;
8299            }
8300
8301            final String perm = bp.name;
8302            boolean allowedSig = false;
8303            int grant = GRANT_DENIED;
8304
8305            // Keep track of app op permissions.
8306            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8307                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8308                if (pkgs == null) {
8309                    pkgs = new ArraySet<>();
8310                    mAppOpPermissionPackages.put(bp.name, pkgs);
8311                }
8312                pkgs.add(pkg.packageName);
8313            }
8314
8315            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8316            switch (level) {
8317                case PermissionInfo.PROTECTION_NORMAL: {
8318                    // For all apps normal permissions are install time ones.
8319                    grant = GRANT_INSTALL;
8320                } break;
8321
8322                case PermissionInfo.PROTECTION_DANGEROUS: {
8323                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8324                        // For legacy apps dangerous permissions are install time ones.
8325                        grant = GRANT_INSTALL_LEGACY;
8326                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8327                        // For legacy apps that became modern, install becomes runtime.
8328                        grant = GRANT_UPGRADE;
8329                    } else {
8330                        // For modern apps keep runtime permissions unchanged.
8331                        grant = GRANT_RUNTIME;
8332                    }
8333                } break;
8334
8335                case PermissionInfo.PROTECTION_SIGNATURE: {
8336                    // For all apps signature permissions are install time ones.
8337                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8338                    if (allowedSig) {
8339                        grant = GRANT_INSTALL;
8340                    }
8341                } break;
8342            }
8343
8344            if (DEBUG_INSTALL) {
8345                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8346            }
8347
8348            if (grant != GRANT_DENIED) {
8349                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8350                    // If this is an existing, non-system package, then
8351                    // we can't add any new permissions to it.
8352                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8353                        // Except...  if this is a permission that was added
8354                        // to the platform (note: need to only do this when
8355                        // updating the platform).
8356                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8357                            grant = GRANT_DENIED;
8358                        }
8359                    }
8360                }
8361
8362                switch (grant) {
8363                    case GRANT_INSTALL: {
8364                        // Revoke this as runtime permission to handle the case of
8365                        // a runtime permission being downgraded to an install one.
8366                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8367                            if (origPermissions.getRuntimePermissionState(
8368                                    bp.name, userId) != null) {
8369                                // Revoke the runtime permission and clear the flags.
8370                                origPermissions.revokeRuntimePermission(bp, userId);
8371                                origPermissions.updatePermissionFlags(bp, userId,
8372                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8373                                // If we revoked a permission permission, we have to write.
8374                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8375                                        changedRuntimePermissionUserIds, userId);
8376                            }
8377                        }
8378                        // Grant an install permission.
8379                        if (permissionsState.grantInstallPermission(bp) !=
8380                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8381                            changedInstallPermission = true;
8382                        }
8383                    } break;
8384
8385                    case GRANT_INSTALL_LEGACY: {
8386                        // Grant an install permission.
8387                        if (permissionsState.grantInstallPermission(bp) !=
8388                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8389                            changedInstallPermission = true;
8390                        }
8391                    } break;
8392
8393                    case GRANT_RUNTIME: {
8394                        // Grant previously granted runtime permissions.
8395                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8396                            PermissionState permissionState = origPermissions
8397                                    .getRuntimePermissionState(bp.name, userId);
8398                            final int flags = permissionState != null
8399                                    ? permissionState.getFlags() : 0;
8400                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8401                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8402                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8403                                    // If we cannot put the permission as it was, we have to write.
8404                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8405                                            changedRuntimePermissionUserIds, userId);
8406                                }
8407                            }
8408                            // Propagate the permission flags.
8409                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8410                        }
8411                    } break;
8412
8413                    case GRANT_UPGRADE: {
8414                        // Grant runtime permissions for a previously held install permission.
8415                        PermissionState permissionState = origPermissions
8416                                .getInstallPermissionState(bp.name);
8417                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8418
8419                        if (origPermissions.revokeInstallPermission(bp)
8420                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8421                            // We will be transferring the permission flags, so clear them.
8422                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8423                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8424                            changedInstallPermission = true;
8425                        }
8426
8427                        // If the permission is not to be promoted to runtime we ignore it and
8428                        // also its other flags as they are not applicable to install permissions.
8429                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8430                            for (int userId : currentUserIds) {
8431                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8432                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8433                                    // Transfer the permission flags.
8434                                    permissionsState.updatePermissionFlags(bp, userId,
8435                                            flags, flags);
8436                                    // If we granted the permission, we have to write.
8437                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8438                                            changedRuntimePermissionUserIds, userId);
8439                                }
8440                            }
8441                        }
8442                    } break;
8443
8444                    default: {
8445                        if (packageOfInterest == null
8446                                || packageOfInterest.equals(pkg.packageName)) {
8447                            Slog.w(TAG, "Not granting permission " + perm
8448                                    + " to package " + pkg.packageName
8449                                    + " because it was previously installed without");
8450                        }
8451                    } break;
8452                }
8453            } else {
8454                if (permissionsState.revokeInstallPermission(bp) !=
8455                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8456                    // Also drop the permission flags.
8457                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8458                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8459                    changedInstallPermission = true;
8460                    Slog.i(TAG, "Un-granting permission " + perm
8461                            + " from package " + pkg.packageName
8462                            + " (protectionLevel=" + bp.protectionLevel
8463                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8464                            + ")");
8465                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8466                    // Don't print warning for app op permissions, since it is fine for them
8467                    // not to be granted, there is a UI for the user to decide.
8468                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8469                        Slog.w(TAG, "Not granting permission " + perm
8470                                + " to package " + pkg.packageName
8471                                + " (protectionLevel=" + bp.protectionLevel
8472                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8473                                + ")");
8474                    }
8475                }
8476            }
8477        }
8478
8479        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8480                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8481            // This is the first that we have heard about this package, so the
8482            // permissions we have now selected are fixed until explicitly
8483            // changed.
8484            ps.installPermissionsFixed = true;
8485        }
8486
8487        // Persist the runtime permissions state for users with changes.
8488        for (int userId : changedRuntimePermissionUserIds) {
8489            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8490        }
8491    }
8492
8493    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8494        boolean allowed = false;
8495        final int NP = PackageParser.NEW_PERMISSIONS.length;
8496        for (int ip=0; ip<NP; ip++) {
8497            final PackageParser.NewPermissionInfo npi
8498                    = PackageParser.NEW_PERMISSIONS[ip];
8499            if (npi.name.equals(perm)
8500                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8501                allowed = true;
8502                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8503                        + pkg.packageName);
8504                break;
8505            }
8506        }
8507        return allowed;
8508    }
8509
8510    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8511            BasePermission bp, PermissionsState origPermissions) {
8512        boolean allowed;
8513        allowed = (compareSignatures(
8514                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8515                        == PackageManager.SIGNATURE_MATCH)
8516                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8517                        == PackageManager.SIGNATURE_MATCH);
8518        if (!allowed && (bp.protectionLevel
8519                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8520            if (isSystemApp(pkg)) {
8521                // For updated system applications, a system permission
8522                // is granted only if it had been defined by the original application.
8523                if (pkg.isUpdatedSystemApp()) {
8524                    final PackageSetting sysPs = mSettings
8525                            .getDisabledSystemPkgLPr(pkg.packageName);
8526                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8527                        // If the original was granted this permission, we take
8528                        // that grant decision as read and propagate it to the
8529                        // update.
8530                        if (sysPs.isPrivileged()) {
8531                            allowed = true;
8532                        }
8533                    } else {
8534                        // The system apk may have been updated with an older
8535                        // version of the one on the data partition, but which
8536                        // granted a new system permission that it didn't have
8537                        // before.  In this case we do want to allow the app to
8538                        // now get the new permission if the ancestral apk is
8539                        // privileged to get it.
8540                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8541                            for (int j=0;
8542                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8543                                if (perm.equals(
8544                                        sysPs.pkg.requestedPermissions.get(j))) {
8545                                    allowed = true;
8546                                    break;
8547                                }
8548                            }
8549                        }
8550                    }
8551                } else {
8552                    allowed = isPrivilegedApp(pkg);
8553                }
8554            }
8555        }
8556        if (!allowed) {
8557            if (!allowed && (bp.protectionLevel
8558                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8559                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) {
8560                // If this was a previously normal/dangerous permission that got moved
8561                // to a system permission as part of the runtime permission redesign, then
8562                // we still want to blindly grant it to old apps.
8563                allowed = true;
8564            }
8565            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8566                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8567                // If this permission is to be granted to the system installer and
8568                // this app is an installer, then it gets the permission.
8569                allowed = true;
8570            }
8571            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8572                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8573                // If this permission is to be granted to the system verifier and
8574                // this app is a verifier, then it gets the permission.
8575                allowed = true;
8576            }
8577            if (!allowed && (bp.protectionLevel
8578                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8579                    && isSystemApp(pkg)) {
8580                // Any pre-installed system app is allowed to get this permission.
8581                allowed = true;
8582            }
8583            if (!allowed && (bp.protectionLevel
8584                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8585                // For development permissions, a development permission
8586                // is granted only if it was already granted.
8587                allowed = origPermissions.hasInstallPermission(perm);
8588            }
8589        }
8590        return allowed;
8591    }
8592
8593    final class ActivityIntentResolver
8594            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8595        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8596                boolean defaultOnly, int userId) {
8597            if (!sUserManager.exists(userId)) return null;
8598            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8599            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8600        }
8601
8602        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8603                int userId) {
8604            if (!sUserManager.exists(userId)) return null;
8605            mFlags = flags;
8606            return super.queryIntent(intent, resolvedType,
8607                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8608        }
8609
8610        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8611                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8612            if (!sUserManager.exists(userId)) return null;
8613            if (packageActivities == null) {
8614                return null;
8615            }
8616            mFlags = flags;
8617            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8618            final int N = packageActivities.size();
8619            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8620                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8621
8622            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8623            for (int i = 0; i < N; ++i) {
8624                intentFilters = packageActivities.get(i).intents;
8625                if (intentFilters != null && intentFilters.size() > 0) {
8626                    PackageParser.ActivityIntentInfo[] array =
8627                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8628                    intentFilters.toArray(array);
8629                    listCut.add(array);
8630                }
8631            }
8632            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8633        }
8634
8635        public final void addActivity(PackageParser.Activity a, String type) {
8636            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8637            mActivities.put(a.getComponentName(), a);
8638            if (DEBUG_SHOW_INFO)
8639                Log.v(
8640                TAG, "  " + type + " " +
8641                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8642            if (DEBUG_SHOW_INFO)
8643                Log.v(TAG, "    Class=" + a.info.name);
8644            final int NI = a.intents.size();
8645            for (int j=0; j<NI; j++) {
8646                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8647                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8648                    intent.setPriority(0);
8649                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8650                            + a.className + " with priority > 0, forcing to 0");
8651                }
8652                if (DEBUG_SHOW_INFO) {
8653                    Log.v(TAG, "    IntentFilter:");
8654                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8655                }
8656                if (!intent.debugCheck()) {
8657                    Log.w(TAG, "==> For Activity " + a.info.name);
8658                }
8659                addFilter(intent);
8660            }
8661        }
8662
8663        public final void removeActivity(PackageParser.Activity a, String type) {
8664            mActivities.remove(a.getComponentName());
8665            if (DEBUG_SHOW_INFO) {
8666                Log.v(TAG, "  " + type + " "
8667                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8668                                : a.info.name) + ":");
8669                Log.v(TAG, "    Class=" + a.info.name);
8670            }
8671            final int NI = a.intents.size();
8672            for (int j=0; j<NI; j++) {
8673                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8674                if (DEBUG_SHOW_INFO) {
8675                    Log.v(TAG, "    IntentFilter:");
8676                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8677                }
8678                removeFilter(intent);
8679            }
8680        }
8681
8682        @Override
8683        protected boolean allowFilterResult(
8684                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8685            ActivityInfo filterAi = filter.activity.info;
8686            for (int i=dest.size()-1; i>=0; i--) {
8687                ActivityInfo destAi = dest.get(i).activityInfo;
8688                if (destAi.name == filterAi.name
8689                        && destAi.packageName == filterAi.packageName) {
8690                    return false;
8691                }
8692            }
8693            return true;
8694        }
8695
8696        @Override
8697        protected ActivityIntentInfo[] newArray(int size) {
8698            return new ActivityIntentInfo[size];
8699        }
8700
8701        @Override
8702        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8703            if (!sUserManager.exists(userId)) return true;
8704            PackageParser.Package p = filter.activity.owner;
8705            if (p != null) {
8706                PackageSetting ps = (PackageSetting)p.mExtras;
8707                if (ps != null) {
8708                    // System apps are never considered stopped for purposes of
8709                    // filtering, because there may be no way for the user to
8710                    // actually re-launch them.
8711                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8712                            && ps.getStopped(userId);
8713                }
8714            }
8715            return false;
8716        }
8717
8718        @Override
8719        protected boolean isPackageForFilter(String packageName,
8720                PackageParser.ActivityIntentInfo info) {
8721            return packageName.equals(info.activity.owner.packageName);
8722        }
8723
8724        @Override
8725        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8726                int match, int userId) {
8727            if (!sUserManager.exists(userId)) return null;
8728            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8729                return null;
8730            }
8731            final PackageParser.Activity activity = info.activity;
8732            if (mSafeMode && (activity.info.applicationInfo.flags
8733                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8734                return null;
8735            }
8736            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8737            if (ps == null) {
8738                return null;
8739            }
8740            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8741                    ps.readUserState(userId), userId);
8742            if (ai == null) {
8743                return null;
8744            }
8745            final ResolveInfo res = new ResolveInfo();
8746            res.activityInfo = ai;
8747            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8748                res.filter = info;
8749            }
8750            if (info != null) {
8751                res.handleAllWebDataURI = info.handleAllWebDataURI();
8752            }
8753            res.priority = info.getPriority();
8754            res.preferredOrder = activity.owner.mPreferredOrder;
8755            //System.out.println("Result: " + res.activityInfo.className +
8756            //                   " = " + res.priority);
8757            res.match = match;
8758            res.isDefault = info.hasDefault;
8759            res.labelRes = info.labelRes;
8760            res.nonLocalizedLabel = info.nonLocalizedLabel;
8761            if (userNeedsBadging(userId)) {
8762                res.noResourceId = true;
8763            } else {
8764                res.icon = info.icon;
8765            }
8766            res.iconResourceId = info.icon;
8767            res.system = res.activityInfo.applicationInfo.isSystemApp();
8768            return res;
8769        }
8770
8771        @Override
8772        protected void sortResults(List<ResolveInfo> results) {
8773            Collections.sort(results, mResolvePrioritySorter);
8774        }
8775
8776        @Override
8777        protected void dumpFilter(PrintWriter out, String prefix,
8778                PackageParser.ActivityIntentInfo filter) {
8779            out.print(prefix); out.print(
8780                    Integer.toHexString(System.identityHashCode(filter.activity)));
8781                    out.print(' ');
8782                    filter.activity.printComponentShortName(out);
8783                    out.print(" filter ");
8784                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8785        }
8786
8787        @Override
8788        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8789            return filter.activity;
8790        }
8791
8792        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8793            PackageParser.Activity activity = (PackageParser.Activity)label;
8794            out.print(prefix); out.print(
8795                    Integer.toHexString(System.identityHashCode(activity)));
8796                    out.print(' ');
8797                    activity.printComponentShortName(out);
8798            if (count > 1) {
8799                out.print(" ("); out.print(count); out.print(" filters)");
8800            }
8801            out.println();
8802        }
8803
8804//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8805//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8806//            final List<ResolveInfo> retList = Lists.newArrayList();
8807//            while (i.hasNext()) {
8808//                final ResolveInfo resolveInfo = i.next();
8809//                if (isEnabledLP(resolveInfo.activityInfo)) {
8810//                    retList.add(resolveInfo);
8811//                }
8812//            }
8813//            return retList;
8814//        }
8815
8816        // Keys are String (activity class name), values are Activity.
8817        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8818                = new ArrayMap<ComponentName, PackageParser.Activity>();
8819        private int mFlags;
8820    }
8821
8822    private final class ServiceIntentResolver
8823            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8824        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8825                boolean defaultOnly, int userId) {
8826            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8827            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8828        }
8829
8830        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8831                int userId) {
8832            if (!sUserManager.exists(userId)) return null;
8833            mFlags = flags;
8834            return super.queryIntent(intent, resolvedType,
8835                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8836        }
8837
8838        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8839                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8840            if (!sUserManager.exists(userId)) return null;
8841            if (packageServices == null) {
8842                return null;
8843            }
8844            mFlags = flags;
8845            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8846            final int N = packageServices.size();
8847            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8848                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8849
8850            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8851            for (int i = 0; i < N; ++i) {
8852                intentFilters = packageServices.get(i).intents;
8853                if (intentFilters != null && intentFilters.size() > 0) {
8854                    PackageParser.ServiceIntentInfo[] array =
8855                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8856                    intentFilters.toArray(array);
8857                    listCut.add(array);
8858                }
8859            }
8860            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8861        }
8862
8863        public final void addService(PackageParser.Service s) {
8864            mServices.put(s.getComponentName(), s);
8865            if (DEBUG_SHOW_INFO) {
8866                Log.v(TAG, "  "
8867                        + (s.info.nonLocalizedLabel != null
8868                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8869                Log.v(TAG, "    Class=" + s.info.name);
8870            }
8871            final int NI = s.intents.size();
8872            int j;
8873            for (j=0; j<NI; j++) {
8874                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8875                if (DEBUG_SHOW_INFO) {
8876                    Log.v(TAG, "    IntentFilter:");
8877                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8878                }
8879                if (!intent.debugCheck()) {
8880                    Log.w(TAG, "==> For Service " + s.info.name);
8881                }
8882                addFilter(intent);
8883            }
8884        }
8885
8886        public final void removeService(PackageParser.Service s) {
8887            mServices.remove(s.getComponentName());
8888            if (DEBUG_SHOW_INFO) {
8889                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8890                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8891                Log.v(TAG, "    Class=" + s.info.name);
8892            }
8893            final int NI = s.intents.size();
8894            int j;
8895            for (j=0; j<NI; j++) {
8896                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8897                if (DEBUG_SHOW_INFO) {
8898                    Log.v(TAG, "    IntentFilter:");
8899                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8900                }
8901                removeFilter(intent);
8902            }
8903        }
8904
8905        @Override
8906        protected boolean allowFilterResult(
8907                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8908            ServiceInfo filterSi = filter.service.info;
8909            for (int i=dest.size()-1; i>=0; i--) {
8910                ServiceInfo destAi = dest.get(i).serviceInfo;
8911                if (destAi.name == filterSi.name
8912                        && destAi.packageName == filterSi.packageName) {
8913                    return false;
8914                }
8915            }
8916            return true;
8917        }
8918
8919        @Override
8920        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8921            return new PackageParser.ServiceIntentInfo[size];
8922        }
8923
8924        @Override
8925        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8926            if (!sUserManager.exists(userId)) return true;
8927            PackageParser.Package p = filter.service.owner;
8928            if (p != null) {
8929                PackageSetting ps = (PackageSetting)p.mExtras;
8930                if (ps != null) {
8931                    // System apps are never considered stopped for purposes of
8932                    // filtering, because there may be no way for the user to
8933                    // actually re-launch them.
8934                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8935                            && ps.getStopped(userId);
8936                }
8937            }
8938            return false;
8939        }
8940
8941        @Override
8942        protected boolean isPackageForFilter(String packageName,
8943                PackageParser.ServiceIntentInfo info) {
8944            return packageName.equals(info.service.owner.packageName);
8945        }
8946
8947        @Override
8948        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8949                int match, int userId) {
8950            if (!sUserManager.exists(userId)) return null;
8951            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8952            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8953                return null;
8954            }
8955            final PackageParser.Service service = info.service;
8956            if (mSafeMode && (service.info.applicationInfo.flags
8957                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8958                return null;
8959            }
8960            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8961            if (ps == null) {
8962                return null;
8963            }
8964            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8965                    ps.readUserState(userId), userId);
8966            if (si == null) {
8967                return null;
8968            }
8969            final ResolveInfo res = new ResolveInfo();
8970            res.serviceInfo = si;
8971            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8972                res.filter = filter;
8973            }
8974            res.priority = info.getPriority();
8975            res.preferredOrder = service.owner.mPreferredOrder;
8976            res.match = match;
8977            res.isDefault = info.hasDefault;
8978            res.labelRes = info.labelRes;
8979            res.nonLocalizedLabel = info.nonLocalizedLabel;
8980            res.icon = info.icon;
8981            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8982            return res;
8983        }
8984
8985        @Override
8986        protected void sortResults(List<ResolveInfo> results) {
8987            Collections.sort(results, mResolvePrioritySorter);
8988        }
8989
8990        @Override
8991        protected void dumpFilter(PrintWriter out, String prefix,
8992                PackageParser.ServiceIntentInfo filter) {
8993            out.print(prefix); out.print(
8994                    Integer.toHexString(System.identityHashCode(filter.service)));
8995                    out.print(' ');
8996                    filter.service.printComponentShortName(out);
8997                    out.print(" filter ");
8998                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8999        }
9000
9001        @Override
9002        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9003            return filter.service;
9004        }
9005
9006        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9007            PackageParser.Service service = (PackageParser.Service)label;
9008            out.print(prefix); out.print(
9009                    Integer.toHexString(System.identityHashCode(service)));
9010                    out.print(' ');
9011                    service.printComponentShortName(out);
9012            if (count > 1) {
9013                out.print(" ("); out.print(count); out.print(" filters)");
9014            }
9015            out.println();
9016        }
9017
9018//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9019//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9020//            final List<ResolveInfo> retList = Lists.newArrayList();
9021//            while (i.hasNext()) {
9022//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9023//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9024//                    retList.add(resolveInfo);
9025//                }
9026//            }
9027//            return retList;
9028//        }
9029
9030        // Keys are String (activity class name), values are Activity.
9031        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9032                = new ArrayMap<ComponentName, PackageParser.Service>();
9033        private int mFlags;
9034    };
9035
9036    private final class ProviderIntentResolver
9037            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9038        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9039                boolean defaultOnly, int userId) {
9040            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9041            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9042        }
9043
9044        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9045                int userId) {
9046            if (!sUserManager.exists(userId))
9047                return null;
9048            mFlags = flags;
9049            return super.queryIntent(intent, resolvedType,
9050                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9051        }
9052
9053        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9054                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9055            if (!sUserManager.exists(userId))
9056                return null;
9057            if (packageProviders == null) {
9058                return null;
9059            }
9060            mFlags = flags;
9061            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9062            final int N = packageProviders.size();
9063            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9064                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9065
9066            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9067            for (int i = 0; i < N; ++i) {
9068                intentFilters = packageProviders.get(i).intents;
9069                if (intentFilters != null && intentFilters.size() > 0) {
9070                    PackageParser.ProviderIntentInfo[] array =
9071                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9072                    intentFilters.toArray(array);
9073                    listCut.add(array);
9074                }
9075            }
9076            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9077        }
9078
9079        public final void addProvider(PackageParser.Provider p) {
9080            if (mProviders.containsKey(p.getComponentName())) {
9081                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9082                return;
9083            }
9084
9085            mProviders.put(p.getComponentName(), p);
9086            if (DEBUG_SHOW_INFO) {
9087                Log.v(TAG, "  "
9088                        + (p.info.nonLocalizedLabel != null
9089                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9090                Log.v(TAG, "    Class=" + p.info.name);
9091            }
9092            final int NI = p.intents.size();
9093            int j;
9094            for (j = 0; j < NI; j++) {
9095                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9096                if (DEBUG_SHOW_INFO) {
9097                    Log.v(TAG, "    IntentFilter:");
9098                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9099                }
9100                if (!intent.debugCheck()) {
9101                    Log.w(TAG, "==> For Provider " + p.info.name);
9102                }
9103                addFilter(intent);
9104            }
9105        }
9106
9107        public final void removeProvider(PackageParser.Provider p) {
9108            mProviders.remove(p.getComponentName());
9109            if (DEBUG_SHOW_INFO) {
9110                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9111                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9112                Log.v(TAG, "    Class=" + p.info.name);
9113            }
9114            final int NI = p.intents.size();
9115            int j;
9116            for (j = 0; j < NI; j++) {
9117                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9118                if (DEBUG_SHOW_INFO) {
9119                    Log.v(TAG, "    IntentFilter:");
9120                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9121                }
9122                removeFilter(intent);
9123            }
9124        }
9125
9126        @Override
9127        protected boolean allowFilterResult(
9128                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9129            ProviderInfo filterPi = filter.provider.info;
9130            for (int i = dest.size() - 1; i >= 0; i--) {
9131                ProviderInfo destPi = dest.get(i).providerInfo;
9132                if (destPi.name == filterPi.name
9133                        && destPi.packageName == filterPi.packageName) {
9134                    return false;
9135                }
9136            }
9137            return true;
9138        }
9139
9140        @Override
9141        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9142            return new PackageParser.ProviderIntentInfo[size];
9143        }
9144
9145        @Override
9146        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9147            if (!sUserManager.exists(userId))
9148                return true;
9149            PackageParser.Package p = filter.provider.owner;
9150            if (p != null) {
9151                PackageSetting ps = (PackageSetting) p.mExtras;
9152                if (ps != null) {
9153                    // System apps are never considered stopped for purposes of
9154                    // filtering, because there may be no way for the user to
9155                    // actually re-launch them.
9156                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9157                            && ps.getStopped(userId);
9158                }
9159            }
9160            return false;
9161        }
9162
9163        @Override
9164        protected boolean isPackageForFilter(String packageName,
9165                PackageParser.ProviderIntentInfo info) {
9166            return packageName.equals(info.provider.owner.packageName);
9167        }
9168
9169        @Override
9170        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9171                int match, int userId) {
9172            if (!sUserManager.exists(userId))
9173                return null;
9174            final PackageParser.ProviderIntentInfo info = filter;
9175            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9176                return null;
9177            }
9178            final PackageParser.Provider provider = info.provider;
9179            if (mSafeMode && (provider.info.applicationInfo.flags
9180                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9181                return null;
9182            }
9183            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9184            if (ps == null) {
9185                return null;
9186            }
9187            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9188                    ps.readUserState(userId), userId);
9189            if (pi == null) {
9190                return null;
9191            }
9192            final ResolveInfo res = new ResolveInfo();
9193            res.providerInfo = pi;
9194            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9195                res.filter = filter;
9196            }
9197            res.priority = info.getPriority();
9198            res.preferredOrder = provider.owner.mPreferredOrder;
9199            res.match = match;
9200            res.isDefault = info.hasDefault;
9201            res.labelRes = info.labelRes;
9202            res.nonLocalizedLabel = info.nonLocalizedLabel;
9203            res.icon = info.icon;
9204            res.system = res.providerInfo.applicationInfo.isSystemApp();
9205            return res;
9206        }
9207
9208        @Override
9209        protected void sortResults(List<ResolveInfo> results) {
9210            Collections.sort(results, mResolvePrioritySorter);
9211        }
9212
9213        @Override
9214        protected void dumpFilter(PrintWriter out, String prefix,
9215                PackageParser.ProviderIntentInfo filter) {
9216            out.print(prefix);
9217            out.print(
9218                    Integer.toHexString(System.identityHashCode(filter.provider)));
9219            out.print(' ');
9220            filter.provider.printComponentShortName(out);
9221            out.print(" filter ");
9222            out.println(Integer.toHexString(System.identityHashCode(filter)));
9223        }
9224
9225        @Override
9226        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9227            return filter.provider;
9228        }
9229
9230        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9231            PackageParser.Provider provider = (PackageParser.Provider)label;
9232            out.print(prefix); out.print(
9233                    Integer.toHexString(System.identityHashCode(provider)));
9234                    out.print(' ');
9235                    provider.printComponentShortName(out);
9236            if (count > 1) {
9237                out.print(" ("); out.print(count); out.print(" filters)");
9238            }
9239            out.println();
9240        }
9241
9242        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9243                = new ArrayMap<ComponentName, PackageParser.Provider>();
9244        private int mFlags;
9245    };
9246
9247    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9248            new Comparator<ResolveInfo>() {
9249        public int compare(ResolveInfo r1, ResolveInfo r2) {
9250            int v1 = r1.priority;
9251            int v2 = r2.priority;
9252            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9253            if (v1 != v2) {
9254                return (v1 > v2) ? -1 : 1;
9255            }
9256            v1 = r1.preferredOrder;
9257            v2 = r2.preferredOrder;
9258            if (v1 != v2) {
9259                return (v1 > v2) ? -1 : 1;
9260            }
9261            if (r1.isDefault != r2.isDefault) {
9262                return r1.isDefault ? -1 : 1;
9263            }
9264            v1 = r1.match;
9265            v2 = r2.match;
9266            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9267            if (v1 != v2) {
9268                return (v1 > v2) ? -1 : 1;
9269            }
9270            if (r1.system != r2.system) {
9271                return r1.system ? -1 : 1;
9272            }
9273            return 0;
9274        }
9275    };
9276
9277    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9278            new Comparator<ProviderInfo>() {
9279        public int compare(ProviderInfo p1, ProviderInfo p2) {
9280            final int v1 = p1.initOrder;
9281            final int v2 = p2.initOrder;
9282            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9283        }
9284    };
9285
9286    final void sendPackageBroadcast(final String action, final String pkg,
9287            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9288            final int[] userIds) {
9289        mHandler.post(new Runnable() {
9290            @Override
9291            public void run() {
9292                try {
9293                    final IActivityManager am = ActivityManagerNative.getDefault();
9294                    if (am == null) return;
9295                    final int[] resolvedUserIds;
9296                    if (userIds == null) {
9297                        resolvedUserIds = am.getRunningUserIds();
9298                    } else {
9299                        resolvedUserIds = userIds;
9300                    }
9301                    for (int id : resolvedUserIds) {
9302                        final Intent intent = new Intent(action,
9303                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9304                        if (extras != null) {
9305                            intent.putExtras(extras);
9306                        }
9307                        if (targetPkg != null) {
9308                            intent.setPackage(targetPkg);
9309                        }
9310                        // Modify the UID when posting to other users
9311                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9312                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9313                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9314                            intent.putExtra(Intent.EXTRA_UID, uid);
9315                        }
9316                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9317                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9318                        if (DEBUG_BROADCASTS) {
9319                            RuntimeException here = new RuntimeException("here");
9320                            here.fillInStackTrace();
9321                            Slog.d(TAG, "Sending to user " + id + ": "
9322                                    + intent.toShortString(false, true, false, false)
9323                                    + " " + intent.getExtras(), here);
9324                        }
9325                        am.broadcastIntent(null, intent, null, finishedReceiver,
9326                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9327                                null, finishedReceiver != null, false, id);
9328                    }
9329                } catch (RemoteException ex) {
9330                }
9331            }
9332        });
9333    }
9334
9335    /**
9336     * Check if the external storage media is available. This is true if there
9337     * is a mounted external storage medium or if the external storage is
9338     * emulated.
9339     */
9340    private boolean isExternalMediaAvailable() {
9341        return mMediaMounted || Environment.isExternalStorageEmulated();
9342    }
9343
9344    @Override
9345    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9346        // writer
9347        synchronized (mPackages) {
9348            if (!isExternalMediaAvailable()) {
9349                // If the external storage is no longer mounted at this point,
9350                // the caller may not have been able to delete all of this
9351                // packages files and can not delete any more.  Bail.
9352                return null;
9353            }
9354            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9355            if (lastPackage != null) {
9356                pkgs.remove(lastPackage);
9357            }
9358            if (pkgs.size() > 0) {
9359                return pkgs.get(0);
9360            }
9361        }
9362        return null;
9363    }
9364
9365    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9366        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9367                userId, andCode ? 1 : 0, packageName);
9368        if (mSystemReady) {
9369            msg.sendToTarget();
9370        } else {
9371            if (mPostSystemReadyMessages == null) {
9372                mPostSystemReadyMessages = new ArrayList<>();
9373            }
9374            mPostSystemReadyMessages.add(msg);
9375        }
9376    }
9377
9378    void startCleaningPackages() {
9379        // reader
9380        synchronized (mPackages) {
9381            if (!isExternalMediaAvailable()) {
9382                return;
9383            }
9384            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9385                return;
9386            }
9387        }
9388        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9389        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9390        IActivityManager am = ActivityManagerNative.getDefault();
9391        if (am != null) {
9392            try {
9393                am.startService(null, intent, null, mContext.getOpPackageName(),
9394                        UserHandle.USER_OWNER);
9395            } catch (RemoteException e) {
9396            }
9397        }
9398    }
9399
9400    @Override
9401    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9402            int installFlags, String installerPackageName, VerificationParams verificationParams,
9403            String packageAbiOverride) {
9404        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9405                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9406    }
9407
9408    @Override
9409    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9410            int installFlags, String installerPackageName, VerificationParams verificationParams,
9411            String packageAbiOverride, int userId) {
9412        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9413
9414        final int callingUid = Binder.getCallingUid();
9415        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9416
9417        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9418            try {
9419                if (observer != null) {
9420                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9421                }
9422            } catch (RemoteException re) {
9423            }
9424            return;
9425        }
9426
9427        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9428            installFlags |= PackageManager.INSTALL_FROM_ADB;
9429
9430        } else {
9431            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9432            // about installerPackageName.
9433
9434            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9435            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9436        }
9437
9438        UserHandle user;
9439        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9440            user = UserHandle.ALL;
9441        } else {
9442            user = new UserHandle(userId);
9443        }
9444
9445        // Only system components can circumvent runtime permissions when installing.
9446        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9447                && mContext.checkCallingOrSelfPermission(Manifest.permission
9448                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9449            throw new SecurityException("You need the "
9450                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9451                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9452        }
9453
9454        verificationParams.setInstallerUid(callingUid);
9455
9456        final File originFile = new File(originPath);
9457        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9458
9459        final Message msg = mHandler.obtainMessage(INIT_COPY);
9460        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9461                null, verificationParams, user, packageAbiOverride);
9462        mHandler.sendMessage(msg);
9463    }
9464
9465    void installStage(String packageName, File stagedDir, String stagedCid,
9466            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9467            String installerPackageName, int installerUid, UserHandle user) {
9468        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9469                params.referrerUri, installerUid, null);
9470        verifParams.setInstallerUid(installerUid);
9471
9472        final OriginInfo origin;
9473        if (stagedDir != null) {
9474            origin = OriginInfo.fromStagedFile(stagedDir);
9475        } else {
9476            origin = OriginInfo.fromStagedContainer(stagedCid);
9477        }
9478
9479        final Message msg = mHandler.obtainMessage(INIT_COPY);
9480        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9481                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
9482        mHandler.sendMessage(msg);
9483    }
9484
9485    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9486        Bundle extras = new Bundle(1);
9487        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9488
9489        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9490                packageName, extras, null, null, new int[] {userId});
9491        try {
9492            IActivityManager am = ActivityManagerNative.getDefault();
9493            final boolean isSystem =
9494                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9495            if (isSystem && am.isUserRunning(userId, false)) {
9496                // The just-installed/enabled app is bundled on the system, so presumed
9497                // to be able to run automatically without needing an explicit launch.
9498                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9499                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9500                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9501                        .setPackage(packageName);
9502                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9503                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9504            }
9505        } catch (RemoteException e) {
9506            // shouldn't happen
9507            Slog.w(TAG, "Unable to bootstrap installed package", e);
9508        }
9509    }
9510
9511    @Override
9512    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9513            int userId) {
9514        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9515        PackageSetting pkgSetting;
9516        final int uid = Binder.getCallingUid();
9517        enforceCrossUserPermission(uid, userId, true, true,
9518                "setApplicationHiddenSetting for user " + userId);
9519
9520        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9521            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9522            return false;
9523        }
9524
9525        long callingId = Binder.clearCallingIdentity();
9526        try {
9527            boolean sendAdded = false;
9528            boolean sendRemoved = false;
9529            // writer
9530            synchronized (mPackages) {
9531                pkgSetting = mSettings.mPackages.get(packageName);
9532                if (pkgSetting == null) {
9533                    return false;
9534                }
9535                if (pkgSetting.getHidden(userId) != hidden) {
9536                    pkgSetting.setHidden(hidden, userId);
9537                    mSettings.writePackageRestrictionsLPr(userId);
9538                    if (hidden) {
9539                        sendRemoved = true;
9540                    } else {
9541                        sendAdded = true;
9542                    }
9543                }
9544            }
9545            if (sendAdded) {
9546                sendPackageAddedForUser(packageName, pkgSetting, userId);
9547                return true;
9548            }
9549            if (sendRemoved) {
9550                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9551                        "hiding pkg");
9552                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9553            }
9554        } finally {
9555            Binder.restoreCallingIdentity(callingId);
9556        }
9557        return false;
9558    }
9559
9560    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9561            int userId) {
9562        final PackageRemovedInfo info = new PackageRemovedInfo();
9563        info.removedPackage = packageName;
9564        info.removedUsers = new int[] {userId};
9565        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9566        info.sendBroadcast(false, false, false);
9567    }
9568
9569    /**
9570     * Returns true if application is not found or there was an error. Otherwise it returns
9571     * the hidden state of the package for the given user.
9572     */
9573    @Override
9574    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9575        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9576        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9577                false, "getApplicationHidden for user " + userId);
9578        PackageSetting pkgSetting;
9579        long callingId = Binder.clearCallingIdentity();
9580        try {
9581            // writer
9582            synchronized (mPackages) {
9583                pkgSetting = mSettings.mPackages.get(packageName);
9584                if (pkgSetting == null) {
9585                    return true;
9586                }
9587                return pkgSetting.getHidden(userId);
9588            }
9589        } finally {
9590            Binder.restoreCallingIdentity(callingId);
9591        }
9592    }
9593
9594    /**
9595     * @hide
9596     */
9597    @Override
9598    public int installExistingPackageAsUser(String packageName, int userId) {
9599        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9600                null);
9601        PackageSetting pkgSetting;
9602        final int uid = Binder.getCallingUid();
9603        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9604                + userId);
9605        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9606            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9607        }
9608
9609        long callingId = Binder.clearCallingIdentity();
9610        try {
9611            boolean sendAdded = false;
9612
9613            // writer
9614            synchronized (mPackages) {
9615                pkgSetting = mSettings.mPackages.get(packageName);
9616                if (pkgSetting == null) {
9617                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9618                }
9619                if (!pkgSetting.getInstalled(userId)) {
9620                    pkgSetting.setInstalled(true, userId);
9621                    pkgSetting.setHidden(false, userId);
9622                    mSettings.writePackageRestrictionsLPr(userId);
9623                    sendAdded = true;
9624                }
9625            }
9626
9627            if (sendAdded) {
9628                sendPackageAddedForUser(packageName, pkgSetting, userId);
9629            }
9630        } finally {
9631            Binder.restoreCallingIdentity(callingId);
9632        }
9633
9634        return PackageManager.INSTALL_SUCCEEDED;
9635    }
9636
9637    boolean isUserRestricted(int userId, String restrictionKey) {
9638        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9639        if (restrictions.getBoolean(restrictionKey, false)) {
9640            Log.w(TAG, "User is restricted: " + restrictionKey);
9641            return true;
9642        }
9643        return false;
9644    }
9645
9646    @Override
9647    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9648        mContext.enforceCallingOrSelfPermission(
9649                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9650                "Only package verification agents can verify applications");
9651
9652        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9653        final PackageVerificationResponse response = new PackageVerificationResponse(
9654                verificationCode, Binder.getCallingUid());
9655        msg.arg1 = id;
9656        msg.obj = response;
9657        mHandler.sendMessage(msg);
9658    }
9659
9660    @Override
9661    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9662            long millisecondsToDelay) {
9663        mContext.enforceCallingOrSelfPermission(
9664                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9665                "Only package verification agents can extend verification timeouts");
9666
9667        final PackageVerificationState state = mPendingVerification.get(id);
9668        final PackageVerificationResponse response = new PackageVerificationResponse(
9669                verificationCodeAtTimeout, Binder.getCallingUid());
9670
9671        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9672            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9673        }
9674        if (millisecondsToDelay < 0) {
9675            millisecondsToDelay = 0;
9676        }
9677        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9678                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9679            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9680        }
9681
9682        if ((state != null) && !state.timeoutExtended()) {
9683            state.extendTimeout();
9684
9685            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9686            msg.arg1 = id;
9687            msg.obj = response;
9688            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9689        }
9690    }
9691
9692    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9693            int verificationCode, UserHandle user) {
9694        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9695        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9696        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9697        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9698        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9699
9700        mContext.sendBroadcastAsUser(intent, user,
9701                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9702    }
9703
9704    private ComponentName matchComponentForVerifier(String packageName,
9705            List<ResolveInfo> receivers) {
9706        ActivityInfo targetReceiver = null;
9707
9708        final int NR = receivers.size();
9709        for (int i = 0; i < NR; i++) {
9710            final ResolveInfo info = receivers.get(i);
9711            if (info.activityInfo == null) {
9712                continue;
9713            }
9714
9715            if (packageName.equals(info.activityInfo.packageName)) {
9716                targetReceiver = info.activityInfo;
9717                break;
9718            }
9719        }
9720
9721        if (targetReceiver == null) {
9722            return null;
9723        }
9724
9725        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9726    }
9727
9728    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9729            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9730        if (pkgInfo.verifiers.length == 0) {
9731            return null;
9732        }
9733
9734        final int N = pkgInfo.verifiers.length;
9735        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9736        for (int i = 0; i < N; i++) {
9737            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9738
9739            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9740                    receivers);
9741            if (comp == null) {
9742                continue;
9743            }
9744
9745            final int verifierUid = getUidForVerifier(verifierInfo);
9746            if (verifierUid == -1) {
9747                continue;
9748            }
9749
9750            if (DEBUG_VERIFY) {
9751                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9752                        + " with the correct signature");
9753            }
9754            sufficientVerifiers.add(comp);
9755            verificationState.addSufficientVerifier(verifierUid);
9756        }
9757
9758        return sufficientVerifiers;
9759    }
9760
9761    private int getUidForVerifier(VerifierInfo verifierInfo) {
9762        synchronized (mPackages) {
9763            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9764            if (pkg == null) {
9765                return -1;
9766            } else if (pkg.mSignatures.length != 1) {
9767                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9768                        + " has more than one signature; ignoring");
9769                return -1;
9770            }
9771
9772            /*
9773             * If the public key of the package's signature does not match
9774             * our expected public key, then this is a different package and
9775             * we should skip.
9776             */
9777
9778            final byte[] expectedPublicKey;
9779            try {
9780                final Signature verifierSig = pkg.mSignatures[0];
9781                final PublicKey publicKey = verifierSig.getPublicKey();
9782                expectedPublicKey = publicKey.getEncoded();
9783            } catch (CertificateException e) {
9784                return -1;
9785            }
9786
9787            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9788
9789            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9790                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9791                        + " does not have the expected public key; ignoring");
9792                return -1;
9793            }
9794
9795            return pkg.applicationInfo.uid;
9796        }
9797    }
9798
9799    @Override
9800    public void finishPackageInstall(int token) {
9801        enforceSystemOrRoot("Only the system is allowed to finish installs");
9802
9803        if (DEBUG_INSTALL) {
9804            Slog.v(TAG, "BM finishing package install for " + token);
9805        }
9806
9807        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9808        mHandler.sendMessage(msg);
9809    }
9810
9811    /**
9812     * Get the verification agent timeout.
9813     *
9814     * @return verification timeout in milliseconds
9815     */
9816    private long getVerificationTimeout() {
9817        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9818                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9819                DEFAULT_VERIFICATION_TIMEOUT);
9820    }
9821
9822    /**
9823     * Get the default verification agent response code.
9824     *
9825     * @return default verification response code
9826     */
9827    private int getDefaultVerificationResponse() {
9828        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9829                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9830                DEFAULT_VERIFICATION_RESPONSE);
9831    }
9832
9833    /**
9834     * Check whether or not package verification has been enabled.
9835     *
9836     * @return true if verification should be performed
9837     */
9838    private boolean isVerificationEnabled(int userId, int installFlags) {
9839        if (!DEFAULT_VERIFY_ENABLE) {
9840            return false;
9841        }
9842
9843        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9844
9845        // Check if installing from ADB
9846        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9847            // Do not run verification in a test harness environment
9848            if (ActivityManager.isRunningInTestHarness()) {
9849                return false;
9850            }
9851            if (ensureVerifyAppsEnabled) {
9852                return true;
9853            }
9854            // Check if the developer does not want package verification for ADB installs
9855            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9856                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9857                return false;
9858            }
9859        }
9860
9861        if (ensureVerifyAppsEnabled) {
9862            return true;
9863        }
9864
9865        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9866                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9867    }
9868
9869    @Override
9870    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9871            throws RemoteException {
9872        mContext.enforceCallingOrSelfPermission(
9873                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9874                "Only intentfilter verification agents can verify applications");
9875
9876        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9877        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9878                Binder.getCallingUid(), verificationCode, failedDomains);
9879        msg.arg1 = id;
9880        msg.obj = response;
9881        mHandler.sendMessage(msg);
9882    }
9883
9884    @Override
9885    public int getIntentVerificationStatus(String packageName, int userId) {
9886        synchronized (mPackages) {
9887            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9888        }
9889    }
9890
9891    @Override
9892    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9893        mContext.enforceCallingOrSelfPermission(
9894                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9895
9896        boolean result = false;
9897        synchronized (mPackages) {
9898            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9899        }
9900        if (result) {
9901            scheduleWritePackageRestrictionsLocked(userId);
9902        }
9903        return result;
9904    }
9905
9906    @Override
9907    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9908        synchronized (mPackages) {
9909            return mSettings.getIntentFilterVerificationsLPr(packageName);
9910        }
9911    }
9912
9913    @Override
9914    public List<IntentFilter> getAllIntentFilters(String packageName) {
9915        if (TextUtils.isEmpty(packageName)) {
9916            return Collections.<IntentFilter>emptyList();
9917        }
9918        synchronized (mPackages) {
9919            PackageParser.Package pkg = mPackages.get(packageName);
9920            if (pkg == null || pkg.activities == null) {
9921                return Collections.<IntentFilter>emptyList();
9922            }
9923            final int count = pkg.activities.size();
9924            ArrayList<IntentFilter> result = new ArrayList<>();
9925            for (int n=0; n<count; n++) {
9926                PackageParser.Activity activity = pkg.activities.get(n);
9927                if (activity.intents != null || activity.intents.size() > 0) {
9928                    result.addAll(activity.intents);
9929                }
9930            }
9931            return result;
9932        }
9933    }
9934
9935    @Override
9936    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9937        mContext.enforceCallingOrSelfPermission(
9938                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9939
9940        synchronized (mPackages) {
9941            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
9942            if (packageName != null) {
9943                result |= updateIntentVerificationStatus(packageName,
9944                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9945                        UserHandle.myUserId());
9946                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
9947                        packageName, userId);
9948            }
9949            return result;
9950        }
9951    }
9952
9953    @Override
9954    public String getDefaultBrowserPackageName(int userId) {
9955        synchronized (mPackages) {
9956            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9957        }
9958    }
9959
9960    /**
9961     * Get the "allow unknown sources" setting.
9962     *
9963     * @return the current "allow unknown sources" setting
9964     */
9965    private int getUnknownSourcesSettings() {
9966        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9967                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9968                -1);
9969    }
9970
9971    @Override
9972    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9973        final int uid = Binder.getCallingUid();
9974        // writer
9975        synchronized (mPackages) {
9976            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9977            if (targetPackageSetting == null) {
9978                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9979            }
9980
9981            PackageSetting installerPackageSetting;
9982            if (installerPackageName != null) {
9983                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9984                if (installerPackageSetting == null) {
9985                    throw new IllegalArgumentException("Unknown installer package: "
9986                            + installerPackageName);
9987                }
9988            } else {
9989                installerPackageSetting = null;
9990            }
9991
9992            Signature[] callerSignature;
9993            Object obj = mSettings.getUserIdLPr(uid);
9994            if (obj != null) {
9995                if (obj instanceof SharedUserSetting) {
9996                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9997                } else if (obj instanceof PackageSetting) {
9998                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9999                } else {
10000                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10001                }
10002            } else {
10003                throw new SecurityException("Unknown calling uid " + uid);
10004            }
10005
10006            // Verify: can't set installerPackageName to a package that is
10007            // not signed with the same cert as the caller.
10008            if (installerPackageSetting != null) {
10009                if (compareSignatures(callerSignature,
10010                        installerPackageSetting.signatures.mSignatures)
10011                        != PackageManager.SIGNATURE_MATCH) {
10012                    throw new SecurityException(
10013                            "Caller does not have same cert as new installer package "
10014                            + installerPackageName);
10015                }
10016            }
10017
10018            // Verify: if target already has an installer package, it must
10019            // be signed with the same cert as the caller.
10020            if (targetPackageSetting.installerPackageName != null) {
10021                PackageSetting setting = mSettings.mPackages.get(
10022                        targetPackageSetting.installerPackageName);
10023                // If the currently set package isn't valid, then it's always
10024                // okay to change it.
10025                if (setting != null) {
10026                    if (compareSignatures(callerSignature,
10027                            setting.signatures.mSignatures)
10028                            != PackageManager.SIGNATURE_MATCH) {
10029                        throw new SecurityException(
10030                                "Caller does not have same cert as old installer package "
10031                                + targetPackageSetting.installerPackageName);
10032                    }
10033                }
10034            }
10035
10036            // Okay!
10037            targetPackageSetting.installerPackageName = installerPackageName;
10038            scheduleWriteSettingsLocked();
10039        }
10040    }
10041
10042    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10043        // Queue up an async operation since the package installation may take a little while.
10044        mHandler.post(new Runnable() {
10045            public void run() {
10046                mHandler.removeCallbacks(this);
10047                 // Result object to be returned
10048                PackageInstalledInfo res = new PackageInstalledInfo();
10049                res.returnCode = currentStatus;
10050                res.uid = -1;
10051                res.pkg = null;
10052                res.removedInfo = new PackageRemovedInfo();
10053                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10054                    args.doPreInstall(res.returnCode);
10055                    synchronized (mInstallLock) {
10056                        installPackageLI(args, res);
10057                    }
10058                    args.doPostInstall(res.returnCode, res.uid);
10059                }
10060
10061                // A restore should be performed at this point if (a) the install
10062                // succeeded, (b) the operation is not an update, and (c) the new
10063                // package has not opted out of backup participation.
10064                final boolean update = res.removedInfo.removedPackage != null;
10065                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10066                boolean doRestore = !update
10067                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10068
10069                // Set up the post-install work request bookkeeping.  This will be used
10070                // and cleaned up by the post-install event handling regardless of whether
10071                // there's a restore pass performed.  Token values are >= 1.
10072                int token;
10073                if (mNextInstallToken < 0) mNextInstallToken = 1;
10074                token = mNextInstallToken++;
10075
10076                PostInstallData data = new PostInstallData(args, res);
10077                mRunningInstalls.put(token, data);
10078                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10079
10080                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10081                    // Pass responsibility to the Backup Manager.  It will perform a
10082                    // restore if appropriate, then pass responsibility back to the
10083                    // Package Manager to run the post-install observer callbacks
10084                    // and broadcasts.
10085                    IBackupManager bm = IBackupManager.Stub.asInterface(
10086                            ServiceManager.getService(Context.BACKUP_SERVICE));
10087                    if (bm != null) {
10088                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10089                                + " to BM for possible restore");
10090                        try {
10091                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
10092                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10093                            } else {
10094                                doRestore = false;
10095                            }
10096                        } catch (RemoteException e) {
10097                            // can't happen; the backup manager is local
10098                        } catch (Exception e) {
10099                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10100                            doRestore = false;
10101                        }
10102                    } else {
10103                        Slog.e(TAG, "Backup Manager not found!");
10104                        doRestore = false;
10105                    }
10106                }
10107
10108                if (!doRestore) {
10109                    // No restore possible, or the Backup Manager was mysteriously not
10110                    // available -- just fire the post-install work request directly.
10111                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10112                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10113                    mHandler.sendMessage(msg);
10114                }
10115            }
10116        });
10117    }
10118
10119    private abstract class HandlerParams {
10120        private static final int MAX_RETRIES = 4;
10121
10122        /**
10123         * Number of times startCopy() has been attempted and had a non-fatal
10124         * error.
10125         */
10126        private int mRetries = 0;
10127
10128        /** User handle for the user requesting the information or installation. */
10129        private final UserHandle mUser;
10130
10131        HandlerParams(UserHandle user) {
10132            mUser = user;
10133        }
10134
10135        UserHandle getUser() {
10136            return mUser;
10137        }
10138
10139        final boolean startCopy() {
10140            boolean res;
10141            try {
10142                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10143
10144                if (++mRetries > MAX_RETRIES) {
10145                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10146                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10147                    handleServiceError();
10148                    return false;
10149                } else {
10150                    handleStartCopy();
10151                    res = true;
10152                }
10153            } catch (RemoteException e) {
10154                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10155                mHandler.sendEmptyMessage(MCS_RECONNECT);
10156                res = false;
10157            }
10158            handleReturnCode();
10159            return res;
10160        }
10161
10162        final void serviceError() {
10163            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10164            handleServiceError();
10165            handleReturnCode();
10166        }
10167
10168        abstract void handleStartCopy() throws RemoteException;
10169        abstract void handleServiceError();
10170        abstract void handleReturnCode();
10171    }
10172
10173    class MeasureParams extends HandlerParams {
10174        private final PackageStats mStats;
10175        private boolean mSuccess;
10176
10177        private final IPackageStatsObserver mObserver;
10178
10179        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10180            super(new UserHandle(stats.userHandle));
10181            mObserver = observer;
10182            mStats = stats;
10183        }
10184
10185        @Override
10186        public String toString() {
10187            return "MeasureParams{"
10188                + Integer.toHexString(System.identityHashCode(this))
10189                + " " + mStats.packageName + "}";
10190        }
10191
10192        @Override
10193        void handleStartCopy() throws RemoteException {
10194            synchronized (mInstallLock) {
10195                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10196            }
10197
10198            if (mSuccess) {
10199                final boolean mounted;
10200                if (Environment.isExternalStorageEmulated()) {
10201                    mounted = true;
10202                } else {
10203                    final String status = Environment.getExternalStorageState();
10204                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10205                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10206                }
10207
10208                if (mounted) {
10209                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10210
10211                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10212                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10213
10214                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10215                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10216
10217                    // Always subtract cache size, since it's a subdirectory
10218                    mStats.externalDataSize -= mStats.externalCacheSize;
10219
10220                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10221                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10222
10223                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10224                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10225                }
10226            }
10227        }
10228
10229        @Override
10230        void handleReturnCode() {
10231            if (mObserver != null) {
10232                try {
10233                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10234                } catch (RemoteException e) {
10235                    Slog.i(TAG, "Observer no longer exists.");
10236                }
10237            }
10238        }
10239
10240        @Override
10241        void handleServiceError() {
10242            Slog.e(TAG, "Could not measure application " + mStats.packageName
10243                            + " external storage");
10244        }
10245    }
10246
10247    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10248            throws RemoteException {
10249        long result = 0;
10250        for (File path : paths) {
10251            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10252        }
10253        return result;
10254    }
10255
10256    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10257        for (File path : paths) {
10258            try {
10259                mcs.clearDirectory(path.getAbsolutePath());
10260            } catch (RemoteException e) {
10261            }
10262        }
10263    }
10264
10265    static class OriginInfo {
10266        /**
10267         * Location where install is coming from, before it has been
10268         * copied/renamed into place. This could be a single monolithic APK
10269         * file, or a cluster directory. This location may be untrusted.
10270         */
10271        final File file;
10272        final String cid;
10273
10274        /**
10275         * Flag indicating that {@link #file} or {@link #cid} has already been
10276         * staged, meaning downstream users don't need to defensively copy the
10277         * contents.
10278         */
10279        final boolean staged;
10280
10281        /**
10282         * Flag indicating that {@link #file} or {@link #cid} is an already
10283         * installed app that is being moved.
10284         */
10285        final boolean existing;
10286
10287        final String resolvedPath;
10288        final File resolvedFile;
10289
10290        static OriginInfo fromNothing() {
10291            return new OriginInfo(null, null, false, false);
10292        }
10293
10294        static OriginInfo fromUntrustedFile(File file) {
10295            return new OriginInfo(file, null, false, false);
10296        }
10297
10298        static OriginInfo fromExistingFile(File file) {
10299            return new OriginInfo(file, null, false, true);
10300        }
10301
10302        static OriginInfo fromStagedFile(File file) {
10303            return new OriginInfo(file, null, true, false);
10304        }
10305
10306        static OriginInfo fromStagedContainer(String cid) {
10307            return new OriginInfo(null, cid, true, false);
10308        }
10309
10310        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10311            this.file = file;
10312            this.cid = cid;
10313            this.staged = staged;
10314            this.existing = existing;
10315
10316            if (cid != null) {
10317                resolvedPath = PackageHelper.getSdDir(cid);
10318                resolvedFile = new File(resolvedPath);
10319            } else if (file != null) {
10320                resolvedPath = file.getAbsolutePath();
10321                resolvedFile = file;
10322            } else {
10323                resolvedPath = null;
10324                resolvedFile = null;
10325            }
10326        }
10327    }
10328
10329    class MoveInfo {
10330        final int moveId;
10331        final String fromUuid;
10332        final String toUuid;
10333        final String packageName;
10334        final String dataAppName;
10335        final int appId;
10336        final String seinfo;
10337
10338        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10339                String dataAppName, int appId, String seinfo) {
10340            this.moveId = moveId;
10341            this.fromUuid = fromUuid;
10342            this.toUuid = toUuid;
10343            this.packageName = packageName;
10344            this.dataAppName = dataAppName;
10345            this.appId = appId;
10346            this.seinfo = seinfo;
10347        }
10348    }
10349
10350    class InstallParams extends HandlerParams {
10351        final OriginInfo origin;
10352        final MoveInfo move;
10353        final IPackageInstallObserver2 observer;
10354        int installFlags;
10355        final String installerPackageName;
10356        final String volumeUuid;
10357        final VerificationParams verificationParams;
10358        private InstallArgs mArgs;
10359        private int mRet;
10360        final String packageAbiOverride;
10361
10362        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10363                int installFlags, String installerPackageName, String volumeUuid,
10364                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
10365            super(user);
10366            this.origin = origin;
10367            this.move = move;
10368            this.observer = observer;
10369            this.installFlags = installFlags;
10370            this.installerPackageName = installerPackageName;
10371            this.volumeUuid = volumeUuid;
10372            this.verificationParams = verificationParams;
10373            this.packageAbiOverride = packageAbiOverride;
10374        }
10375
10376        @Override
10377        public String toString() {
10378            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10379                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10380        }
10381
10382        public ManifestDigest getManifestDigest() {
10383            if (verificationParams == null) {
10384                return null;
10385            }
10386            return verificationParams.getManifestDigest();
10387        }
10388
10389        private int installLocationPolicy(PackageInfoLite pkgLite) {
10390            String packageName = pkgLite.packageName;
10391            int installLocation = pkgLite.installLocation;
10392            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10393            // reader
10394            synchronized (mPackages) {
10395                PackageParser.Package pkg = mPackages.get(packageName);
10396                if (pkg != null) {
10397                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10398                        // Check for downgrading.
10399                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10400                            try {
10401                                checkDowngrade(pkg, pkgLite);
10402                            } catch (PackageManagerException e) {
10403                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10404                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10405                            }
10406                        }
10407                        // Check for updated system application.
10408                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10409                            if (onSd) {
10410                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10411                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10412                            }
10413                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10414                        } else {
10415                            if (onSd) {
10416                                // Install flag overrides everything.
10417                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10418                            }
10419                            // If current upgrade specifies particular preference
10420                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10421                                // Application explicitly specified internal.
10422                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10423                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10424                                // App explictly prefers external. Let policy decide
10425                            } else {
10426                                // Prefer previous location
10427                                if (isExternal(pkg)) {
10428                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10429                                }
10430                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10431                            }
10432                        }
10433                    } else {
10434                        // Invalid install. Return error code
10435                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10436                    }
10437                }
10438            }
10439            // All the special cases have been taken care of.
10440            // Return result based on recommended install location.
10441            if (onSd) {
10442                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10443            }
10444            return pkgLite.recommendedInstallLocation;
10445        }
10446
10447        /*
10448         * Invoke remote method to get package information and install
10449         * location values. Override install location based on default
10450         * policy if needed and then create install arguments based
10451         * on the install location.
10452         */
10453        public void handleStartCopy() throws RemoteException {
10454            int ret = PackageManager.INSTALL_SUCCEEDED;
10455
10456            // If we're already staged, we've firmly committed to an install location
10457            if (origin.staged) {
10458                if (origin.file != null) {
10459                    installFlags |= PackageManager.INSTALL_INTERNAL;
10460                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10461                } else if (origin.cid != null) {
10462                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10463                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10464                } else {
10465                    throw new IllegalStateException("Invalid stage location");
10466                }
10467            }
10468
10469            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10470            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10471
10472            PackageInfoLite pkgLite = null;
10473
10474            if (onInt && onSd) {
10475                // Check if both bits are set.
10476                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10477                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10478            } else {
10479                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10480                        packageAbiOverride);
10481
10482                /*
10483                 * If we have too little free space, try to free cache
10484                 * before giving up.
10485                 */
10486                if (!origin.staged && pkgLite.recommendedInstallLocation
10487                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10488                    // TODO: focus freeing disk space on the target device
10489                    final StorageManager storage = StorageManager.from(mContext);
10490                    final long lowThreshold = storage.getStorageLowBytes(
10491                            Environment.getDataDirectory());
10492
10493                    final long sizeBytes = mContainerService.calculateInstalledSize(
10494                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10495
10496                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10497                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10498                                installFlags, packageAbiOverride);
10499                    }
10500
10501                    /*
10502                     * The cache free must have deleted the file we
10503                     * downloaded to install.
10504                     *
10505                     * TODO: fix the "freeCache" call to not delete
10506                     *       the file we care about.
10507                     */
10508                    if (pkgLite.recommendedInstallLocation
10509                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10510                        pkgLite.recommendedInstallLocation
10511                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10512                    }
10513                }
10514            }
10515
10516            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10517                int loc = pkgLite.recommendedInstallLocation;
10518                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10519                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10520                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10521                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10522                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10523                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10524                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10525                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10526                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10527                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10528                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10529                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10530                } else {
10531                    // Override with defaults if needed.
10532                    loc = installLocationPolicy(pkgLite);
10533                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10534                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10535                    } else if (!onSd && !onInt) {
10536                        // Override install location with flags
10537                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10538                            // Set the flag to install on external media.
10539                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10540                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10541                        } else {
10542                            // Make sure the flag for installing on external
10543                            // media is unset
10544                            installFlags |= PackageManager.INSTALL_INTERNAL;
10545                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10546                        }
10547                    }
10548                }
10549            }
10550
10551            final InstallArgs args = createInstallArgs(this);
10552            mArgs = args;
10553
10554            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10555                 /*
10556                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10557                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10558                 */
10559                int userIdentifier = getUser().getIdentifier();
10560                if (userIdentifier == UserHandle.USER_ALL
10561                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10562                    userIdentifier = UserHandle.USER_OWNER;
10563                }
10564
10565                /*
10566                 * Determine if we have any installed package verifiers. If we
10567                 * do, then we'll defer to them to verify the packages.
10568                 */
10569                final int requiredUid = mRequiredVerifierPackage == null ? -1
10570                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10571                if (!origin.existing && requiredUid != -1
10572                        && isVerificationEnabled(userIdentifier, installFlags)) {
10573                    final Intent verification = new Intent(
10574                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10575                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10576                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10577                            PACKAGE_MIME_TYPE);
10578                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10579
10580                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10581                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10582                            0 /* TODO: Which userId? */);
10583
10584                    if (DEBUG_VERIFY) {
10585                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10586                                + verification.toString() + " with " + pkgLite.verifiers.length
10587                                + " optional verifiers");
10588                    }
10589
10590                    final int verificationId = mPendingVerificationToken++;
10591
10592                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10593
10594                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10595                            installerPackageName);
10596
10597                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10598                            installFlags);
10599
10600                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10601                            pkgLite.packageName);
10602
10603                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10604                            pkgLite.versionCode);
10605
10606                    if (verificationParams != null) {
10607                        if (verificationParams.getVerificationURI() != null) {
10608                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10609                                 verificationParams.getVerificationURI());
10610                        }
10611                        if (verificationParams.getOriginatingURI() != null) {
10612                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10613                                  verificationParams.getOriginatingURI());
10614                        }
10615                        if (verificationParams.getReferrer() != null) {
10616                            verification.putExtra(Intent.EXTRA_REFERRER,
10617                                  verificationParams.getReferrer());
10618                        }
10619                        if (verificationParams.getOriginatingUid() >= 0) {
10620                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10621                                  verificationParams.getOriginatingUid());
10622                        }
10623                        if (verificationParams.getInstallerUid() >= 0) {
10624                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10625                                  verificationParams.getInstallerUid());
10626                        }
10627                    }
10628
10629                    final PackageVerificationState verificationState = new PackageVerificationState(
10630                            requiredUid, args);
10631
10632                    mPendingVerification.append(verificationId, verificationState);
10633
10634                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10635                            receivers, verificationState);
10636
10637                    /*
10638                     * If any sufficient verifiers were listed in the package
10639                     * manifest, attempt to ask them.
10640                     */
10641                    if (sufficientVerifiers != null) {
10642                        final int N = sufficientVerifiers.size();
10643                        if (N == 0) {
10644                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10645                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10646                        } else {
10647                            for (int i = 0; i < N; i++) {
10648                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10649
10650                                final Intent sufficientIntent = new Intent(verification);
10651                                sufficientIntent.setComponent(verifierComponent);
10652
10653                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
10654                            }
10655                        }
10656                    }
10657
10658                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10659                            mRequiredVerifierPackage, receivers);
10660                    if (ret == PackageManager.INSTALL_SUCCEEDED
10661                            && mRequiredVerifierPackage != null) {
10662                        /*
10663                         * Send the intent to the required verification agent,
10664                         * but only start the verification timeout after the
10665                         * target BroadcastReceivers have run.
10666                         */
10667                        verification.setComponent(requiredVerifierComponent);
10668                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
10669                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10670                                new BroadcastReceiver() {
10671                                    @Override
10672                                    public void onReceive(Context context, Intent intent) {
10673                                        final Message msg = mHandler
10674                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10675                                        msg.arg1 = verificationId;
10676                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10677                                    }
10678                                }, null, 0, null, null);
10679
10680                        /*
10681                         * We don't want the copy to proceed until verification
10682                         * succeeds, so null out this field.
10683                         */
10684                        mArgs = null;
10685                    }
10686                } else {
10687                    /*
10688                     * No package verification is enabled, so immediately start
10689                     * the remote call to initiate copy using temporary file.
10690                     */
10691                    ret = args.copyApk(mContainerService, true);
10692                }
10693            }
10694
10695            mRet = ret;
10696        }
10697
10698        @Override
10699        void handleReturnCode() {
10700            // If mArgs is null, then MCS couldn't be reached. When it
10701            // reconnects, it will try again to install. At that point, this
10702            // will succeed.
10703            if (mArgs != null) {
10704                processPendingInstall(mArgs, mRet);
10705            }
10706        }
10707
10708        @Override
10709        void handleServiceError() {
10710            mArgs = createInstallArgs(this);
10711            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10712        }
10713
10714        public boolean isForwardLocked() {
10715            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10716        }
10717    }
10718
10719    /**
10720     * Used during creation of InstallArgs
10721     *
10722     * @param installFlags package installation flags
10723     * @return true if should be installed on external storage
10724     */
10725    private static boolean installOnExternalAsec(int installFlags) {
10726        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10727            return false;
10728        }
10729        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10730            return true;
10731        }
10732        return false;
10733    }
10734
10735    /**
10736     * Used during creation of InstallArgs
10737     *
10738     * @param installFlags package installation flags
10739     * @return true if should be installed as forward locked
10740     */
10741    private static boolean installForwardLocked(int installFlags) {
10742        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10743    }
10744
10745    private InstallArgs createInstallArgs(InstallParams params) {
10746        if (params.move != null) {
10747            return new MoveInstallArgs(params);
10748        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10749            return new AsecInstallArgs(params);
10750        } else {
10751            return new FileInstallArgs(params);
10752        }
10753    }
10754
10755    /**
10756     * Create args that describe an existing installed package. Typically used
10757     * when cleaning up old installs, or used as a move source.
10758     */
10759    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10760            String resourcePath, String[] instructionSets) {
10761        final boolean isInAsec;
10762        if (installOnExternalAsec(installFlags)) {
10763            /* Apps on SD card are always in ASEC containers. */
10764            isInAsec = true;
10765        } else if (installForwardLocked(installFlags)
10766                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10767            /*
10768             * Forward-locked apps are only in ASEC containers if they're the
10769             * new style
10770             */
10771            isInAsec = true;
10772        } else {
10773            isInAsec = false;
10774        }
10775
10776        if (isInAsec) {
10777            return new AsecInstallArgs(codePath, instructionSets,
10778                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10779        } else {
10780            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10781        }
10782    }
10783
10784    static abstract class InstallArgs {
10785        /** @see InstallParams#origin */
10786        final OriginInfo origin;
10787        /** @see InstallParams#move */
10788        final MoveInfo move;
10789
10790        final IPackageInstallObserver2 observer;
10791        // Always refers to PackageManager flags only
10792        final int installFlags;
10793        final String installerPackageName;
10794        final String volumeUuid;
10795        final ManifestDigest manifestDigest;
10796        final UserHandle user;
10797        final String abiOverride;
10798
10799        // The list of instruction sets supported by this app. This is currently
10800        // only used during the rmdex() phase to clean up resources. We can get rid of this
10801        // if we move dex files under the common app path.
10802        /* nullable */ String[] instructionSets;
10803
10804        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10805                int installFlags, String installerPackageName, String volumeUuid,
10806                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10807                String abiOverride) {
10808            this.origin = origin;
10809            this.move = move;
10810            this.installFlags = installFlags;
10811            this.observer = observer;
10812            this.installerPackageName = installerPackageName;
10813            this.volumeUuid = volumeUuid;
10814            this.manifestDigest = manifestDigest;
10815            this.user = user;
10816            this.instructionSets = instructionSets;
10817            this.abiOverride = abiOverride;
10818        }
10819
10820        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10821        abstract int doPreInstall(int status);
10822
10823        /**
10824         * Rename package into final resting place. All paths on the given
10825         * scanned package should be updated to reflect the rename.
10826         */
10827        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10828        abstract int doPostInstall(int status, int uid);
10829
10830        /** @see PackageSettingBase#codePathString */
10831        abstract String getCodePath();
10832        /** @see PackageSettingBase#resourcePathString */
10833        abstract String getResourcePath();
10834
10835        // Need installer lock especially for dex file removal.
10836        abstract void cleanUpResourcesLI();
10837        abstract boolean doPostDeleteLI(boolean delete);
10838
10839        /**
10840         * Called before the source arguments are copied. This is used mostly
10841         * for MoveParams when it needs to read the source file to put it in the
10842         * destination.
10843         */
10844        int doPreCopy() {
10845            return PackageManager.INSTALL_SUCCEEDED;
10846        }
10847
10848        /**
10849         * Called after the source arguments are copied. This is used mostly for
10850         * MoveParams when it needs to read the source file to put it in the
10851         * destination.
10852         *
10853         * @return
10854         */
10855        int doPostCopy(int uid) {
10856            return PackageManager.INSTALL_SUCCEEDED;
10857        }
10858
10859        protected boolean isFwdLocked() {
10860            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10861        }
10862
10863        protected boolean isExternalAsec() {
10864            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10865        }
10866
10867        UserHandle getUser() {
10868            return user;
10869        }
10870    }
10871
10872    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10873        if (!allCodePaths.isEmpty()) {
10874            if (instructionSets == null) {
10875                throw new IllegalStateException("instructionSet == null");
10876            }
10877            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10878            for (String codePath : allCodePaths) {
10879                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10880                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10881                    if (retCode < 0) {
10882                        Slog.w(TAG, "Couldn't remove dex file for package: "
10883                                + " at location " + codePath + ", retcode=" + retCode);
10884                        // we don't consider this to be a failure of the core package deletion
10885                    }
10886                }
10887            }
10888        }
10889    }
10890
10891    /**
10892     * Logic to handle installation of non-ASEC applications, including copying
10893     * and renaming logic.
10894     */
10895    class FileInstallArgs extends InstallArgs {
10896        private File codeFile;
10897        private File resourceFile;
10898
10899        // Example topology:
10900        // /data/app/com.example/base.apk
10901        // /data/app/com.example/split_foo.apk
10902        // /data/app/com.example/lib/arm/libfoo.so
10903        // /data/app/com.example/lib/arm64/libfoo.so
10904        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10905
10906        /** New install */
10907        FileInstallArgs(InstallParams params) {
10908            super(params.origin, params.move, params.observer, params.installFlags,
10909                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10910                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10911            if (isFwdLocked()) {
10912                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10913            }
10914        }
10915
10916        /** Existing install */
10917        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10918            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10919                    null);
10920            this.codeFile = (codePath != null) ? new File(codePath) : null;
10921            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10922        }
10923
10924        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10925            if (origin.staged) {
10926                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10927                codeFile = origin.file;
10928                resourceFile = origin.file;
10929                return PackageManager.INSTALL_SUCCEEDED;
10930            }
10931
10932            try {
10933                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10934                codeFile = tempDir;
10935                resourceFile = tempDir;
10936            } catch (IOException e) {
10937                Slog.w(TAG, "Failed to create copy file: " + e);
10938                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10939            }
10940
10941            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10942                @Override
10943                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10944                    if (!FileUtils.isValidExtFilename(name)) {
10945                        throw new IllegalArgumentException("Invalid filename: " + name);
10946                    }
10947                    try {
10948                        final File file = new File(codeFile, name);
10949                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10950                                O_RDWR | O_CREAT, 0644);
10951                        Os.chmod(file.getAbsolutePath(), 0644);
10952                        return new ParcelFileDescriptor(fd);
10953                    } catch (ErrnoException e) {
10954                        throw new RemoteException("Failed to open: " + e.getMessage());
10955                    }
10956                }
10957            };
10958
10959            int ret = PackageManager.INSTALL_SUCCEEDED;
10960            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10961            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10962                Slog.e(TAG, "Failed to copy package");
10963                return ret;
10964            }
10965
10966            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10967            NativeLibraryHelper.Handle handle = null;
10968            try {
10969                handle = NativeLibraryHelper.Handle.create(codeFile);
10970                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10971                        abiOverride);
10972            } catch (IOException e) {
10973                Slog.e(TAG, "Copying native libraries failed", e);
10974                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10975            } finally {
10976                IoUtils.closeQuietly(handle);
10977            }
10978
10979            return ret;
10980        }
10981
10982        int doPreInstall(int status) {
10983            if (status != PackageManager.INSTALL_SUCCEEDED) {
10984                cleanUp();
10985            }
10986            return status;
10987        }
10988
10989        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10990            if (status != PackageManager.INSTALL_SUCCEEDED) {
10991                cleanUp();
10992                return false;
10993            }
10994
10995            final File targetDir = codeFile.getParentFile();
10996            final File beforeCodeFile = codeFile;
10997            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10998
10999            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11000            try {
11001                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11002            } catch (ErrnoException e) {
11003                Slog.w(TAG, "Failed to rename", e);
11004                return false;
11005            }
11006
11007            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11008                Slog.w(TAG, "Failed to restorecon");
11009                return false;
11010            }
11011
11012            // Reflect the rename internally
11013            codeFile = afterCodeFile;
11014            resourceFile = afterCodeFile;
11015
11016            // Reflect the rename in scanned details
11017            pkg.codePath = afterCodeFile.getAbsolutePath();
11018            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11019                    pkg.baseCodePath);
11020            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11021                    pkg.splitCodePaths);
11022
11023            // Reflect the rename in app info
11024            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11025            pkg.applicationInfo.setCodePath(pkg.codePath);
11026            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11027            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11028            pkg.applicationInfo.setResourcePath(pkg.codePath);
11029            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11030            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11031
11032            return true;
11033        }
11034
11035        int doPostInstall(int status, int uid) {
11036            if (status != PackageManager.INSTALL_SUCCEEDED) {
11037                cleanUp();
11038            }
11039            return status;
11040        }
11041
11042        @Override
11043        String getCodePath() {
11044            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11045        }
11046
11047        @Override
11048        String getResourcePath() {
11049            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11050        }
11051
11052        private boolean cleanUp() {
11053            if (codeFile == null || !codeFile.exists()) {
11054                return false;
11055            }
11056
11057            if (codeFile.isDirectory()) {
11058                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11059            } else {
11060                codeFile.delete();
11061            }
11062
11063            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11064                resourceFile.delete();
11065            }
11066
11067            return true;
11068        }
11069
11070        void cleanUpResourcesLI() {
11071            // Try enumerating all code paths before deleting
11072            List<String> allCodePaths = Collections.EMPTY_LIST;
11073            if (codeFile != null && codeFile.exists()) {
11074                try {
11075                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11076                    allCodePaths = pkg.getAllCodePaths();
11077                } catch (PackageParserException e) {
11078                    // Ignored; we tried our best
11079                }
11080            }
11081
11082            cleanUp();
11083            removeDexFiles(allCodePaths, instructionSets);
11084        }
11085
11086        boolean doPostDeleteLI(boolean delete) {
11087            // XXX err, shouldn't we respect the delete flag?
11088            cleanUpResourcesLI();
11089            return true;
11090        }
11091    }
11092
11093    private boolean isAsecExternal(String cid) {
11094        final String asecPath = PackageHelper.getSdFilesystem(cid);
11095        return !asecPath.startsWith(mAsecInternalPath);
11096    }
11097
11098    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11099            PackageManagerException {
11100        if (copyRet < 0) {
11101            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11102                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11103                throw new PackageManagerException(copyRet, message);
11104            }
11105        }
11106    }
11107
11108    /**
11109     * Extract the MountService "container ID" from the full code path of an
11110     * .apk.
11111     */
11112    static String cidFromCodePath(String fullCodePath) {
11113        int eidx = fullCodePath.lastIndexOf("/");
11114        String subStr1 = fullCodePath.substring(0, eidx);
11115        int sidx = subStr1.lastIndexOf("/");
11116        return subStr1.substring(sidx+1, eidx);
11117    }
11118
11119    /**
11120     * Logic to handle installation of ASEC applications, including copying and
11121     * renaming logic.
11122     */
11123    class AsecInstallArgs extends InstallArgs {
11124        static final String RES_FILE_NAME = "pkg.apk";
11125        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11126
11127        String cid;
11128        String packagePath;
11129        String resourcePath;
11130
11131        /** New install */
11132        AsecInstallArgs(InstallParams params) {
11133            super(params.origin, params.move, params.observer, params.installFlags,
11134                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11135                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
11136        }
11137
11138        /** Existing install */
11139        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11140                        boolean isExternal, boolean isForwardLocked) {
11141            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11142                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11143                    instructionSets, null);
11144            // Hackily pretend we're still looking at a full code path
11145            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11146                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11147            }
11148
11149            // Extract cid from fullCodePath
11150            int eidx = fullCodePath.lastIndexOf("/");
11151            String subStr1 = fullCodePath.substring(0, eidx);
11152            int sidx = subStr1.lastIndexOf("/");
11153            cid = subStr1.substring(sidx+1, eidx);
11154            setMountPath(subStr1);
11155        }
11156
11157        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11158            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11159                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11160                    instructionSets, null);
11161            this.cid = cid;
11162            setMountPath(PackageHelper.getSdDir(cid));
11163        }
11164
11165        void createCopyFile() {
11166            cid = mInstallerService.allocateExternalStageCidLegacy();
11167        }
11168
11169        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11170            if (origin.staged) {
11171                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11172                cid = origin.cid;
11173                setMountPath(PackageHelper.getSdDir(cid));
11174                return PackageManager.INSTALL_SUCCEEDED;
11175            }
11176
11177            if (temp) {
11178                createCopyFile();
11179            } else {
11180                /*
11181                 * Pre-emptively destroy the container since it's destroyed if
11182                 * copying fails due to it existing anyway.
11183                 */
11184                PackageHelper.destroySdDir(cid);
11185            }
11186
11187            final String newMountPath = imcs.copyPackageToContainer(
11188                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11189                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11190
11191            if (newMountPath != null) {
11192                setMountPath(newMountPath);
11193                return PackageManager.INSTALL_SUCCEEDED;
11194            } else {
11195                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11196            }
11197        }
11198
11199        @Override
11200        String getCodePath() {
11201            return packagePath;
11202        }
11203
11204        @Override
11205        String getResourcePath() {
11206            return resourcePath;
11207        }
11208
11209        int doPreInstall(int status) {
11210            if (status != PackageManager.INSTALL_SUCCEEDED) {
11211                // Destroy container
11212                PackageHelper.destroySdDir(cid);
11213            } else {
11214                boolean mounted = PackageHelper.isContainerMounted(cid);
11215                if (!mounted) {
11216                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11217                            Process.SYSTEM_UID);
11218                    if (newMountPath != null) {
11219                        setMountPath(newMountPath);
11220                    } else {
11221                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11222                    }
11223                }
11224            }
11225            return status;
11226        }
11227
11228        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11229            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11230            String newMountPath = null;
11231            if (PackageHelper.isContainerMounted(cid)) {
11232                // Unmount the container
11233                if (!PackageHelper.unMountSdDir(cid)) {
11234                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11235                    return false;
11236                }
11237            }
11238            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11239                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11240                        " which might be stale. Will try to clean up.");
11241                // Clean up the stale container and proceed to recreate.
11242                if (!PackageHelper.destroySdDir(newCacheId)) {
11243                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11244                    return false;
11245                }
11246                // Successfully cleaned up stale container. Try to rename again.
11247                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11248                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11249                            + " inspite of cleaning it up.");
11250                    return false;
11251                }
11252            }
11253            if (!PackageHelper.isContainerMounted(newCacheId)) {
11254                Slog.w(TAG, "Mounting container " + newCacheId);
11255                newMountPath = PackageHelper.mountSdDir(newCacheId,
11256                        getEncryptKey(), Process.SYSTEM_UID);
11257            } else {
11258                newMountPath = PackageHelper.getSdDir(newCacheId);
11259            }
11260            if (newMountPath == null) {
11261                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11262                return false;
11263            }
11264            Log.i(TAG, "Succesfully renamed " + cid +
11265                    " to " + newCacheId +
11266                    " at new path: " + newMountPath);
11267            cid = newCacheId;
11268
11269            final File beforeCodeFile = new File(packagePath);
11270            setMountPath(newMountPath);
11271            final File afterCodeFile = new File(packagePath);
11272
11273            // Reflect the rename in scanned details
11274            pkg.codePath = afterCodeFile.getAbsolutePath();
11275            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11276                    pkg.baseCodePath);
11277            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11278                    pkg.splitCodePaths);
11279
11280            // Reflect the rename in app info
11281            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11282            pkg.applicationInfo.setCodePath(pkg.codePath);
11283            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11284            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11285            pkg.applicationInfo.setResourcePath(pkg.codePath);
11286            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11287            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11288
11289            return true;
11290        }
11291
11292        private void setMountPath(String mountPath) {
11293            final File mountFile = new File(mountPath);
11294
11295            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11296            if (monolithicFile.exists()) {
11297                packagePath = monolithicFile.getAbsolutePath();
11298                if (isFwdLocked()) {
11299                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11300                } else {
11301                    resourcePath = packagePath;
11302                }
11303            } else {
11304                packagePath = mountFile.getAbsolutePath();
11305                resourcePath = packagePath;
11306            }
11307        }
11308
11309        int doPostInstall(int status, int uid) {
11310            if (status != PackageManager.INSTALL_SUCCEEDED) {
11311                cleanUp();
11312            } else {
11313                final int groupOwner;
11314                final String protectedFile;
11315                if (isFwdLocked()) {
11316                    groupOwner = UserHandle.getSharedAppGid(uid);
11317                    protectedFile = RES_FILE_NAME;
11318                } else {
11319                    groupOwner = -1;
11320                    protectedFile = null;
11321                }
11322
11323                if (uid < Process.FIRST_APPLICATION_UID
11324                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11325                    Slog.e(TAG, "Failed to finalize " + cid);
11326                    PackageHelper.destroySdDir(cid);
11327                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11328                }
11329
11330                boolean mounted = PackageHelper.isContainerMounted(cid);
11331                if (!mounted) {
11332                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11333                }
11334            }
11335            return status;
11336        }
11337
11338        private void cleanUp() {
11339            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11340
11341            // Destroy secure container
11342            PackageHelper.destroySdDir(cid);
11343        }
11344
11345        private List<String> getAllCodePaths() {
11346            final File codeFile = new File(getCodePath());
11347            if (codeFile != null && codeFile.exists()) {
11348                try {
11349                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11350                    return pkg.getAllCodePaths();
11351                } catch (PackageParserException e) {
11352                    // Ignored; we tried our best
11353                }
11354            }
11355            return Collections.EMPTY_LIST;
11356        }
11357
11358        void cleanUpResourcesLI() {
11359            // Enumerate all code paths before deleting
11360            cleanUpResourcesLI(getAllCodePaths());
11361        }
11362
11363        private void cleanUpResourcesLI(List<String> allCodePaths) {
11364            cleanUp();
11365            removeDexFiles(allCodePaths, instructionSets);
11366        }
11367
11368        String getPackageName() {
11369            return getAsecPackageName(cid);
11370        }
11371
11372        boolean doPostDeleteLI(boolean delete) {
11373            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11374            final List<String> allCodePaths = getAllCodePaths();
11375            boolean mounted = PackageHelper.isContainerMounted(cid);
11376            if (mounted) {
11377                // Unmount first
11378                if (PackageHelper.unMountSdDir(cid)) {
11379                    mounted = false;
11380                }
11381            }
11382            if (!mounted && delete) {
11383                cleanUpResourcesLI(allCodePaths);
11384            }
11385            return !mounted;
11386        }
11387
11388        @Override
11389        int doPreCopy() {
11390            if (isFwdLocked()) {
11391                if (!PackageHelper.fixSdPermissions(cid,
11392                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11393                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11394                }
11395            }
11396
11397            return PackageManager.INSTALL_SUCCEEDED;
11398        }
11399
11400        @Override
11401        int doPostCopy(int uid) {
11402            if (isFwdLocked()) {
11403                if (uid < Process.FIRST_APPLICATION_UID
11404                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11405                                RES_FILE_NAME)) {
11406                    Slog.e(TAG, "Failed to finalize " + cid);
11407                    PackageHelper.destroySdDir(cid);
11408                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11409                }
11410            }
11411
11412            return PackageManager.INSTALL_SUCCEEDED;
11413        }
11414    }
11415
11416    /**
11417     * Logic to handle movement of existing installed applications.
11418     */
11419    class MoveInstallArgs extends InstallArgs {
11420        private File codeFile;
11421        private File resourceFile;
11422
11423        /** New install */
11424        MoveInstallArgs(InstallParams params) {
11425            super(params.origin, params.move, params.observer, params.installFlags,
11426                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11427                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
11428        }
11429
11430        int copyApk(IMediaContainerService imcs, boolean temp) {
11431            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11432                    + move.fromUuid + " to " + move.toUuid);
11433            synchronized (mInstaller) {
11434                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11435                        move.dataAppName, move.appId, move.seinfo) != 0) {
11436                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11437                }
11438            }
11439
11440            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11441            resourceFile = codeFile;
11442            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11443
11444            return PackageManager.INSTALL_SUCCEEDED;
11445        }
11446
11447        int doPreInstall(int status) {
11448            if (status != PackageManager.INSTALL_SUCCEEDED) {
11449                cleanUp(move.toUuid);
11450            }
11451            return status;
11452        }
11453
11454        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11455            if (status != PackageManager.INSTALL_SUCCEEDED) {
11456                cleanUp(move.toUuid);
11457                return false;
11458            }
11459
11460            // Reflect the move in app info
11461            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11462            pkg.applicationInfo.setCodePath(pkg.codePath);
11463            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11464            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11465            pkg.applicationInfo.setResourcePath(pkg.codePath);
11466            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11467            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11468
11469            return true;
11470        }
11471
11472        int doPostInstall(int status, int uid) {
11473            if (status == PackageManager.INSTALL_SUCCEEDED) {
11474                cleanUp(move.fromUuid);
11475            } else {
11476                cleanUp(move.toUuid);
11477            }
11478            return status;
11479        }
11480
11481        @Override
11482        String getCodePath() {
11483            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11484        }
11485
11486        @Override
11487        String getResourcePath() {
11488            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11489        }
11490
11491        private boolean cleanUp(String volumeUuid) {
11492            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11493                    move.dataAppName);
11494            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11495            synchronized (mInstallLock) {
11496                // Clean up both app data and code
11497                removeDataDirsLI(volumeUuid, move.packageName);
11498                if (codeFile.isDirectory()) {
11499                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11500                } else {
11501                    codeFile.delete();
11502                }
11503            }
11504            return true;
11505        }
11506
11507        void cleanUpResourcesLI() {
11508            throw new UnsupportedOperationException();
11509        }
11510
11511        boolean doPostDeleteLI(boolean delete) {
11512            throw new UnsupportedOperationException();
11513        }
11514    }
11515
11516    static String getAsecPackageName(String packageCid) {
11517        int idx = packageCid.lastIndexOf("-");
11518        if (idx == -1) {
11519            return packageCid;
11520        }
11521        return packageCid.substring(0, idx);
11522    }
11523
11524    // Utility method used to create code paths based on package name and available index.
11525    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11526        String idxStr = "";
11527        int idx = 1;
11528        // Fall back to default value of idx=1 if prefix is not
11529        // part of oldCodePath
11530        if (oldCodePath != null) {
11531            String subStr = oldCodePath;
11532            // Drop the suffix right away
11533            if (suffix != null && subStr.endsWith(suffix)) {
11534                subStr = subStr.substring(0, subStr.length() - suffix.length());
11535            }
11536            // If oldCodePath already contains prefix find out the
11537            // ending index to either increment or decrement.
11538            int sidx = subStr.lastIndexOf(prefix);
11539            if (sidx != -1) {
11540                subStr = subStr.substring(sidx + prefix.length());
11541                if (subStr != null) {
11542                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11543                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11544                    }
11545                    try {
11546                        idx = Integer.parseInt(subStr);
11547                        if (idx <= 1) {
11548                            idx++;
11549                        } else {
11550                            idx--;
11551                        }
11552                    } catch(NumberFormatException e) {
11553                    }
11554                }
11555            }
11556        }
11557        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11558        return prefix + idxStr;
11559    }
11560
11561    private File getNextCodePath(File targetDir, String packageName) {
11562        int suffix = 1;
11563        File result;
11564        do {
11565            result = new File(targetDir, packageName + "-" + suffix);
11566            suffix++;
11567        } while (result.exists());
11568        return result;
11569    }
11570
11571    // Utility method that returns the relative package path with respect
11572    // to the installation directory. Like say for /data/data/com.test-1.apk
11573    // string com.test-1 is returned.
11574    static String deriveCodePathName(String codePath) {
11575        if (codePath == null) {
11576            return null;
11577        }
11578        final File codeFile = new File(codePath);
11579        final String name = codeFile.getName();
11580        if (codeFile.isDirectory()) {
11581            return name;
11582        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11583            final int lastDot = name.lastIndexOf('.');
11584            return name.substring(0, lastDot);
11585        } else {
11586            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11587            return null;
11588        }
11589    }
11590
11591    class PackageInstalledInfo {
11592        String name;
11593        int uid;
11594        // The set of users that originally had this package installed.
11595        int[] origUsers;
11596        // The set of users that now have this package installed.
11597        int[] newUsers;
11598        PackageParser.Package pkg;
11599        int returnCode;
11600        String returnMsg;
11601        PackageRemovedInfo removedInfo;
11602
11603        public void setError(int code, String msg) {
11604            returnCode = code;
11605            returnMsg = msg;
11606            Slog.w(TAG, msg);
11607        }
11608
11609        public void setError(String msg, PackageParserException e) {
11610            returnCode = e.error;
11611            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11612            Slog.w(TAG, msg, e);
11613        }
11614
11615        public void setError(String msg, PackageManagerException e) {
11616            returnCode = e.error;
11617            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11618            Slog.w(TAG, msg, e);
11619        }
11620
11621        // In some error cases we want to convey more info back to the observer
11622        String origPackage;
11623        String origPermission;
11624    }
11625
11626    /*
11627     * Install a non-existing package.
11628     */
11629    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11630            UserHandle user, String installerPackageName, String volumeUuid,
11631            PackageInstalledInfo res) {
11632        // Remember this for later, in case we need to rollback this install
11633        String pkgName = pkg.packageName;
11634
11635        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11636        final boolean dataDirExists = Environment
11637                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists();
11638        synchronized(mPackages) {
11639            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11640                // A package with the same name is already installed, though
11641                // it has been renamed to an older name.  The package we
11642                // are trying to install should be installed as an update to
11643                // the existing one, but that has not been requested, so bail.
11644                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11645                        + " without first uninstalling package running as "
11646                        + mSettings.mRenamedPackages.get(pkgName));
11647                return;
11648            }
11649            if (mPackages.containsKey(pkgName)) {
11650                // Don't allow installation over an existing package with the same name.
11651                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11652                        + " without first uninstalling.");
11653                return;
11654            }
11655        }
11656
11657        try {
11658            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11659                    System.currentTimeMillis(), user);
11660
11661            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11662            // delete the partially installed application. the data directory will have to be
11663            // restored if it was already existing
11664            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11665                // remove package from internal structures.  Note that we want deletePackageX to
11666                // delete the package data and cache directories that it created in
11667                // scanPackageLocked, unless those directories existed before we even tried to
11668                // install.
11669                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11670                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11671                                res.removedInfo, true);
11672            }
11673
11674        } catch (PackageManagerException e) {
11675            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11676        }
11677    }
11678
11679    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11680        // Can't rotate keys during boot or if sharedUser.
11681        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11682                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11683            return false;
11684        }
11685        // app is using upgradeKeySets; make sure all are valid
11686        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11687        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11688        for (int i = 0; i < upgradeKeySets.length; i++) {
11689            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11690                Slog.wtf(TAG, "Package "
11691                         + (oldPs.name != null ? oldPs.name : "<null>")
11692                         + " contains upgrade-key-set reference to unknown key-set: "
11693                         + upgradeKeySets[i]
11694                         + " reverting to signatures check.");
11695                return false;
11696            }
11697        }
11698        return true;
11699    }
11700
11701    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11702        // Upgrade keysets are being used.  Determine if new package has a superset of the
11703        // required keys.
11704        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11705        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11706        for (int i = 0; i < upgradeKeySets.length; i++) {
11707            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11708            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11709                return true;
11710            }
11711        }
11712        return false;
11713    }
11714
11715    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11716            UserHandle user, String installerPackageName, String volumeUuid,
11717            PackageInstalledInfo res) {
11718        final PackageParser.Package oldPackage;
11719        final String pkgName = pkg.packageName;
11720        final int[] allUsers;
11721        final boolean[] perUserInstalled;
11722        final boolean weFroze;
11723
11724        // First find the old package info and check signatures
11725        synchronized(mPackages) {
11726            oldPackage = mPackages.get(pkgName);
11727            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11728            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11729            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11730                if(!checkUpgradeKeySetLP(ps, pkg)) {
11731                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11732                            "New package not signed by keys specified by upgrade-keysets: "
11733                            + pkgName);
11734                    return;
11735                }
11736            } else {
11737                // default to original signature matching
11738                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11739                    != PackageManager.SIGNATURE_MATCH) {
11740                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11741                            "New package has a different signature: " + pkgName);
11742                    return;
11743                }
11744            }
11745
11746            // In case of rollback, remember per-user/profile install state
11747            allUsers = sUserManager.getUserIds();
11748            perUserInstalled = new boolean[allUsers.length];
11749            for (int i = 0; i < allUsers.length; i++) {
11750                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11751            }
11752
11753            // Mark the app as frozen to prevent launching during the upgrade
11754            // process, and then kill all running instances
11755            if (!ps.frozen) {
11756                ps.frozen = true;
11757                weFroze = true;
11758            } else {
11759                weFroze = false;
11760            }
11761        }
11762
11763        // Now that we're guarded by frozen state, kill app during upgrade
11764        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11765
11766        try {
11767            boolean sysPkg = (isSystemApp(oldPackage));
11768            if (sysPkg) {
11769                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11770                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11771            } else {
11772                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11773                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11774            }
11775        } finally {
11776            // Regardless of success or failure of upgrade steps above, always
11777            // unfreeze the package if we froze it
11778            if (weFroze) {
11779                unfreezePackage(pkgName);
11780            }
11781        }
11782    }
11783
11784    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11785            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11786            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11787            String volumeUuid, PackageInstalledInfo res) {
11788        String pkgName = deletedPackage.packageName;
11789        boolean deletedPkg = true;
11790        boolean updatedSettings = false;
11791
11792        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11793                + deletedPackage);
11794        long origUpdateTime;
11795        if (pkg.mExtras != null) {
11796            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11797        } else {
11798            origUpdateTime = 0;
11799        }
11800
11801        // First delete the existing package while retaining the data directory
11802        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11803                res.removedInfo, true)) {
11804            // If the existing package wasn't successfully deleted
11805            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11806            deletedPkg = false;
11807        } else {
11808            // Successfully deleted the old package; proceed with replace.
11809
11810            // If deleted package lived in a container, give users a chance to
11811            // relinquish resources before killing.
11812            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11813                if (DEBUG_INSTALL) {
11814                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11815                }
11816                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11817                final ArrayList<String> pkgList = new ArrayList<String>(1);
11818                pkgList.add(deletedPackage.applicationInfo.packageName);
11819                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11820            }
11821
11822            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11823            try {
11824                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11825                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11826                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11827                        perUserInstalled, res, user);
11828                updatedSettings = true;
11829            } catch (PackageManagerException e) {
11830                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11831            }
11832        }
11833
11834        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11835            // remove package from internal structures.  Note that we want deletePackageX to
11836            // delete the package data and cache directories that it created in
11837            // scanPackageLocked, unless those directories existed before we even tried to
11838            // install.
11839            if(updatedSettings) {
11840                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11841                deletePackageLI(
11842                        pkgName, null, true, allUsers, perUserInstalled,
11843                        PackageManager.DELETE_KEEP_DATA,
11844                                res.removedInfo, true);
11845            }
11846            // Since we failed to install the new package we need to restore the old
11847            // package that we deleted.
11848            if (deletedPkg) {
11849                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11850                File restoreFile = new File(deletedPackage.codePath);
11851                // Parse old package
11852                boolean oldExternal = isExternal(deletedPackage);
11853                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11854                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11855                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11856                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11857                try {
11858                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11859                } catch (PackageManagerException e) {
11860                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11861                            + e.getMessage());
11862                    return;
11863                }
11864                // Restore of old package succeeded. Update permissions.
11865                // writer
11866                synchronized (mPackages) {
11867                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11868                            UPDATE_PERMISSIONS_ALL);
11869                    // can downgrade to reader
11870                    mSettings.writeLPr();
11871                }
11872                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11873            }
11874        }
11875    }
11876
11877    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11878            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11879            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11880            String volumeUuid, PackageInstalledInfo res) {
11881        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11882                + ", old=" + deletedPackage);
11883        boolean disabledSystem = false;
11884        boolean updatedSettings = false;
11885        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11886        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11887                != 0) {
11888            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11889        }
11890        String packageName = deletedPackage.packageName;
11891        if (packageName == null) {
11892            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11893                    "Attempt to delete null packageName.");
11894            return;
11895        }
11896        PackageParser.Package oldPkg;
11897        PackageSetting oldPkgSetting;
11898        // reader
11899        synchronized (mPackages) {
11900            oldPkg = mPackages.get(packageName);
11901            oldPkgSetting = mSettings.mPackages.get(packageName);
11902            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11903                    (oldPkgSetting == null)) {
11904                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11905                        "Couldn't find package:" + packageName + " information");
11906                return;
11907            }
11908        }
11909
11910        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11911        res.removedInfo.removedPackage = packageName;
11912        // Remove existing system package
11913        removePackageLI(oldPkgSetting, true);
11914        // writer
11915        synchronized (mPackages) {
11916            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11917            if (!disabledSystem && deletedPackage != null) {
11918                // We didn't need to disable the .apk as a current system package,
11919                // which means we are replacing another update that is already
11920                // installed.  We need to make sure to delete the older one's .apk.
11921                res.removedInfo.args = createInstallArgsForExisting(0,
11922                        deletedPackage.applicationInfo.getCodePath(),
11923                        deletedPackage.applicationInfo.getResourcePath(),
11924                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11925            } else {
11926                res.removedInfo.args = null;
11927            }
11928        }
11929
11930        // Successfully disabled the old package. Now proceed with re-installation
11931        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11932
11933        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11934        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11935
11936        PackageParser.Package newPackage = null;
11937        try {
11938            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11939            if (newPackage.mExtras != null) {
11940                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11941                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11942                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11943
11944                // is the update attempting to change shared user? that isn't going to work...
11945                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11946                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11947                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11948                            + " to " + newPkgSetting.sharedUser);
11949                    updatedSettings = true;
11950                }
11951            }
11952
11953            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11954                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11955                        perUserInstalled, res, user);
11956                updatedSettings = true;
11957            }
11958
11959        } catch (PackageManagerException e) {
11960            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11961        }
11962
11963        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11964            // Re installation failed. Restore old information
11965            // Remove new pkg information
11966            if (newPackage != null) {
11967                removeInstalledPackageLI(newPackage, true);
11968            }
11969            // Add back the old system package
11970            try {
11971                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11972            } catch (PackageManagerException e) {
11973                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11974            }
11975            // Restore the old system information in Settings
11976            synchronized (mPackages) {
11977                if (disabledSystem) {
11978                    mSettings.enableSystemPackageLPw(packageName);
11979                }
11980                if (updatedSettings) {
11981                    mSettings.setInstallerPackageName(packageName,
11982                            oldPkgSetting.installerPackageName);
11983                }
11984                mSettings.writeLPr();
11985            }
11986        }
11987    }
11988
11989    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
11990            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
11991            UserHandle user) {
11992        String pkgName = newPackage.packageName;
11993        synchronized (mPackages) {
11994            //write settings. the installStatus will be incomplete at this stage.
11995            //note that the new package setting would have already been
11996            //added to mPackages. It hasn't been persisted yet.
11997            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11998            mSettings.writeLPr();
11999        }
12000
12001        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12002
12003        synchronized (mPackages) {
12004            updatePermissionsLPw(newPackage.packageName, newPackage,
12005                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12006                            ? UPDATE_PERMISSIONS_ALL : 0));
12007            // For system-bundled packages, we assume that installing an upgraded version
12008            // of the package implies that the user actually wants to run that new code,
12009            // so we enable the package.
12010            PackageSetting ps = mSettings.mPackages.get(pkgName);
12011            if (ps != null) {
12012                if (isSystemApp(newPackage)) {
12013                    // NB: implicit assumption that system package upgrades apply to all users
12014                    if (DEBUG_INSTALL) {
12015                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12016                    }
12017                    if (res.origUsers != null) {
12018                        for (int userHandle : res.origUsers) {
12019                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12020                                    userHandle, installerPackageName);
12021                        }
12022                    }
12023                    // Also convey the prior install/uninstall state
12024                    if (allUsers != null && perUserInstalled != null) {
12025                        for (int i = 0; i < allUsers.length; i++) {
12026                            if (DEBUG_INSTALL) {
12027                                Slog.d(TAG, "    user " + allUsers[i]
12028                                        + " => " + perUserInstalled[i]);
12029                            }
12030                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12031                        }
12032                        // these install state changes will be persisted in the
12033                        // upcoming call to mSettings.writeLPr().
12034                    }
12035                }
12036                // It's implied that when a user requests installation, they want the app to be
12037                // installed and enabled.
12038                int userId = user.getIdentifier();
12039                if (userId != UserHandle.USER_ALL) {
12040                    ps.setInstalled(true, userId);
12041                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12042                }
12043            }
12044            res.name = pkgName;
12045            res.uid = newPackage.applicationInfo.uid;
12046            res.pkg = newPackage;
12047            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12048            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12049            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12050            //to update install status
12051            mSettings.writeLPr();
12052        }
12053    }
12054
12055    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12056        final int installFlags = args.installFlags;
12057        final String installerPackageName = args.installerPackageName;
12058        final String volumeUuid = args.volumeUuid;
12059        final File tmpPackageFile = new File(args.getCodePath());
12060        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12061        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12062                || (args.volumeUuid != null));
12063        boolean replace = false;
12064        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12065        if (args.move != null) {
12066            // moving a complete application; perfom an initial scan on the new install location
12067            scanFlags |= SCAN_INITIAL;
12068        }
12069        // Result object to be returned
12070        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12071
12072        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12073        // Retrieve PackageSettings and parse package
12074        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12075                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12076                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12077        PackageParser pp = new PackageParser();
12078        pp.setSeparateProcesses(mSeparateProcesses);
12079        pp.setDisplayMetrics(mMetrics);
12080
12081        final PackageParser.Package pkg;
12082        try {
12083            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12084        } catch (PackageParserException e) {
12085            res.setError("Failed parse during installPackageLI", e);
12086            return;
12087        }
12088
12089        // Mark that we have an install time CPU ABI override.
12090        pkg.cpuAbiOverride = args.abiOverride;
12091
12092        String pkgName = res.name = pkg.packageName;
12093        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12094            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12095                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12096                return;
12097            }
12098        }
12099
12100        try {
12101            pp.collectCertificates(pkg, parseFlags);
12102            pp.collectManifestDigest(pkg);
12103        } catch (PackageParserException e) {
12104            res.setError("Failed collect during installPackageLI", e);
12105            return;
12106        }
12107
12108        /* If the installer passed in a manifest digest, compare it now. */
12109        if (args.manifestDigest != null) {
12110            if (DEBUG_INSTALL) {
12111                final String parsedManifest = pkg.manifestDigest == null ? "null"
12112                        : pkg.manifestDigest.toString();
12113                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12114                        + parsedManifest);
12115            }
12116
12117            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12118                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12119                return;
12120            }
12121        } else if (DEBUG_INSTALL) {
12122            final String parsedManifest = pkg.manifestDigest == null
12123                    ? "null" : pkg.manifestDigest.toString();
12124            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12125        }
12126
12127        // Get rid of all references to package scan path via parser.
12128        pp = null;
12129        String oldCodePath = null;
12130        boolean systemApp = false;
12131        synchronized (mPackages) {
12132            // Check if installing already existing package
12133            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12134                String oldName = mSettings.mRenamedPackages.get(pkgName);
12135                if (pkg.mOriginalPackages != null
12136                        && pkg.mOriginalPackages.contains(oldName)
12137                        && mPackages.containsKey(oldName)) {
12138                    // This package is derived from an original package,
12139                    // and this device has been updating from that original
12140                    // name.  We must continue using the original name, so
12141                    // rename the new package here.
12142                    pkg.setPackageName(oldName);
12143                    pkgName = pkg.packageName;
12144                    replace = true;
12145                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12146                            + oldName + " pkgName=" + pkgName);
12147                } else if (mPackages.containsKey(pkgName)) {
12148                    // This package, under its official name, already exists
12149                    // on the device; we should replace it.
12150                    replace = true;
12151                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12152                }
12153
12154                // Prevent apps opting out from runtime permissions
12155                if (replace) {
12156                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12157                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12158                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12159                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12160                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12161                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12162                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12163                                        + " doesn't support runtime permissions but the old"
12164                                        + " target SDK " + oldTargetSdk + " does.");
12165                        return;
12166                    }
12167                }
12168            }
12169
12170            PackageSetting ps = mSettings.mPackages.get(pkgName);
12171            if (ps != null) {
12172                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12173
12174                // Quick sanity check that we're signed correctly if updating;
12175                // we'll check this again later when scanning, but we want to
12176                // bail early here before tripping over redefined permissions.
12177                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12178                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12179                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12180                                + pkg.packageName + " upgrade keys do not match the "
12181                                + "previously installed version");
12182                        return;
12183                    }
12184                } else {
12185                    try {
12186                        verifySignaturesLP(ps, pkg);
12187                    } catch (PackageManagerException e) {
12188                        res.setError(e.error, e.getMessage());
12189                        return;
12190                    }
12191                }
12192
12193                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12194                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12195                    systemApp = (ps.pkg.applicationInfo.flags &
12196                            ApplicationInfo.FLAG_SYSTEM) != 0;
12197                }
12198                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12199            }
12200
12201            // Check whether the newly-scanned package wants to define an already-defined perm
12202            int N = pkg.permissions.size();
12203            for (int i = N-1; i >= 0; i--) {
12204                PackageParser.Permission perm = pkg.permissions.get(i);
12205                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12206                if (bp != null) {
12207                    // If the defining package is signed with our cert, it's okay.  This
12208                    // also includes the "updating the same package" case, of course.
12209                    // "updating same package" could also involve key-rotation.
12210                    final boolean sigsOk;
12211                    if (bp.sourcePackage.equals(pkg.packageName)
12212                            && (bp.packageSetting instanceof PackageSetting)
12213                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12214                                    scanFlags))) {
12215                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12216                    } else {
12217                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12218                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12219                    }
12220                    if (!sigsOk) {
12221                        // If the owning package is the system itself, we log but allow
12222                        // install to proceed; we fail the install on all other permission
12223                        // redefinitions.
12224                        if (!bp.sourcePackage.equals("android")) {
12225                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12226                                    + pkg.packageName + " attempting to redeclare permission "
12227                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12228                            res.origPermission = perm.info.name;
12229                            res.origPackage = bp.sourcePackage;
12230                            return;
12231                        } else {
12232                            Slog.w(TAG, "Package " + pkg.packageName
12233                                    + " attempting to redeclare system permission "
12234                                    + perm.info.name + "; ignoring new declaration");
12235                            pkg.permissions.remove(i);
12236                        }
12237                    }
12238                }
12239            }
12240
12241        }
12242
12243        if (systemApp && onExternal) {
12244            // Disable updates to system apps on sdcard
12245            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12246                    "Cannot install updates to system apps on sdcard");
12247            return;
12248        }
12249
12250        if (args.move != null) {
12251            // We did an in-place move, so dex is ready to roll
12252            scanFlags |= SCAN_NO_DEX;
12253            scanFlags |= SCAN_MOVE;
12254        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12255            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12256            scanFlags |= SCAN_NO_DEX;
12257
12258            try {
12259                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12260                        true /* extract libs */);
12261            } catch (PackageManagerException pme) {
12262                Slog.e(TAG, "Error deriving application ABI", pme);
12263                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12264                return;
12265            }
12266
12267            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12268            int result = mPackageDexOptimizer
12269                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12270                            false /* defer */, false /* inclDependencies */);
12271            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12272                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12273                return;
12274            }
12275        }
12276
12277        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12278            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12279            return;
12280        }
12281
12282        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12283
12284        if (replace) {
12285            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
12286                    installerPackageName, volumeUuid, res);
12287        } else {
12288            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12289                    args.user, installerPackageName, volumeUuid, res);
12290        }
12291        synchronized (mPackages) {
12292            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12293            if (ps != null) {
12294                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12295            }
12296        }
12297    }
12298
12299    private void startIntentFilterVerifications(int userId, boolean replacing,
12300            PackageParser.Package pkg) {
12301        if (mIntentFilterVerifierComponent == null) {
12302            Slog.w(TAG, "No IntentFilter verification will not be done as "
12303                    + "there is no IntentFilterVerifier available!");
12304            return;
12305        }
12306
12307        final int verifierUid = getPackageUid(
12308                mIntentFilterVerifierComponent.getPackageName(),
12309                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12310
12311        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12312        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12313        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12314        mHandler.sendMessage(msg);
12315    }
12316
12317    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12318            PackageParser.Package pkg) {
12319        int size = pkg.activities.size();
12320        if (size == 0) {
12321            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12322                    "No activity, so no need to verify any IntentFilter!");
12323            return;
12324        }
12325
12326        final boolean hasDomainURLs = hasDomainURLs(pkg);
12327        if (!hasDomainURLs) {
12328            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12329                    "No domain URLs, so no need to verify any IntentFilter!");
12330            return;
12331        }
12332
12333        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12334                + " if any IntentFilter from the " + size
12335                + " Activities needs verification ...");
12336
12337        int count = 0;
12338        final String packageName = pkg.packageName;
12339
12340        synchronized (mPackages) {
12341            // If this is a new install and we see that we've already run verification for this
12342            // package, we have nothing to do: it means the state was restored from backup.
12343            if (!replacing) {
12344                IntentFilterVerificationInfo ivi =
12345                        mSettings.getIntentFilterVerificationLPr(packageName);
12346                if (ivi != null) {
12347                    if (DEBUG_DOMAIN_VERIFICATION) {
12348                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12349                                + ivi.getStatusString());
12350                    }
12351                    return;
12352                }
12353            }
12354
12355            // If any filters need to be verified, then all need to be.
12356            boolean needToVerify = false;
12357            for (PackageParser.Activity a : pkg.activities) {
12358                for (ActivityIntentInfo filter : a.intents) {
12359                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12360                        if (DEBUG_DOMAIN_VERIFICATION) {
12361                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12362                        }
12363                        needToVerify = true;
12364                        break;
12365                    }
12366                }
12367            }
12368
12369            if (needToVerify) {
12370                final int verificationId = mIntentFilterVerificationToken++;
12371                for (PackageParser.Activity a : pkg.activities) {
12372                    for (ActivityIntentInfo filter : a.intents) {
12373                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12374                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12375                                    "Verification needed for IntentFilter:" + filter.toString());
12376                            mIntentFilterVerifier.addOneIntentFilterVerification(
12377                                    verifierUid, userId, verificationId, filter, packageName);
12378                            count++;
12379                        }
12380                    }
12381                }
12382            }
12383        }
12384
12385        if (count > 0) {
12386            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12387                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12388                    +  " for userId:" + userId);
12389            mIntentFilterVerifier.startVerifications(userId);
12390        } else {
12391            if (DEBUG_DOMAIN_VERIFICATION) {
12392                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12393            }
12394        }
12395    }
12396
12397    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12398        final ComponentName cn  = filter.activity.getComponentName();
12399        final String packageName = cn.getPackageName();
12400
12401        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12402                packageName);
12403        if (ivi == null) {
12404            return true;
12405        }
12406        int status = ivi.getStatus();
12407        switch (status) {
12408            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12409            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12410                return true;
12411
12412            default:
12413                // Nothing to do
12414                return false;
12415        }
12416    }
12417
12418    private static boolean isMultiArch(PackageSetting ps) {
12419        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12420    }
12421
12422    private static boolean isMultiArch(ApplicationInfo info) {
12423        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12424    }
12425
12426    private static boolean isExternal(PackageParser.Package pkg) {
12427        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12428    }
12429
12430    private static boolean isExternal(PackageSetting ps) {
12431        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12432    }
12433
12434    private static boolean isExternal(ApplicationInfo info) {
12435        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12436    }
12437
12438    private static boolean isSystemApp(PackageParser.Package pkg) {
12439        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12440    }
12441
12442    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12443        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12444    }
12445
12446    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12447        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12448    }
12449
12450    private static boolean isSystemApp(PackageSetting ps) {
12451        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12452    }
12453
12454    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12455        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12456    }
12457
12458    private int packageFlagsToInstallFlags(PackageSetting ps) {
12459        int installFlags = 0;
12460        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12461            // This existing package was an external ASEC install when we have
12462            // the external flag without a UUID
12463            installFlags |= PackageManager.INSTALL_EXTERNAL;
12464        }
12465        if (ps.isForwardLocked()) {
12466            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12467        }
12468        return installFlags;
12469    }
12470
12471    private void deleteTempPackageFiles() {
12472        final FilenameFilter filter = new FilenameFilter() {
12473            public boolean accept(File dir, String name) {
12474                return name.startsWith("vmdl") && name.endsWith(".tmp");
12475            }
12476        };
12477        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12478            file.delete();
12479        }
12480    }
12481
12482    @Override
12483    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12484            int flags) {
12485        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12486                flags);
12487    }
12488
12489    @Override
12490    public void deletePackage(final String packageName,
12491            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12492        mContext.enforceCallingOrSelfPermission(
12493                android.Manifest.permission.DELETE_PACKAGES, null);
12494        Preconditions.checkNotNull(packageName);
12495        Preconditions.checkNotNull(observer);
12496        final int uid = Binder.getCallingUid();
12497        if (UserHandle.getUserId(uid) != userId) {
12498            mContext.enforceCallingPermission(
12499                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12500                    "deletePackage for user " + userId);
12501        }
12502        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12503            try {
12504                observer.onPackageDeleted(packageName,
12505                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12506            } catch (RemoteException re) {
12507            }
12508            return;
12509        }
12510
12511        boolean uninstallBlocked = false;
12512        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12513            int[] users = sUserManager.getUserIds();
12514            for (int i = 0; i < users.length; ++i) {
12515                if (getBlockUninstallForUser(packageName, users[i])) {
12516                    uninstallBlocked = true;
12517                    break;
12518                }
12519            }
12520        } else {
12521            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12522        }
12523        if (uninstallBlocked) {
12524            try {
12525                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12526                        null);
12527            } catch (RemoteException re) {
12528            }
12529            return;
12530        }
12531
12532        if (DEBUG_REMOVE) {
12533            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12534        }
12535        // Queue up an async operation since the package deletion may take a little while.
12536        mHandler.post(new Runnable() {
12537            public void run() {
12538                mHandler.removeCallbacks(this);
12539                final int returnCode = deletePackageX(packageName, userId, flags);
12540                if (observer != null) {
12541                    try {
12542                        observer.onPackageDeleted(packageName, returnCode, null);
12543                    } catch (RemoteException e) {
12544                        Log.i(TAG, "Observer no longer exists.");
12545                    } //end catch
12546                } //end if
12547            } //end run
12548        });
12549    }
12550
12551    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12552        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12553                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12554        try {
12555            if (dpm != null) {
12556                if (dpm.isDeviceOwner(packageName)) {
12557                    return true;
12558                }
12559                int[] users;
12560                if (userId == UserHandle.USER_ALL) {
12561                    users = sUserManager.getUserIds();
12562                } else {
12563                    users = new int[]{userId};
12564                }
12565                for (int i = 0; i < users.length; ++i) {
12566                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12567                        return true;
12568                    }
12569                }
12570            }
12571        } catch (RemoteException e) {
12572        }
12573        return false;
12574    }
12575
12576    /**
12577     *  This method is an internal method that could be get invoked either
12578     *  to delete an installed package or to clean up a failed installation.
12579     *  After deleting an installed package, a broadcast is sent to notify any
12580     *  listeners that the package has been installed. For cleaning up a failed
12581     *  installation, the broadcast is not necessary since the package's
12582     *  installation wouldn't have sent the initial broadcast either
12583     *  The key steps in deleting a package are
12584     *  deleting the package information in internal structures like mPackages,
12585     *  deleting the packages base directories through installd
12586     *  updating mSettings to reflect current status
12587     *  persisting settings for later use
12588     *  sending a broadcast if necessary
12589     */
12590    private int deletePackageX(String packageName, int userId, int flags) {
12591        final PackageRemovedInfo info = new PackageRemovedInfo();
12592        final boolean res;
12593
12594        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12595                ? UserHandle.ALL : new UserHandle(userId);
12596
12597        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12598            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12599            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12600        }
12601
12602        boolean removedForAllUsers = false;
12603        boolean systemUpdate = false;
12604
12605        // for the uninstall-updates case and restricted profiles, remember the per-
12606        // userhandle installed state
12607        int[] allUsers;
12608        boolean[] perUserInstalled;
12609        synchronized (mPackages) {
12610            PackageSetting ps = mSettings.mPackages.get(packageName);
12611            allUsers = sUserManager.getUserIds();
12612            perUserInstalled = new boolean[allUsers.length];
12613            for (int i = 0; i < allUsers.length; i++) {
12614                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12615            }
12616        }
12617
12618        synchronized (mInstallLock) {
12619            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12620            res = deletePackageLI(packageName, removeForUser,
12621                    true, allUsers, perUserInstalled,
12622                    flags | REMOVE_CHATTY, info, true);
12623            systemUpdate = info.isRemovedPackageSystemUpdate;
12624            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12625                removedForAllUsers = true;
12626            }
12627            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12628                    + " removedForAllUsers=" + removedForAllUsers);
12629        }
12630
12631        if (res) {
12632            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12633
12634            // If the removed package was a system update, the old system package
12635            // was re-enabled; we need to broadcast this information
12636            if (systemUpdate) {
12637                Bundle extras = new Bundle(1);
12638                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12639                        ? info.removedAppId : info.uid);
12640                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12641
12642                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12643                        extras, null, null, null);
12644                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12645                        extras, null, null, null);
12646                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12647                        null, packageName, null, null);
12648            }
12649        }
12650        // Force a gc here.
12651        Runtime.getRuntime().gc();
12652        // Delete the resources here after sending the broadcast to let
12653        // other processes clean up before deleting resources.
12654        if (info.args != null) {
12655            synchronized (mInstallLock) {
12656                info.args.doPostDeleteLI(true);
12657            }
12658        }
12659
12660        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12661    }
12662
12663    class PackageRemovedInfo {
12664        String removedPackage;
12665        int uid = -1;
12666        int removedAppId = -1;
12667        int[] removedUsers = null;
12668        boolean isRemovedPackageSystemUpdate = false;
12669        // Clean up resources deleted packages.
12670        InstallArgs args = null;
12671
12672        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12673            Bundle extras = new Bundle(1);
12674            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12675            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12676            if (replacing) {
12677                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12678            }
12679            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12680            if (removedPackage != null) {
12681                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12682                        extras, null, null, removedUsers);
12683                if (fullRemove && !replacing) {
12684                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12685                            extras, null, null, removedUsers);
12686                }
12687            }
12688            if (removedAppId >= 0) {
12689                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12690                        removedUsers);
12691            }
12692        }
12693    }
12694
12695    /*
12696     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12697     * flag is not set, the data directory is removed as well.
12698     * make sure this flag is set for partially installed apps. If not its meaningless to
12699     * delete a partially installed application.
12700     */
12701    private void removePackageDataLI(PackageSetting ps,
12702            int[] allUserHandles, boolean[] perUserInstalled,
12703            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12704        String packageName = ps.name;
12705        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12706        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12707        // Retrieve object to delete permissions for shared user later on
12708        final PackageSetting deletedPs;
12709        // reader
12710        synchronized (mPackages) {
12711            deletedPs = mSettings.mPackages.get(packageName);
12712            if (outInfo != null) {
12713                outInfo.removedPackage = packageName;
12714                outInfo.removedUsers = deletedPs != null
12715                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12716                        : null;
12717            }
12718        }
12719        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12720            removeDataDirsLI(ps.volumeUuid, packageName);
12721            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12722        }
12723        // writer
12724        synchronized (mPackages) {
12725            if (deletedPs != null) {
12726                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12727                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12728                    clearDefaultBrowserIfNeeded(packageName);
12729                    if (outInfo != null) {
12730                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12731                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12732                    }
12733                    updatePermissionsLPw(deletedPs.name, null, 0);
12734                    if (deletedPs.sharedUser != null) {
12735                        // Remove permissions associated with package. Since runtime
12736                        // permissions are per user we have to kill the removed package
12737                        // or packages running under the shared user of the removed
12738                        // package if revoking the permissions requested only by the removed
12739                        // package is successful and this causes a change in gids.
12740                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12741                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12742                                    userId);
12743                            if (userIdToKill == UserHandle.USER_ALL
12744                                    || userIdToKill >= UserHandle.USER_OWNER) {
12745                                // If gids changed for this user, kill all affected packages.
12746                                mHandler.post(new Runnable() {
12747                                    @Override
12748                                    public void run() {
12749                                        // This has to happen with no lock held.
12750                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12751                                                KILL_APP_REASON_GIDS_CHANGED);
12752                                    }
12753                                });
12754                                break;
12755                            }
12756                        }
12757                    }
12758                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12759                }
12760                // make sure to preserve per-user disabled state if this removal was just
12761                // a downgrade of a system app to the factory package
12762                if (allUserHandles != null && perUserInstalled != null) {
12763                    if (DEBUG_REMOVE) {
12764                        Slog.d(TAG, "Propagating install state across downgrade");
12765                    }
12766                    for (int i = 0; i < allUserHandles.length; i++) {
12767                        if (DEBUG_REMOVE) {
12768                            Slog.d(TAG, "    user " + allUserHandles[i]
12769                                    + " => " + perUserInstalled[i]);
12770                        }
12771                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12772                    }
12773                }
12774            }
12775            // can downgrade to reader
12776            if (writeSettings) {
12777                // Save settings now
12778                mSettings.writeLPr();
12779            }
12780        }
12781        if (outInfo != null) {
12782            // A user ID was deleted here. Go through all users and remove it
12783            // from KeyStore.
12784            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12785        }
12786    }
12787
12788    static boolean locationIsPrivileged(File path) {
12789        try {
12790            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12791                    .getCanonicalPath();
12792            return path.getCanonicalPath().startsWith(privilegedAppDir);
12793        } catch (IOException e) {
12794            Slog.e(TAG, "Unable to access code path " + path);
12795        }
12796        return false;
12797    }
12798
12799    /*
12800     * Tries to delete system package.
12801     */
12802    private boolean deleteSystemPackageLI(PackageSetting newPs,
12803            int[] allUserHandles, boolean[] perUserInstalled,
12804            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12805        final boolean applyUserRestrictions
12806                = (allUserHandles != null) && (perUserInstalled != null);
12807        PackageSetting disabledPs = null;
12808        // Confirm if the system package has been updated
12809        // An updated system app can be deleted. This will also have to restore
12810        // the system pkg from system partition
12811        // reader
12812        synchronized (mPackages) {
12813            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12814        }
12815        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12816                + " disabledPs=" + disabledPs);
12817        if (disabledPs == null) {
12818            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12819            return false;
12820        } else if (DEBUG_REMOVE) {
12821            Slog.d(TAG, "Deleting system pkg from data partition");
12822        }
12823        if (DEBUG_REMOVE) {
12824            if (applyUserRestrictions) {
12825                Slog.d(TAG, "Remembering install states:");
12826                for (int i = 0; i < allUserHandles.length; i++) {
12827                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12828                }
12829            }
12830        }
12831        // Delete the updated package
12832        outInfo.isRemovedPackageSystemUpdate = true;
12833        if (disabledPs.versionCode < newPs.versionCode) {
12834            // Delete data for downgrades
12835            flags &= ~PackageManager.DELETE_KEEP_DATA;
12836        } else {
12837            // Preserve data by setting flag
12838            flags |= PackageManager.DELETE_KEEP_DATA;
12839        }
12840        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12841                allUserHandles, perUserInstalled, outInfo, writeSettings);
12842        if (!ret) {
12843            return false;
12844        }
12845        // writer
12846        synchronized (mPackages) {
12847            // Reinstate the old system package
12848            mSettings.enableSystemPackageLPw(newPs.name);
12849            // Remove any native libraries from the upgraded package.
12850            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12851        }
12852        // Install the system package
12853        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12854        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12855        if (locationIsPrivileged(disabledPs.codePath)) {
12856            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12857        }
12858
12859        final PackageParser.Package newPkg;
12860        try {
12861            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12862        } catch (PackageManagerException e) {
12863            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12864            return false;
12865        }
12866
12867        // writer
12868        synchronized (mPackages) {
12869            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12870
12871            // Propagate the permissions state as we do want to drop on the floor
12872            // runtime permissions. The update permissions method below will take
12873            // care of removing obsolete permissions and grant install permissions.
12874            ps.getPermissionsState().copyFrom(disabledPs.getPermissionsState());
12875            updatePermissionsLPw(newPkg.packageName, newPkg,
12876                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12877
12878            if (applyUserRestrictions) {
12879                if (DEBUG_REMOVE) {
12880                    Slog.d(TAG, "Propagating install state across reinstall");
12881                }
12882                for (int i = 0; i < allUserHandles.length; i++) {
12883                    if (DEBUG_REMOVE) {
12884                        Slog.d(TAG, "    user " + allUserHandles[i]
12885                                + " => " + perUserInstalled[i]);
12886                    }
12887                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12888                }
12889                // Regardless of writeSettings we need to ensure that this restriction
12890                // state propagation is persisted
12891                mSettings.writeAllUsersPackageRestrictionsLPr();
12892            }
12893            // can downgrade to reader here
12894            if (writeSettings) {
12895                mSettings.writeLPr();
12896            }
12897        }
12898        return true;
12899    }
12900
12901    private boolean deleteInstalledPackageLI(PackageSetting ps,
12902            boolean deleteCodeAndResources, int flags,
12903            int[] allUserHandles, boolean[] perUserInstalled,
12904            PackageRemovedInfo outInfo, boolean writeSettings) {
12905        if (outInfo != null) {
12906            outInfo.uid = ps.appId;
12907        }
12908
12909        // Delete package data from internal structures and also remove data if flag is set
12910        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12911
12912        // Delete application code and resources
12913        if (deleteCodeAndResources && (outInfo != null)) {
12914            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12915                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12916            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12917        }
12918        return true;
12919    }
12920
12921    @Override
12922    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12923            int userId) {
12924        mContext.enforceCallingOrSelfPermission(
12925                android.Manifest.permission.DELETE_PACKAGES, null);
12926        synchronized (mPackages) {
12927            PackageSetting ps = mSettings.mPackages.get(packageName);
12928            if (ps == null) {
12929                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12930                return false;
12931            }
12932            if (!ps.getInstalled(userId)) {
12933                // Can't block uninstall for an app that is not installed or enabled.
12934                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12935                return false;
12936            }
12937            ps.setBlockUninstall(blockUninstall, userId);
12938            mSettings.writePackageRestrictionsLPr(userId);
12939        }
12940        return true;
12941    }
12942
12943    @Override
12944    public boolean getBlockUninstallForUser(String packageName, int userId) {
12945        synchronized (mPackages) {
12946            PackageSetting ps = mSettings.mPackages.get(packageName);
12947            if (ps == null) {
12948                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
12949                return false;
12950            }
12951            return ps.getBlockUninstall(userId);
12952        }
12953    }
12954
12955    /*
12956     * This method handles package deletion in general
12957     */
12958    private boolean deletePackageLI(String packageName, UserHandle user,
12959            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
12960            int flags, PackageRemovedInfo outInfo,
12961            boolean writeSettings) {
12962        if (packageName == null) {
12963            Slog.w(TAG, "Attempt to delete null packageName.");
12964            return false;
12965        }
12966        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
12967        PackageSetting ps;
12968        boolean dataOnly = false;
12969        int removeUser = -1;
12970        int appId = -1;
12971        synchronized (mPackages) {
12972            ps = mSettings.mPackages.get(packageName);
12973            if (ps == null) {
12974                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12975                return false;
12976            }
12977            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
12978                    && user.getIdentifier() != UserHandle.USER_ALL) {
12979                // The caller is asking that the package only be deleted for a single
12980                // user.  To do this, we just mark its uninstalled state and delete
12981                // its data.  If this is a system app, we only allow this to happen if
12982                // they have set the special DELETE_SYSTEM_APP which requests different
12983                // semantics than normal for uninstalling system apps.
12984                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
12985                ps.setUserState(user.getIdentifier(),
12986                        COMPONENT_ENABLED_STATE_DEFAULT,
12987                        false, //installed
12988                        true,  //stopped
12989                        true,  //notLaunched
12990                        false, //hidden
12991                        null, null, null,
12992                        false, // blockUninstall
12993                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED, 0);
12994                if (!isSystemApp(ps)) {
12995                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
12996                        // Other user still have this package installed, so all
12997                        // we need to do is clear this user's data and save that
12998                        // it is uninstalled.
12999                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13000                        removeUser = user.getIdentifier();
13001                        appId = ps.appId;
13002                        scheduleWritePackageRestrictionsLocked(removeUser);
13003                    } else {
13004                        // We need to set it back to 'installed' so the uninstall
13005                        // broadcasts will be sent correctly.
13006                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13007                        ps.setInstalled(true, user.getIdentifier());
13008                    }
13009                } else {
13010                    // This is a system app, so we assume that the
13011                    // other users still have this package installed, so all
13012                    // we need to do is clear this user's data and save that
13013                    // it is uninstalled.
13014                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13015                    removeUser = user.getIdentifier();
13016                    appId = ps.appId;
13017                    scheduleWritePackageRestrictionsLocked(removeUser);
13018                }
13019            }
13020        }
13021
13022        if (removeUser >= 0) {
13023            // From above, we determined that we are deleting this only
13024            // for a single user.  Continue the work here.
13025            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13026            if (outInfo != null) {
13027                outInfo.removedPackage = packageName;
13028                outInfo.removedAppId = appId;
13029                outInfo.removedUsers = new int[] {removeUser};
13030            }
13031            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13032            removeKeystoreDataIfNeeded(removeUser, appId);
13033            schedulePackageCleaning(packageName, removeUser, false);
13034            synchronized (mPackages) {
13035                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13036                    scheduleWritePackageRestrictionsLocked(removeUser);
13037                }
13038                resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, removeUser);
13039            }
13040            return true;
13041        }
13042
13043        if (dataOnly) {
13044            // Delete application data first
13045            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13046            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13047            return true;
13048        }
13049
13050        boolean ret = false;
13051        if (isSystemApp(ps)) {
13052            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13053            // When an updated system application is deleted we delete the existing resources as well and
13054            // fall back to existing code in system partition
13055            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13056                    flags, outInfo, writeSettings);
13057        } else {
13058            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13059            // Kill application pre-emptively especially for apps on sd.
13060            killApplication(packageName, ps.appId, "uninstall pkg");
13061            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13062                    allUserHandles, perUserInstalled,
13063                    outInfo, writeSettings);
13064        }
13065
13066        return ret;
13067    }
13068
13069    private final class ClearStorageConnection implements ServiceConnection {
13070        IMediaContainerService mContainerService;
13071
13072        @Override
13073        public void onServiceConnected(ComponentName name, IBinder service) {
13074            synchronized (this) {
13075                mContainerService = IMediaContainerService.Stub.asInterface(service);
13076                notifyAll();
13077            }
13078        }
13079
13080        @Override
13081        public void onServiceDisconnected(ComponentName name) {
13082        }
13083    }
13084
13085    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13086        final boolean mounted;
13087        if (Environment.isExternalStorageEmulated()) {
13088            mounted = true;
13089        } else {
13090            final String status = Environment.getExternalStorageState();
13091
13092            mounted = status.equals(Environment.MEDIA_MOUNTED)
13093                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13094        }
13095
13096        if (!mounted) {
13097            return;
13098        }
13099
13100        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13101        int[] users;
13102        if (userId == UserHandle.USER_ALL) {
13103            users = sUserManager.getUserIds();
13104        } else {
13105            users = new int[] { userId };
13106        }
13107        final ClearStorageConnection conn = new ClearStorageConnection();
13108        if (mContext.bindServiceAsUser(
13109                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
13110            try {
13111                for (int curUser : users) {
13112                    long timeout = SystemClock.uptimeMillis() + 5000;
13113                    synchronized (conn) {
13114                        long now = SystemClock.uptimeMillis();
13115                        while (conn.mContainerService == null && now < timeout) {
13116                            try {
13117                                conn.wait(timeout - now);
13118                            } catch (InterruptedException e) {
13119                            }
13120                        }
13121                    }
13122                    if (conn.mContainerService == null) {
13123                        return;
13124                    }
13125
13126                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13127                    clearDirectory(conn.mContainerService,
13128                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13129                    if (allData) {
13130                        clearDirectory(conn.mContainerService,
13131                                userEnv.buildExternalStorageAppDataDirs(packageName));
13132                        clearDirectory(conn.mContainerService,
13133                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13134                    }
13135                }
13136            } finally {
13137                mContext.unbindService(conn);
13138            }
13139        }
13140    }
13141
13142    @Override
13143    public void clearApplicationUserData(final String packageName,
13144            final IPackageDataObserver observer, final int userId) {
13145        mContext.enforceCallingOrSelfPermission(
13146                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13147        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13148        // Queue up an async operation since the package deletion may take a little while.
13149        mHandler.post(new Runnable() {
13150            public void run() {
13151                mHandler.removeCallbacks(this);
13152                final boolean succeeded;
13153                synchronized (mInstallLock) {
13154                    succeeded = clearApplicationUserDataLI(packageName, userId);
13155                }
13156                clearExternalStorageDataSync(packageName, userId, true);
13157                if (succeeded) {
13158                    // invoke DeviceStorageMonitor's update method to clear any notifications
13159                    DeviceStorageMonitorInternal
13160                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13161                    if (dsm != null) {
13162                        dsm.checkMemory();
13163                    }
13164                }
13165                if(observer != null) {
13166                    try {
13167                        observer.onRemoveCompleted(packageName, succeeded);
13168                    } catch (RemoteException e) {
13169                        Log.i(TAG, "Observer no longer exists.");
13170                    }
13171                } //end if observer
13172            } //end run
13173        });
13174    }
13175
13176    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13177        if (packageName == null) {
13178            Slog.w(TAG, "Attempt to delete null packageName.");
13179            return false;
13180        }
13181
13182        // Try finding details about the requested package
13183        PackageParser.Package pkg;
13184        synchronized (mPackages) {
13185            pkg = mPackages.get(packageName);
13186            if (pkg == null) {
13187                final PackageSetting ps = mSettings.mPackages.get(packageName);
13188                if (ps != null) {
13189                    pkg = ps.pkg;
13190                }
13191            }
13192
13193            if (pkg == null) {
13194                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13195                return false;
13196            }
13197
13198            PackageSetting ps = (PackageSetting) pkg.mExtras;
13199            resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, userId);
13200        }
13201
13202        // Always delete data directories for package, even if we found no other
13203        // record of app. This helps users recover from UID mismatches without
13204        // resorting to a full data wipe.
13205        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13206        if (retCode < 0) {
13207            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13208            return false;
13209        }
13210
13211        final int appId = pkg.applicationInfo.uid;
13212        removeKeystoreDataIfNeeded(userId, appId);
13213
13214        // Create a native library symlink only if we have native libraries
13215        // and if the native libraries are 32 bit libraries. We do not provide
13216        // this symlink for 64 bit libraries.
13217        if (pkg.applicationInfo.primaryCpuAbi != null &&
13218                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13219            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13220            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13221                    nativeLibPath, userId) < 0) {
13222                Slog.w(TAG, "Failed linking native library dir");
13223                return false;
13224            }
13225        }
13226
13227        return true;
13228    }
13229
13230    /**
13231     * Reverts user permission state changes (permissions and flags).
13232     *
13233     * @param ps The package for which to reset.
13234     * @param userId The device user for which to do a reset.
13235     */
13236    private void resetUserChangesToRuntimePermissionsAndFlagsLocked(
13237            final PackageSetting ps, final int userId) {
13238        if (ps.pkg == null) {
13239            return;
13240        }
13241
13242        final int userSettableFlags = FLAG_PERMISSION_USER_SET
13243                | FLAG_PERMISSION_USER_FIXED
13244                | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13245
13246        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13247                | FLAG_PERMISSION_POLICY_FIXED;
13248
13249        boolean writeInstallPermissions = false;
13250        boolean writeRuntimePermissions = false;
13251
13252        final int permissionCount = ps.pkg.requestedPermissions.size();
13253        for (int i = 0; i < permissionCount; i++) {
13254            String permission = ps.pkg.requestedPermissions.get(i);
13255
13256            BasePermission bp = mSettings.mPermissions.get(permission);
13257            if (bp == null) {
13258                continue;
13259            }
13260
13261            // If shared user we just reset the state to which only this app contributed.
13262            if (ps.sharedUser != null) {
13263                boolean used = false;
13264                final int packageCount = ps.sharedUser.packages.size();
13265                for (int j = 0; j < packageCount; j++) {
13266                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13267                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13268                            && pkg.pkg.requestedPermissions.contains(permission)) {
13269                        used = true;
13270                        break;
13271                    }
13272                }
13273                if (used) {
13274                    continue;
13275                }
13276            }
13277
13278            PermissionsState permissionsState = ps.getPermissionsState();
13279
13280            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13281
13282            // Always clear the user settable flags.
13283            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13284                    bp.name) != null;
13285            if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13286                if (hasInstallState) {
13287                    writeInstallPermissions = true;
13288                } else {
13289                    writeRuntimePermissions = true;
13290                }
13291            }
13292
13293            // Below is only runtime permission handling.
13294            if (!bp.isRuntime()) {
13295                continue;
13296            }
13297
13298            // Never clobber system or policy.
13299            if ((oldFlags & policyOrSystemFlags) != 0) {
13300                continue;
13301            }
13302
13303            // If this permission was granted by default, make sure it is.
13304            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13305                if (permissionsState.grantRuntimePermission(bp, userId)
13306                        != PERMISSION_OPERATION_FAILURE) {
13307                    writeRuntimePermissions = true;
13308                }
13309            } else {
13310                // Otherwise, reset the permission.
13311                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13312                switch (revokeResult) {
13313                    case PERMISSION_OPERATION_SUCCESS: {
13314                        writeRuntimePermissions = true;
13315                    } break;
13316
13317                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13318                        writeRuntimePermissions = true;
13319                        // If gids changed for this user, kill all affected packages.
13320                        mHandler.post(new Runnable() {
13321                            @Override
13322                            public void run() {
13323                                // This has to happen with no lock held.
13324                                killSettingPackagesForUser(ps, userId,
13325                                        KILL_APP_REASON_GIDS_CHANGED);
13326                            }
13327                        });
13328                    } break;
13329                }
13330            }
13331        }
13332
13333        // Synchronously write as we are taking permissions away.
13334        if (writeRuntimePermissions) {
13335            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13336        }
13337
13338        // Synchronously write as we are taking permissions away.
13339        if (writeInstallPermissions) {
13340            mSettings.writeLPr();
13341        }
13342    }
13343
13344    /**
13345     * Remove entries from the keystore daemon. Will only remove it if the
13346     * {@code appId} is valid.
13347     */
13348    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13349        if (appId < 0) {
13350            return;
13351        }
13352
13353        final KeyStore keyStore = KeyStore.getInstance();
13354        if (keyStore != null) {
13355            if (userId == UserHandle.USER_ALL) {
13356                for (final int individual : sUserManager.getUserIds()) {
13357                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13358                }
13359            } else {
13360                keyStore.clearUid(UserHandle.getUid(userId, appId));
13361            }
13362        } else {
13363            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13364        }
13365    }
13366
13367    @Override
13368    public void deleteApplicationCacheFiles(final String packageName,
13369            final IPackageDataObserver observer) {
13370        mContext.enforceCallingOrSelfPermission(
13371                android.Manifest.permission.DELETE_CACHE_FILES, null);
13372        // Queue up an async operation since the package deletion may take a little while.
13373        final int userId = UserHandle.getCallingUserId();
13374        mHandler.post(new Runnable() {
13375            public void run() {
13376                mHandler.removeCallbacks(this);
13377                final boolean succeded;
13378                synchronized (mInstallLock) {
13379                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13380                }
13381                clearExternalStorageDataSync(packageName, userId, false);
13382                if (observer != null) {
13383                    try {
13384                        observer.onRemoveCompleted(packageName, succeded);
13385                    } catch (RemoteException e) {
13386                        Log.i(TAG, "Observer no longer exists.");
13387                    }
13388                } //end if observer
13389            } //end run
13390        });
13391    }
13392
13393    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13394        if (packageName == null) {
13395            Slog.w(TAG, "Attempt to delete null packageName.");
13396            return false;
13397        }
13398        PackageParser.Package p;
13399        synchronized (mPackages) {
13400            p = mPackages.get(packageName);
13401        }
13402        if (p == null) {
13403            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13404            return false;
13405        }
13406        final ApplicationInfo applicationInfo = p.applicationInfo;
13407        if (applicationInfo == null) {
13408            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13409            return false;
13410        }
13411        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13412        if (retCode < 0) {
13413            Slog.w(TAG, "Couldn't remove cache files for package: "
13414                       + packageName + " u" + userId);
13415            return false;
13416        }
13417        return true;
13418    }
13419
13420    @Override
13421    public void getPackageSizeInfo(final String packageName, int userHandle,
13422            final IPackageStatsObserver observer) {
13423        mContext.enforceCallingOrSelfPermission(
13424                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13425        if (packageName == null) {
13426            throw new IllegalArgumentException("Attempt to get size of null packageName");
13427        }
13428
13429        PackageStats stats = new PackageStats(packageName, userHandle);
13430
13431        /*
13432         * Queue up an async operation since the package measurement may take a
13433         * little while.
13434         */
13435        Message msg = mHandler.obtainMessage(INIT_COPY);
13436        msg.obj = new MeasureParams(stats, observer);
13437        mHandler.sendMessage(msg);
13438    }
13439
13440    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13441            PackageStats pStats) {
13442        if (packageName == null) {
13443            Slog.w(TAG, "Attempt to get size of null packageName.");
13444            return false;
13445        }
13446        PackageParser.Package p;
13447        boolean dataOnly = false;
13448        String libDirRoot = null;
13449        String asecPath = null;
13450        PackageSetting ps = null;
13451        synchronized (mPackages) {
13452            p = mPackages.get(packageName);
13453            ps = mSettings.mPackages.get(packageName);
13454            if(p == null) {
13455                dataOnly = true;
13456                if((ps == null) || (ps.pkg == null)) {
13457                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13458                    return false;
13459                }
13460                p = ps.pkg;
13461            }
13462            if (ps != null) {
13463                libDirRoot = ps.legacyNativeLibraryPathString;
13464            }
13465            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13466                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13467                if (secureContainerId != null) {
13468                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13469                }
13470            }
13471        }
13472        String publicSrcDir = null;
13473        if(!dataOnly) {
13474            final ApplicationInfo applicationInfo = p.applicationInfo;
13475            if (applicationInfo == null) {
13476                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13477                return false;
13478            }
13479            if (p.isForwardLocked()) {
13480                publicSrcDir = applicationInfo.getBaseResourcePath();
13481            }
13482        }
13483        // TODO: extend to measure size of split APKs
13484        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13485        // not just the first level.
13486        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13487        // just the primary.
13488        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13489        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13490                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13491        if (res < 0) {
13492            return false;
13493        }
13494
13495        // Fix-up for forward-locked applications in ASEC containers.
13496        if (!isExternal(p)) {
13497            pStats.codeSize += pStats.externalCodeSize;
13498            pStats.externalCodeSize = 0L;
13499        }
13500
13501        return true;
13502    }
13503
13504
13505    @Override
13506    public void addPackageToPreferred(String packageName) {
13507        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13508    }
13509
13510    @Override
13511    public void removePackageFromPreferred(String packageName) {
13512        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13513    }
13514
13515    @Override
13516    public List<PackageInfo> getPreferredPackages(int flags) {
13517        return new ArrayList<PackageInfo>();
13518    }
13519
13520    private int getUidTargetSdkVersionLockedLPr(int uid) {
13521        Object obj = mSettings.getUserIdLPr(uid);
13522        if (obj instanceof SharedUserSetting) {
13523            final SharedUserSetting sus = (SharedUserSetting) obj;
13524            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13525            final Iterator<PackageSetting> it = sus.packages.iterator();
13526            while (it.hasNext()) {
13527                final PackageSetting ps = it.next();
13528                if (ps.pkg != null) {
13529                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13530                    if (v < vers) vers = v;
13531                }
13532            }
13533            return vers;
13534        } else if (obj instanceof PackageSetting) {
13535            final PackageSetting ps = (PackageSetting) obj;
13536            if (ps.pkg != null) {
13537                return ps.pkg.applicationInfo.targetSdkVersion;
13538            }
13539        }
13540        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13541    }
13542
13543    @Override
13544    public void addPreferredActivity(IntentFilter filter, int match,
13545            ComponentName[] set, ComponentName activity, int userId) {
13546        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13547                "Adding preferred");
13548    }
13549
13550    private void addPreferredActivityInternal(IntentFilter filter, int match,
13551            ComponentName[] set, ComponentName activity, boolean always, int userId,
13552            String opname) {
13553        // writer
13554        int callingUid = Binder.getCallingUid();
13555        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13556        if (filter.countActions() == 0) {
13557            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13558            return;
13559        }
13560        synchronized (mPackages) {
13561            if (mContext.checkCallingOrSelfPermission(
13562                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13563                    != PackageManager.PERMISSION_GRANTED) {
13564                if (getUidTargetSdkVersionLockedLPr(callingUid)
13565                        < Build.VERSION_CODES.FROYO) {
13566                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13567                            + callingUid);
13568                    return;
13569                }
13570                mContext.enforceCallingOrSelfPermission(
13571                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13572            }
13573
13574            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13575            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13576                    + userId + ":");
13577            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13578            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13579            scheduleWritePackageRestrictionsLocked(userId);
13580        }
13581    }
13582
13583    @Override
13584    public void replacePreferredActivity(IntentFilter filter, int match,
13585            ComponentName[] set, ComponentName activity, int userId) {
13586        if (filter.countActions() != 1) {
13587            throw new IllegalArgumentException(
13588                    "replacePreferredActivity expects filter to have only 1 action.");
13589        }
13590        if (filter.countDataAuthorities() != 0
13591                || filter.countDataPaths() != 0
13592                || filter.countDataSchemes() > 1
13593                || filter.countDataTypes() != 0) {
13594            throw new IllegalArgumentException(
13595                    "replacePreferredActivity expects filter to have no data authorities, " +
13596                    "paths, or types; and at most one scheme.");
13597        }
13598
13599        final int callingUid = Binder.getCallingUid();
13600        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13601        synchronized (mPackages) {
13602            if (mContext.checkCallingOrSelfPermission(
13603                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13604                    != PackageManager.PERMISSION_GRANTED) {
13605                if (getUidTargetSdkVersionLockedLPr(callingUid)
13606                        < Build.VERSION_CODES.FROYO) {
13607                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13608                            + Binder.getCallingUid());
13609                    return;
13610                }
13611                mContext.enforceCallingOrSelfPermission(
13612                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13613            }
13614
13615            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13616            if (pir != null) {
13617                // Get all of the existing entries that exactly match this filter.
13618                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13619                if (existing != null && existing.size() == 1) {
13620                    PreferredActivity cur = existing.get(0);
13621                    if (DEBUG_PREFERRED) {
13622                        Slog.i(TAG, "Checking replace of preferred:");
13623                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13624                        if (!cur.mPref.mAlways) {
13625                            Slog.i(TAG, "  -- CUR; not mAlways!");
13626                        } else {
13627                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13628                            Slog.i(TAG, "  -- CUR: mSet="
13629                                    + Arrays.toString(cur.mPref.mSetComponents));
13630                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13631                            Slog.i(TAG, "  -- NEW: mMatch="
13632                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13633                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13634                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13635                        }
13636                    }
13637                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13638                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13639                            && cur.mPref.sameSet(set)) {
13640                        // Setting the preferred activity to what it happens to be already
13641                        if (DEBUG_PREFERRED) {
13642                            Slog.i(TAG, "Replacing with same preferred activity "
13643                                    + cur.mPref.mShortComponent + " for user "
13644                                    + userId + ":");
13645                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13646                        }
13647                        return;
13648                    }
13649                }
13650
13651                if (existing != null) {
13652                    if (DEBUG_PREFERRED) {
13653                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13654                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13655                    }
13656                    for (int i = 0; i < existing.size(); i++) {
13657                        PreferredActivity pa = existing.get(i);
13658                        if (DEBUG_PREFERRED) {
13659                            Slog.i(TAG, "Removing existing preferred activity "
13660                                    + pa.mPref.mComponent + ":");
13661                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13662                        }
13663                        pir.removeFilter(pa);
13664                    }
13665                }
13666            }
13667            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13668                    "Replacing preferred");
13669        }
13670    }
13671
13672    @Override
13673    public void clearPackagePreferredActivities(String packageName) {
13674        final int uid = Binder.getCallingUid();
13675        // writer
13676        synchronized (mPackages) {
13677            PackageParser.Package pkg = mPackages.get(packageName);
13678            if (pkg == null || pkg.applicationInfo.uid != uid) {
13679                if (mContext.checkCallingOrSelfPermission(
13680                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13681                        != PackageManager.PERMISSION_GRANTED) {
13682                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13683                            < Build.VERSION_CODES.FROYO) {
13684                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13685                                + Binder.getCallingUid());
13686                        return;
13687                    }
13688                    mContext.enforceCallingOrSelfPermission(
13689                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13690                }
13691            }
13692
13693            int user = UserHandle.getCallingUserId();
13694            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13695                scheduleWritePackageRestrictionsLocked(user);
13696            }
13697        }
13698    }
13699
13700    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13701    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13702        ArrayList<PreferredActivity> removed = null;
13703        boolean changed = false;
13704        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13705            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13706            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13707            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13708                continue;
13709            }
13710            Iterator<PreferredActivity> it = pir.filterIterator();
13711            while (it.hasNext()) {
13712                PreferredActivity pa = it.next();
13713                // Mark entry for removal only if it matches the package name
13714                // and the entry is of type "always".
13715                if (packageName == null ||
13716                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13717                                && pa.mPref.mAlways)) {
13718                    if (removed == null) {
13719                        removed = new ArrayList<PreferredActivity>();
13720                    }
13721                    removed.add(pa);
13722                }
13723            }
13724            if (removed != null) {
13725                for (int j=0; j<removed.size(); j++) {
13726                    PreferredActivity pa = removed.get(j);
13727                    pir.removeFilter(pa);
13728                }
13729                changed = true;
13730            }
13731        }
13732        return changed;
13733    }
13734
13735    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13736    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13737        if (userId == UserHandle.USER_ALL) {
13738            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13739                    sUserManager.getUserIds())) {
13740                for (int oneUserId : sUserManager.getUserIds()) {
13741                    scheduleWritePackageRestrictionsLocked(oneUserId);
13742                }
13743            }
13744        } else {
13745            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13746                scheduleWritePackageRestrictionsLocked(userId);
13747            }
13748        }
13749    }
13750
13751
13752    void clearDefaultBrowserIfNeeded(String packageName) {
13753        for (int oneUserId : sUserManager.getUserIds()) {
13754            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13755            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13756            if (packageName.equals(defaultBrowserPackageName)) {
13757                setDefaultBrowserPackageName(null, oneUserId);
13758            }
13759        }
13760    }
13761
13762    @Override
13763    public void resetPreferredActivities(int userId) {
13764        mContext.enforceCallingOrSelfPermission(
13765                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13766        // writer
13767        synchronized (mPackages) {
13768            clearPackagePreferredActivitiesLPw(null, userId);
13769            mSettings.applyDefaultPreferredAppsLPw(this, userId);
13770            applyFactoryDefaultBrowserLPw(userId);
13771            primeDomainVerificationsLPw(userId);
13772
13773            scheduleWritePackageRestrictionsLocked(userId);
13774        }
13775    }
13776
13777    @Override
13778    public int getPreferredActivities(List<IntentFilter> outFilters,
13779            List<ComponentName> outActivities, String packageName) {
13780
13781        int num = 0;
13782        final int userId = UserHandle.getCallingUserId();
13783        // reader
13784        synchronized (mPackages) {
13785            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13786            if (pir != null) {
13787                final Iterator<PreferredActivity> it = pir.filterIterator();
13788                while (it.hasNext()) {
13789                    final PreferredActivity pa = it.next();
13790                    if (packageName == null
13791                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13792                                    && pa.mPref.mAlways)) {
13793                        if (outFilters != null) {
13794                            outFilters.add(new IntentFilter(pa));
13795                        }
13796                        if (outActivities != null) {
13797                            outActivities.add(pa.mPref.mComponent);
13798                        }
13799                    }
13800                }
13801            }
13802        }
13803
13804        return num;
13805    }
13806
13807    @Override
13808    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13809            int userId) {
13810        int callingUid = Binder.getCallingUid();
13811        if (callingUid != Process.SYSTEM_UID) {
13812            throw new SecurityException(
13813                    "addPersistentPreferredActivity can only be run by the system");
13814        }
13815        if (filter.countActions() == 0) {
13816            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13817            return;
13818        }
13819        synchronized (mPackages) {
13820            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13821                    " :");
13822            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13823            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13824                    new PersistentPreferredActivity(filter, activity));
13825            scheduleWritePackageRestrictionsLocked(userId);
13826        }
13827    }
13828
13829    @Override
13830    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13831        int callingUid = Binder.getCallingUid();
13832        if (callingUid != Process.SYSTEM_UID) {
13833            throw new SecurityException(
13834                    "clearPackagePersistentPreferredActivities can only be run by the system");
13835        }
13836        ArrayList<PersistentPreferredActivity> removed = null;
13837        boolean changed = false;
13838        synchronized (mPackages) {
13839            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13840                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13841                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13842                        .valueAt(i);
13843                if (userId != thisUserId) {
13844                    continue;
13845                }
13846                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13847                while (it.hasNext()) {
13848                    PersistentPreferredActivity ppa = it.next();
13849                    // Mark entry for removal only if it matches the package name.
13850                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13851                        if (removed == null) {
13852                            removed = new ArrayList<PersistentPreferredActivity>();
13853                        }
13854                        removed.add(ppa);
13855                    }
13856                }
13857                if (removed != null) {
13858                    for (int j=0; j<removed.size(); j++) {
13859                        PersistentPreferredActivity ppa = removed.get(j);
13860                        ppir.removeFilter(ppa);
13861                    }
13862                    changed = true;
13863                }
13864            }
13865
13866            if (changed) {
13867                scheduleWritePackageRestrictionsLocked(userId);
13868            }
13869        }
13870    }
13871
13872    /**
13873     * Common machinery for picking apart a restored XML blob and passing
13874     * it to a caller-supplied functor to be applied to the running system.
13875     */
13876    private void restoreFromXml(XmlPullParser parser, int userId,
13877            String expectedStartTag, BlobXmlRestorer functor)
13878            throws IOException, XmlPullParserException {
13879        int type;
13880        while ((type = parser.next()) != XmlPullParser.START_TAG
13881                && type != XmlPullParser.END_DOCUMENT) {
13882        }
13883        if (type != XmlPullParser.START_TAG) {
13884            // oops didn't find a start tag?!
13885            if (DEBUG_BACKUP) {
13886                Slog.e(TAG, "Didn't find start tag during restore");
13887            }
13888            return;
13889        }
13890
13891        // this is supposed to be TAG_PREFERRED_BACKUP
13892        if (!expectedStartTag.equals(parser.getName())) {
13893            if (DEBUG_BACKUP) {
13894                Slog.e(TAG, "Found unexpected tag " + parser.getName());
13895            }
13896            return;
13897        }
13898
13899        // skip interfering stuff, then we're aligned with the backing implementation
13900        while ((type = parser.next()) == XmlPullParser.TEXT) { }
13901        functor.apply(parser, userId);
13902    }
13903
13904    private interface BlobXmlRestorer {
13905        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
13906    }
13907
13908    /**
13909     * Non-Binder method, support for the backup/restore mechanism: write the
13910     * full set of preferred activities in its canonical XML format.  Returns the
13911     * XML output as a byte array, or null if there is none.
13912     */
13913    @Override
13914    public byte[] getPreferredActivityBackup(int userId) {
13915        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13916            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13917        }
13918
13919        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13920        try {
13921            final XmlSerializer serializer = new FastXmlSerializer();
13922            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13923            serializer.startDocument(null, true);
13924            serializer.startTag(null, TAG_PREFERRED_BACKUP);
13925
13926            synchronized (mPackages) {
13927                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13928            }
13929
13930            serializer.endTag(null, TAG_PREFERRED_BACKUP);
13931            serializer.endDocument();
13932            serializer.flush();
13933        } catch (Exception e) {
13934            if (DEBUG_BACKUP) {
13935                Slog.e(TAG, "Unable to write preferred activities for backup", e);
13936            }
13937            return null;
13938        }
13939
13940        return dataStream.toByteArray();
13941    }
13942
13943    @Override
13944    public void restorePreferredActivities(byte[] backup, int userId) {
13945        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13946            throw new SecurityException("Only the system may call restorePreferredActivities()");
13947        }
13948
13949        try {
13950            final XmlPullParser parser = Xml.newPullParser();
13951            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13952            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
13953                    new BlobXmlRestorer() {
13954                        @Override
13955                        public void apply(XmlPullParser parser, int userId)
13956                                throws XmlPullParserException, IOException {
13957                            synchronized (mPackages) {
13958                                mSettings.readPreferredActivitiesLPw(parser, userId);
13959                            }
13960                        }
13961                    } );
13962        } catch (Exception e) {
13963            if (DEBUG_BACKUP) {
13964                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13965            }
13966        }
13967    }
13968
13969    /**
13970     * Non-Binder method, support for the backup/restore mechanism: write the
13971     * default browser (etc) settings in its canonical XML format.  Returns the default
13972     * browser XML representation as a byte array, or null if there is none.
13973     */
13974    @Override
13975    public byte[] getDefaultAppsBackup(int userId) {
13976        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13977            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
13978        }
13979
13980        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13981        try {
13982            final XmlSerializer serializer = new FastXmlSerializer();
13983            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13984            serializer.startDocument(null, true);
13985            serializer.startTag(null, TAG_DEFAULT_APPS);
13986
13987            synchronized (mPackages) {
13988                mSettings.writeDefaultAppsLPr(serializer, userId);
13989            }
13990
13991            serializer.endTag(null, TAG_DEFAULT_APPS);
13992            serializer.endDocument();
13993            serializer.flush();
13994        } catch (Exception e) {
13995            if (DEBUG_BACKUP) {
13996                Slog.e(TAG, "Unable to write default apps for backup", e);
13997            }
13998            return null;
13999        }
14000
14001        return dataStream.toByteArray();
14002    }
14003
14004    @Override
14005    public void restoreDefaultApps(byte[] backup, int userId) {
14006        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14007            throw new SecurityException("Only the system may call restoreDefaultApps()");
14008        }
14009
14010        try {
14011            final XmlPullParser parser = Xml.newPullParser();
14012            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14013            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14014                    new BlobXmlRestorer() {
14015                        @Override
14016                        public void apply(XmlPullParser parser, int userId)
14017                                throws XmlPullParserException, IOException {
14018                            synchronized (mPackages) {
14019                                mSettings.readDefaultAppsLPw(parser, userId);
14020                            }
14021                        }
14022                    } );
14023        } catch (Exception e) {
14024            if (DEBUG_BACKUP) {
14025                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14026            }
14027        }
14028    }
14029
14030    @Override
14031    public byte[] getIntentFilterVerificationBackup(int userId) {
14032        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14033            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14034        }
14035
14036        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14037        try {
14038            final XmlSerializer serializer = new FastXmlSerializer();
14039            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14040            serializer.startDocument(null, true);
14041            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14042
14043            synchronized (mPackages) {
14044                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14045            }
14046
14047            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14048            serializer.endDocument();
14049            serializer.flush();
14050        } catch (Exception e) {
14051            if (DEBUG_BACKUP) {
14052                Slog.e(TAG, "Unable to write default apps for backup", e);
14053            }
14054            return null;
14055        }
14056
14057        return dataStream.toByteArray();
14058    }
14059
14060    @Override
14061    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14062        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14063            throw new SecurityException("Only the system may call restorePreferredActivities()");
14064        }
14065
14066        try {
14067            final XmlPullParser parser = Xml.newPullParser();
14068            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14069            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14070                    new BlobXmlRestorer() {
14071                        @Override
14072                        public void apply(XmlPullParser parser, int userId)
14073                                throws XmlPullParserException, IOException {
14074                            synchronized (mPackages) {
14075                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14076                                mSettings.writeLPr();
14077                            }
14078                        }
14079                    } );
14080        } catch (Exception e) {
14081            if (DEBUG_BACKUP) {
14082                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14083            }
14084        }
14085    }
14086
14087    @Override
14088    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14089            int sourceUserId, int targetUserId, int flags) {
14090        mContext.enforceCallingOrSelfPermission(
14091                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14092        int callingUid = Binder.getCallingUid();
14093        enforceOwnerRights(ownerPackage, callingUid);
14094        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14095        if (intentFilter.countActions() == 0) {
14096            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14097            return;
14098        }
14099        synchronized (mPackages) {
14100            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14101                    ownerPackage, targetUserId, flags);
14102            CrossProfileIntentResolver resolver =
14103                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14104            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14105            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14106            if (existing != null) {
14107                int size = existing.size();
14108                for (int i = 0; i < size; i++) {
14109                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14110                        return;
14111                    }
14112                }
14113            }
14114            resolver.addFilter(newFilter);
14115            scheduleWritePackageRestrictionsLocked(sourceUserId);
14116        }
14117    }
14118
14119    @Override
14120    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14121        mContext.enforceCallingOrSelfPermission(
14122                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14123        int callingUid = Binder.getCallingUid();
14124        enforceOwnerRights(ownerPackage, callingUid);
14125        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14126        synchronized (mPackages) {
14127            CrossProfileIntentResolver resolver =
14128                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14129            ArraySet<CrossProfileIntentFilter> set =
14130                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14131            for (CrossProfileIntentFilter filter : set) {
14132                if (filter.getOwnerPackage().equals(ownerPackage)) {
14133                    resolver.removeFilter(filter);
14134                }
14135            }
14136            scheduleWritePackageRestrictionsLocked(sourceUserId);
14137        }
14138    }
14139
14140    // Enforcing that callingUid is owning pkg on userId
14141    private void enforceOwnerRights(String pkg, int callingUid) {
14142        // The system owns everything.
14143        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14144            return;
14145        }
14146        int callingUserId = UserHandle.getUserId(callingUid);
14147        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14148        if (pi == null) {
14149            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14150                    + callingUserId);
14151        }
14152        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14153            throw new SecurityException("Calling uid " + callingUid
14154                    + " does not own package " + pkg);
14155        }
14156    }
14157
14158    @Override
14159    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14160        Intent intent = new Intent(Intent.ACTION_MAIN);
14161        intent.addCategory(Intent.CATEGORY_HOME);
14162
14163        final int callingUserId = UserHandle.getCallingUserId();
14164        List<ResolveInfo> list = queryIntentActivities(intent, null,
14165                PackageManager.GET_META_DATA, callingUserId);
14166        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14167                true, false, false, callingUserId);
14168
14169        allHomeCandidates.clear();
14170        if (list != null) {
14171            for (ResolveInfo ri : list) {
14172                allHomeCandidates.add(ri);
14173            }
14174        }
14175        return (preferred == null || preferred.activityInfo == null)
14176                ? null
14177                : new ComponentName(preferred.activityInfo.packageName,
14178                        preferred.activityInfo.name);
14179    }
14180
14181    @Override
14182    public void setApplicationEnabledSetting(String appPackageName,
14183            int newState, int flags, int userId, String callingPackage) {
14184        if (!sUserManager.exists(userId)) return;
14185        if (callingPackage == null) {
14186            callingPackage = Integer.toString(Binder.getCallingUid());
14187        }
14188        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14189    }
14190
14191    @Override
14192    public void setComponentEnabledSetting(ComponentName componentName,
14193            int newState, int flags, int userId) {
14194        if (!sUserManager.exists(userId)) return;
14195        setEnabledSetting(componentName.getPackageName(),
14196                componentName.getClassName(), newState, flags, userId, null);
14197    }
14198
14199    private void setEnabledSetting(final String packageName, String className, int newState,
14200            final int flags, int userId, String callingPackage) {
14201        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14202              || newState == COMPONENT_ENABLED_STATE_ENABLED
14203              || newState == COMPONENT_ENABLED_STATE_DISABLED
14204              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14205              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14206            throw new IllegalArgumentException("Invalid new component state: "
14207                    + newState);
14208        }
14209        PackageSetting pkgSetting;
14210        final int uid = Binder.getCallingUid();
14211        final int permission = mContext.checkCallingOrSelfPermission(
14212                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14213        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14214        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14215        boolean sendNow = false;
14216        boolean isApp = (className == null);
14217        String componentName = isApp ? packageName : className;
14218        int packageUid = -1;
14219        ArrayList<String> components;
14220
14221        // writer
14222        synchronized (mPackages) {
14223            pkgSetting = mSettings.mPackages.get(packageName);
14224            if (pkgSetting == null) {
14225                if (className == null) {
14226                    throw new IllegalArgumentException(
14227                            "Unknown package: " + packageName);
14228                }
14229                throw new IllegalArgumentException(
14230                        "Unknown component: " + packageName
14231                        + "/" + className);
14232            }
14233            // Allow root and verify that userId is not being specified by a different user
14234            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14235                throw new SecurityException(
14236                        "Permission Denial: attempt to change component state from pid="
14237                        + Binder.getCallingPid()
14238                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14239            }
14240            if (className == null) {
14241                // We're dealing with an application/package level state change
14242                if (pkgSetting.getEnabled(userId) == newState) {
14243                    // Nothing to do
14244                    return;
14245                }
14246                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14247                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14248                    // Don't care about who enables an app.
14249                    callingPackage = null;
14250                }
14251                pkgSetting.setEnabled(newState, userId, callingPackage);
14252                // pkgSetting.pkg.mSetEnabled = newState;
14253            } else {
14254                // We're dealing with a component level state change
14255                // First, verify that this is a valid class name.
14256                PackageParser.Package pkg = pkgSetting.pkg;
14257                if (pkg == null || !pkg.hasComponentClassName(className)) {
14258                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14259                        throw new IllegalArgumentException("Component class " + className
14260                                + " does not exist in " + packageName);
14261                    } else {
14262                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14263                                + className + " does not exist in " + packageName);
14264                    }
14265                }
14266                switch (newState) {
14267                case COMPONENT_ENABLED_STATE_ENABLED:
14268                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14269                        return;
14270                    }
14271                    break;
14272                case COMPONENT_ENABLED_STATE_DISABLED:
14273                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14274                        return;
14275                    }
14276                    break;
14277                case COMPONENT_ENABLED_STATE_DEFAULT:
14278                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14279                        return;
14280                    }
14281                    break;
14282                default:
14283                    Slog.e(TAG, "Invalid new component state: " + newState);
14284                    return;
14285                }
14286            }
14287            scheduleWritePackageRestrictionsLocked(userId);
14288            components = mPendingBroadcasts.get(userId, packageName);
14289            final boolean newPackage = components == null;
14290            if (newPackage) {
14291                components = new ArrayList<String>();
14292            }
14293            if (!components.contains(componentName)) {
14294                components.add(componentName);
14295            }
14296            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14297                sendNow = true;
14298                // Purge entry from pending broadcast list if another one exists already
14299                // since we are sending one right away.
14300                mPendingBroadcasts.remove(userId, packageName);
14301            } else {
14302                if (newPackage) {
14303                    mPendingBroadcasts.put(userId, packageName, components);
14304                }
14305                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14306                    // Schedule a message
14307                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14308                }
14309            }
14310        }
14311
14312        long callingId = Binder.clearCallingIdentity();
14313        try {
14314            if (sendNow) {
14315                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14316                sendPackageChangedBroadcast(packageName,
14317                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14318            }
14319        } finally {
14320            Binder.restoreCallingIdentity(callingId);
14321        }
14322    }
14323
14324    private void sendPackageChangedBroadcast(String packageName,
14325            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14326        if (DEBUG_INSTALL)
14327            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14328                    + componentNames);
14329        Bundle extras = new Bundle(4);
14330        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14331        String nameList[] = new String[componentNames.size()];
14332        componentNames.toArray(nameList);
14333        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14334        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14335        extras.putInt(Intent.EXTRA_UID, packageUid);
14336        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14337                new int[] {UserHandle.getUserId(packageUid)});
14338    }
14339
14340    @Override
14341    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14342        if (!sUserManager.exists(userId)) return;
14343        final int uid = Binder.getCallingUid();
14344        final int permission = mContext.checkCallingOrSelfPermission(
14345                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14346        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14347        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14348        // writer
14349        synchronized (mPackages) {
14350            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14351                    allowedByPermission, uid, userId)) {
14352                scheduleWritePackageRestrictionsLocked(userId);
14353            }
14354        }
14355    }
14356
14357    @Override
14358    public String getInstallerPackageName(String packageName) {
14359        // reader
14360        synchronized (mPackages) {
14361            return mSettings.getInstallerPackageNameLPr(packageName);
14362        }
14363    }
14364
14365    @Override
14366    public int getApplicationEnabledSetting(String packageName, int userId) {
14367        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14368        int uid = Binder.getCallingUid();
14369        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14370        // reader
14371        synchronized (mPackages) {
14372            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14373        }
14374    }
14375
14376    @Override
14377    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14378        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14379        int uid = Binder.getCallingUid();
14380        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14381        // reader
14382        synchronized (mPackages) {
14383            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14384        }
14385    }
14386
14387    @Override
14388    public void enterSafeMode() {
14389        enforceSystemOrRoot("Only the system can request entering safe mode");
14390
14391        if (!mSystemReady) {
14392            mSafeMode = true;
14393        }
14394    }
14395
14396    @Override
14397    public void systemReady() {
14398        mSystemReady = true;
14399
14400        // Read the compatibilty setting when the system is ready.
14401        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14402                mContext.getContentResolver(),
14403                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14404        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14405        if (DEBUG_SETTINGS) {
14406            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14407        }
14408
14409        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14410
14411        synchronized (mPackages) {
14412            // Verify that all of the preferred activity components actually
14413            // exist.  It is possible for applications to be updated and at
14414            // that point remove a previously declared activity component that
14415            // had been set as a preferred activity.  We try to clean this up
14416            // the next time we encounter that preferred activity, but it is
14417            // possible for the user flow to never be able to return to that
14418            // situation so here we do a sanity check to make sure we haven't
14419            // left any junk around.
14420            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14421            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14422                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14423                removed.clear();
14424                for (PreferredActivity pa : pir.filterSet()) {
14425                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14426                        removed.add(pa);
14427                    }
14428                }
14429                if (removed.size() > 0) {
14430                    for (int r=0; r<removed.size(); r++) {
14431                        PreferredActivity pa = removed.get(r);
14432                        Slog.w(TAG, "Removing dangling preferred activity: "
14433                                + pa.mPref.mComponent);
14434                        pir.removeFilter(pa);
14435                    }
14436                    mSettings.writePackageRestrictionsLPr(
14437                            mSettings.mPreferredActivities.keyAt(i));
14438                }
14439            }
14440
14441            for (int userId : UserManagerService.getInstance().getUserIds()) {
14442                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14443                    grantPermissionsUserIds = ArrayUtils.appendInt(
14444                            grantPermissionsUserIds, userId);
14445                }
14446            }
14447        }
14448        sUserManager.systemReady();
14449
14450        // If we upgraded grant all default permissions before kicking off.
14451        for (int userId : grantPermissionsUserIds) {
14452            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14453        }
14454
14455        // Kick off any messages waiting for system ready
14456        if (mPostSystemReadyMessages != null) {
14457            for (Message msg : mPostSystemReadyMessages) {
14458                msg.sendToTarget();
14459            }
14460            mPostSystemReadyMessages = null;
14461        }
14462
14463        // Watch for external volumes that come and go over time
14464        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14465        storage.registerListener(mStorageListener);
14466
14467        mInstallerService.systemReady();
14468        mPackageDexOptimizer.systemReady();
14469    }
14470
14471    @Override
14472    public boolean isSafeMode() {
14473        return mSafeMode;
14474    }
14475
14476    @Override
14477    public boolean hasSystemUidErrors() {
14478        return mHasSystemUidErrors;
14479    }
14480
14481    static String arrayToString(int[] array) {
14482        StringBuffer buf = new StringBuffer(128);
14483        buf.append('[');
14484        if (array != null) {
14485            for (int i=0; i<array.length; i++) {
14486                if (i > 0) buf.append(", ");
14487                buf.append(array[i]);
14488            }
14489        }
14490        buf.append(']');
14491        return buf.toString();
14492    }
14493
14494    static class DumpState {
14495        public static final int DUMP_LIBS = 1 << 0;
14496        public static final int DUMP_FEATURES = 1 << 1;
14497        public static final int DUMP_RESOLVERS = 1 << 2;
14498        public static final int DUMP_PERMISSIONS = 1 << 3;
14499        public static final int DUMP_PACKAGES = 1 << 4;
14500        public static final int DUMP_SHARED_USERS = 1 << 5;
14501        public static final int DUMP_MESSAGES = 1 << 6;
14502        public static final int DUMP_PROVIDERS = 1 << 7;
14503        public static final int DUMP_VERIFIERS = 1 << 8;
14504        public static final int DUMP_PREFERRED = 1 << 9;
14505        public static final int DUMP_PREFERRED_XML = 1 << 10;
14506        public static final int DUMP_KEYSETS = 1 << 11;
14507        public static final int DUMP_VERSION = 1 << 12;
14508        public static final int DUMP_INSTALLS = 1 << 13;
14509        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14510        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14511
14512        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14513
14514        private int mTypes;
14515
14516        private int mOptions;
14517
14518        private boolean mTitlePrinted;
14519
14520        private SharedUserSetting mSharedUser;
14521
14522        public boolean isDumping(int type) {
14523            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14524                return true;
14525            }
14526
14527            return (mTypes & type) != 0;
14528        }
14529
14530        public void setDump(int type) {
14531            mTypes |= type;
14532        }
14533
14534        public boolean isOptionEnabled(int option) {
14535            return (mOptions & option) != 0;
14536        }
14537
14538        public void setOptionEnabled(int option) {
14539            mOptions |= option;
14540        }
14541
14542        public boolean onTitlePrinted() {
14543            final boolean printed = mTitlePrinted;
14544            mTitlePrinted = true;
14545            return printed;
14546        }
14547
14548        public boolean getTitlePrinted() {
14549            return mTitlePrinted;
14550        }
14551
14552        public void setTitlePrinted(boolean enabled) {
14553            mTitlePrinted = enabled;
14554        }
14555
14556        public SharedUserSetting getSharedUser() {
14557            return mSharedUser;
14558        }
14559
14560        public void setSharedUser(SharedUserSetting user) {
14561            mSharedUser = user;
14562        }
14563    }
14564
14565    @Override
14566    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14567        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14568                != PackageManager.PERMISSION_GRANTED) {
14569            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14570                    + Binder.getCallingPid()
14571                    + ", uid=" + Binder.getCallingUid()
14572                    + " without permission "
14573                    + android.Manifest.permission.DUMP);
14574            return;
14575        }
14576
14577        DumpState dumpState = new DumpState();
14578        boolean fullPreferred = false;
14579        boolean checkin = false;
14580
14581        String packageName = null;
14582        ArraySet<String> permissionNames = null;
14583
14584        int opti = 0;
14585        while (opti < args.length) {
14586            String opt = args[opti];
14587            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14588                break;
14589            }
14590            opti++;
14591
14592            if ("-a".equals(opt)) {
14593                // Right now we only know how to print all.
14594            } else if ("-h".equals(opt)) {
14595                pw.println("Package manager dump options:");
14596                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14597                pw.println("    --checkin: dump for a checkin");
14598                pw.println("    -f: print details of intent filters");
14599                pw.println("    -h: print this help");
14600                pw.println("  cmd may be one of:");
14601                pw.println("    l[ibraries]: list known shared libraries");
14602                pw.println("    f[ibraries]: list device features");
14603                pw.println("    k[eysets]: print known keysets");
14604                pw.println("    r[esolvers]: dump intent resolvers");
14605                pw.println("    perm[issions]: dump permissions");
14606                pw.println("    permission [name ...]: dump declaration and use of given permission");
14607                pw.println("    pref[erred]: print preferred package settings");
14608                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14609                pw.println("    prov[iders]: dump content providers");
14610                pw.println("    p[ackages]: dump installed packages");
14611                pw.println("    s[hared-users]: dump shared user IDs");
14612                pw.println("    m[essages]: print collected runtime messages");
14613                pw.println("    v[erifiers]: print package verifier info");
14614                pw.println("    version: print database version info");
14615                pw.println("    write: write current settings now");
14616                pw.println("    <package.name>: info about given package");
14617                pw.println("    installs: details about install sessions");
14618                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14619                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14620                return;
14621            } else if ("--checkin".equals(opt)) {
14622                checkin = true;
14623            } else if ("-f".equals(opt)) {
14624                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14625            } else {
14626                pw.println("Unknown argument: " + opt + "; use -h for help");
14627            }
14628        }
14629
14630        // Is the caller requesting to dump a particular piece of data?
14631        if (opti < args.length) {
14632            String cmd = args[opti];
14633            opti++;
14634            // Is this a package name?
14635            if ("android".equals(cmd) || cmd.contains(".")) {
14636                packageName = cmd;
14637                // When dumping a single package, we always dump all of its
14638                // filter information since the amount of data will be reasonable.
14639                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14640            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14641                dumpState.setDump(DumpState.DUMP_LIBS);
14642            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14643                dumpState.setDump(DumpState.DUMP_FEATURES);
14644            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14645                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14646            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14647                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14648            } else if ("permission".equals(cmd)) {
14649                if (opti >= args.length) {
14650                    pw.println("Error: permission requires permission name");
14651                    return;
14652                }
14653                permissionNames = new ArraySet<>();
14654                while (opti < args.length) {
14655                    permissionNames.add(args[opti]);
14656                    opti++;
14657                }
14658                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14659                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14660            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14661                dumpState.setDump(DumpState.DUMP_PREFERRED);
14662            } else if ("preferred-xml".equals(cmd)) {
14663                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14664                if (opti < args.length && "--full".equals(args[opti])) {
14665                    fullPreferred = true;
14666                    opti++;
14667                }
14668            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14669                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14670            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14671                dumpState.setDump(DumpState.DUMP_PACKAGES);
14672            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14673                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14674            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14675                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14676            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14677                dumpState.setDump(DumpState.DUMP_MESSAGES);
14678            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14679                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14680            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14681                    || "intent-filter-verifiers".equals(cmd)) {
14682                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14683            } else if ("version".equals(cmd)) {
14684                dumpState.setDump(DumpState.DUMP_VERSION);
14685            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14686                dumpState.setDump(DumpState.DUMP_KEYSETS);
14687            } else if ("installs".equals(cmd)) {
14688                dumpState.setDump(DumpState.DUMP_INSTALLS);
14689            } else if ("write".equals(cmd)) {
14690                synchronized (mPackages) {
14691                    mSettings.writeLPr();
14692                    pw.println("Settings written.");
14693                    return;
14694                }
14695            }
14696        }
14697
14698        if (checkin) {
14699            pw.println("vers,1");
14700        }
14701
14702        // reader
14703        synchronized (mPackages) {
14704            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14705                if (!checkin) {
14706                    if (dumpState.onTitlePrinted())
14707                        pw.println();
14708                    pw.println("Database versions:");
14709                    pw.print("  SDK Version:");
14710                    pw.print(" internal=");
14711                    pw.print(mSettings.mInternalSdkPlatform);
14712                    pw.print(" external=");
14713                    pw.println(mSettings.mExternalSdkPlatform);
14714                    pw.print("  DB Version:");
14715                    pw.print(" internal=");
14716                    pw.print(mSettings.mInternalDatabaseVersion);
14717                    pw.print(" external=");
14718                    pw.println(mSettings.mExternalDatabaseVersion);
14719                }
14720            }
14721
14722            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14723                if (!checkin) {
14724                    if (dumpState.onTitlePrinted())
14725                        pw.println();
14726                    pw.println("Verifiers:");
14727                    pw.print("  Required: ");
14728                    pw.print(mRequiredVerifierPackage);
14729                    pw.print(" (uid=");
14730                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14731                    pw.println(")");
14732                } else if (mRequiredVerifierPackage != null) {
14733                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14734                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14735                }
14736            }
14737
14738            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14739                    packageName == null) {
14740                if (mIntentFilterVerifierComponent != null) {
14741                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14742                    if (!checkin) {
14743                        if (dumpState.onTitlePrinted())
14744                            pw.println();
14745                        pw.println("Intent Filter Verifier:");
14746                        pw.print("  Using: ");
14747                        pw.print(verifierPackageName);
14748                        pw.print(" (uid=");
14749                        pw.print(getPackageUid(verifierPackageName, 0));
14750                        pw.println(")");
14751                    } else if (verifierPackageName != null) {
14752                        pw.print("ifv,"); pw.print(verifierPackageName);
14753                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14754                    }
14755                } else {
14756                    pw.println();
14757                    pw.println("No Intent Filter Verifier available!");
14758                }
14759            }
14760
14761            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14762                boolean printedHeader = false;
14763                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14764                while (it.hasNext()) {
14765                    String name = it.next();
14766                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14767                    if (!checkin) {
14768                        if (!printedHeader) {
14769                            if (dumpState.onTitlePrinted())
14770                                pw.println();
14771                            pw.println("Libraries:");
14772                            printedHeader = true;
14773                        }
14774                        pw.print("  ");
14775                    } else {
14776                        pw.print("lib,");
14777                    }
14778                    pw.print(name);
14779                    if (!checkin) {
14780                        pw.print(" -> ");
14781                    }
14782                    if (ent.path != null) {
14783                        if (!checkin) {
14784                            pw.print("(jar) ");
14785                            pw.print(ent.path);
14786                        } else {
14787                            pw.print(",jar,");
14788                            pw.print(ent.path);
14789                        }
14790                    } else {
14791                        if (!checkin) {
14792                            pw.print("(apk) ");
14793                            pw.print(ent.apk);
14794                        } else {
14795                            pw.print(",apk,");
14796                            pw.print(ent.apk);
14797                        }
14798                    }
14799                    pw.println();
14800                }
14801            }
14802
14803            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14804                if (dumpState.onTitlePrinted())
14805                    pw.println();
14806                if (!checkin) {
14807                    pw.println("Features:");
14808                }
14809                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14810                while (it.hasNext()) {
14811                    String name = it.next();
14812                    if (!checkin) {
14813                        pw.print("  ");
14814                    } else {
14815                        pw.print("feat,");
14816                    }
14817                    pw.println(name);
14818                }
14819            }
14820
14821            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14822                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14823                        : "Activity Resolver Table:", "  ", packageName,
14824                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14825                    dumpState.setTitlePrinted(true);
14826                }
14827                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14828                        : "Receiver Resolver Table:", "  ", packageName,
14829                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14830                    dumpState.setTitlePrinted(true);
14831                }
14832                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14833                        : "Service Resolver Table:", "  ", packageName,
14834                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14835                    dumpState.setTitlePrinted(true);
14836                }
14837                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14838                        : "Provider Resolver Table:", "  ", packageName,
14839                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14840                    dumpState.setTitlePrinted(true);
14841                }
14842            }
14843
14844            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14845                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14846                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14847                    int user = mSettings.mPreferredActivities.keyAt(i);
14848                    if (pir.dump(pw,
14849                            dumpState.getTitlePrinted()
14850                                ? "\nPreferred Activities User " + user + ":"
14851                                : "Preferred Activities User " + user + ":", "  ",
14852                            packageName, true, false)) {
14853                        dumpState.setTitlePrinted(true);
14854                    }
14855                }
14856            }
14857
14858            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14859                pw.flush();
14860                FileOutputStream fout = new FileOutputStream(fd);
14861                BufferedOutputStream str = new BufferedOutputStream(fout);
14862                XmlSerializer serializer = new FastXmlSerializer();
14863                try {
14864                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14865                    serializer.startDocument(null, true);
14866                    serializer.setFeature(
14867                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14868                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14869                    serializer.endDocument();
14870                    serializer.flush();
14871                } catch (IllegalArgumentException e) {
14872                    pw.println("Failed writing: " + e);
14873                } catch (IllegalStateException e) {
14874                    pw.println("Failed writing: " + e);
14875                } catch (IOException e) {
14876                    pw.println("Failed writing: " + e);
14877                }
14878            }
14879
14880            if (!checkin
14881                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
14882                    && packageName == null) {
14883                pw.println();
14884                int count = mSettings.mPackages.size();
14885                if (count == 0) {
14886                    pw.println("No applications!");
14887                    pw.println();
14888                } else {
14889                    final String prefix = "  ";
14890                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
14891                    if (allPackageSettings.size() == 0) {
14892                        pw.println("No domain preferred apps!");
14893                        pw.println();
14894                    } else {
14895                        pw.println("App verification status:");
14896                        pw.println();
14897                        count = 0;
14898                        for (PackageSetting ps : allPackageSettings) {
14899                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14900                            if (ivi == null || ivi.getPackageName() == null) continue;
14901                            pw.println(prefix + "Package: " + ivi.getPackageName());
14902                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
14903                            pw.println(prefix + "Status:  " + ivi.getStatusString());
14904                            pw.println();
14905                            count++;
14906                        }
14907                        if (count == 0) {
14908                            pw.println(prefix + "No app verification established.");
14909                            pw.println();
14910                        }
14911                        for (int userId : sUserManager.getUserIds()) {
14912                            pw.println("App linkages for user " + userId + ":");
14913                            pw.println();
14914                            count = 0;
14915                            for (PackageSetting ps : allPackageSettings) {
14916                                final long status = ps.getDomainVerificationStatusForUser(userId);
14917                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
14918                                    continue;
14919                                }
14920                                pw.println(prefix + "Package: " + ps.name);
14921                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
14922                                String statusStr = IntentFilterVerificationInfo.
14923                                        getStatusStringFromValue(status);
14924                                pw.println(prefix + "Status:  " + statusStr);
14925                                pw.println();
14926                                count++;
14927                            }
14928                            if (count == 0) {
14929                                pw.println(prefix + "No configured app linkages.");
14930                                pw.println();
14931                            }
14932                        }
14933                    }
14934                }
14935            }
14936
14937            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
14938                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
14939                if (packageName == null && permissionNames == null) {
14940                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
14941                        if (iperm == 0) {
14942                            if (dumpState.onTitlePrinted())
14943                                pw.println();
14944                            pw.println("AppOp Permissions:");
14945                        }
14946                        pw.print("  AppOp Permission ");
14947                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
14948                        pw.println(":");
14949                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
14950                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
14951                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
14952                        }
14953                    }
14954                }
14955            }
14956
14957            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
14958                boolean printedSomething = false;
14959                for (PackageParser.Provider p : mProviders.mProviders.values()) {
14960                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14961                        continue;
14962                    }
14963                    if (!printedSomething) {
14964                        if (dumpState.onTitlePrinted())
14965                            pw.println();
14966                        pw.println("Registered ContentProviders:");
14967                        printedSomething = true;
14968                    }
14969                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
14970                    pw.print("    "); pw.println(p.toString());
14971                }
14972                printedSomething = false;
14973                for (Map.Entry<String, PackageParser.Provider> entry :
14974                        mProvidersByAuthority.entrySet()) {
14975                    PackageParser.Provider p = entry.getValue();
14976                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14977                        continue;
14978                    }
14979                    if (!printedSomething) {
14980                        if (dumpState.onTitlePrinted())
14981                            pw.println();
14982                        pw.println("ContentProvider Authorities:");
14983                        printedSomething = true;
14984                    }
14985                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
14986                    pw.print("    "); pw.println(p.toString());
14987                    if (p.info != null && p.info.applicationInfo != null) {
14988                        final String appInfo = p.info.applicationInfo.toString();
14989                        pw.print("      applicationInfo="); pw.println(appInfo);
14990                    }
14991                }
14992            }
14993
14994            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
14995                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
14996            }
14997
14998            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
14999                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15000            }
15001
15002            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15003                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15004            }
15005
15006            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15007                // XXX should handle packageName != null by dumping only install data that
15008                // the given package is involved with.
15009                if (dumpState.onTitlePrinted()) pw.println();
15010                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15011            }
15012
15013            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15014                if (dumpState.onTitlePrinted()) pw.println();
15015                mSettings.dumpReadMessagesLPr(pw, dumpState);
15016
15017                pw.println();
15018                pw.println("Package warning messages:");
15019                BufferedReader in = null;
15020                String line = null;
15021                try {
15022                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15023                    while ((line = in.readLine()) != null) {
15024                        if (line.contains("ignored: updated version")) continue;
15025                        pw.println(line);
15026                    }
15027                } catch (IOException ignored) {
15028                } finally {
15029                    IoUtils.closeQuietly(in);
15030                }
15031            }
15032
15033            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15034                BufferedReader in = null;
15035                String line = null;
15036                try {
15037                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15038                    while ((line = in.readLine()) != null) {
15039                        if (line.contains("ignored: updated version")) continue;
15040                        pw.print("msg,");
15041                        pw.println(line);
15042                    }
15043                } catch (IOException ignored) {
15044                } finally {
15045                    IoUtils.closeQuietly(in);
15046                }
15047            }
15048        }
15049    }
15050
15051    private String dumpDomainString(String packageName) {
15052        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15053        List<IntentFilter> filters = getAllIntentFilters(packageName);
15054
15055        ArraySet<String> result = new ArraySet<>();
15056        if (iviList.size() > 0) {
15057            for (IntentFilterVerificationInfo ivi : iviList) {
15058                for (String host : ivi.getDomains()) {
15059                    result.add(host);
15060                }
15061            }
15062        }
15063        if (filters != null && filters.size() > 0) {
15064            for (IntentFilter filter : filters) {
15065                if (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15066                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)) {
15067                    result.addAll(filter.getHostsList());
15068                }
15069            }
15070        }
15071
15072        StringBuilder sb = new StringBuilder(result.size() * 16);
15073        for (String domain : result) {
15074            if (sb.length() > 0) sb.append(" ");
15075            sb.append(domain);
15076        }
15077        return sb.toString();
15078    }
15079
15080    // ------- apps on sdcard specific code -------
15081    static final boolean DEBUG_SD_INSTALL = false;
15082
15083    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15084
15085    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15086
15087    private boolean mMediaMounted = false;
15088
15089    static String getEncryptKey() {
15090        try {
15091            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15092                    SD_ENCRYPTION_KEYSTORE_NAME);
15093            if (sdEncKey == null) {
15094                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15095                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15096                if (sdEncKey == null) {
15097                    Slog.e(TAG, "Failed to create encryption keys");
15098                    return null;
15099                }
15100            }
15101            return sdEncKey;
15102        } catch (NoSuchAlgorithmException nsae) {
15103            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15104            return null;
15105        } catch (IOException ioe) {
15106            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15107            return null;
15108        }
15109    }
15110
15111    /*
15112     * Update media status on PackageManager.
15113     */
15114    @Override
15115    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15116        int callingUid = Binder.getCallingUid();
15117        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15118            throw new SecurityException("Media status can only be updated by the system");
15119        }
15120        // reader; this apparently protects mMediaMounted, but should probably
15121        // be a different lock in that case.
15122        synchronized (mPackages) {
15123            Log.i(TAG, "Updating external media status from "
15124                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15125                    + (mediaStatus ? "mounted" : "unmounted"));
15126            if (DEBUG_SD_INSTALL)
15127                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15128                        + ", mMediaMounted=" + mMediaMounted);
15129            if (mediaStatus == mMediaMounted) {
15130                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15131                        : 0, -1);
15132                mHandler.sendMessage(msg);
15133                return;
15134            }
15135            mMediaMounted = mediaStatus;
15136        }
15137        // Queue up an async operation since the package installation may take a
15138        // little while.
15139        mHandler.post(new Runnable() {
15140            public void run() {
15141                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15142            }
15143        });
15144    }
15145
15146    /**
15147     * Called by MountService when the initial ASECs to scan are available.
15148     * Should block until all the ASEC containers are finished being scanned.
15149     */
15150    public void scanAvailableAsecs() {
15151        updateExternalMediaStatusInner(true, false, false);
15152        if (mShouldRestoreconData) {
15153            SELinuxMMAC.setRestoreconDone();
15154            mShouldRestoreconData = false;
15155        }
15156    }
15157
15158    /*
15159     * Collect information of applications on external media, map them against
15160     * existing containers and update information based on current mount status.
15161     * Please note that we always have to report status if reportStatus has been
15162     * set to true especially when unloading packages.
15163     */
15164    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15165            boolean externalStorage) {
15166        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15167        int[] uidArr = EmptyArray.INT;
15168
15169        final String[] list = PackageHelper.getSecureContainerList();
15170        if (ArrayUtils.isEmpty(list)) {
15171            Log.i(TAG, "No secure containers found");
15172        } else {
15173            // Process list of secure containers and categorize them
15174            // as active or stale based on their package internal state.
15175
15176            // reader
15177            synchronized (mPackages) {
15178                for (String cid : list) {
15179                    // Leave stages untouched for now; installer service owns them
15180                    if (PackageInstallerService.isStageName(cid)) continue;
15181
15182                    if (DEBUG_SD_INSTALL)
15183                        Log.i(TAG, "Processing container " + cid);
15184                    String pkgName = getAsecPackageName(cid);
15185                    if (pkgName == null) {
15186                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15187                        continue;
15188                    }
15189                    if (DEBUG_SD_INSTALL)
15190                        Log.i(TAG, "Looking for pkg : " + pkgName);
15191
15192                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15193                    if (ps == null) {
15194                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15195                        continue;
15196                    }
15197
15198                    /*
15199                     * Skip packages that are not external if we're unmounting
15200                     * external storage.
15201                     */
15202                    if (externalStorage && !isMounted && !isExternal(ps)) {
15203                        continue;
15204                    }
15205
15206                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15207                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15208                    // The package status is changed only if the code path
15209                    // matches between settings and the container id.
15210                    if (ps.codePathString != null
15211                            && ps.codePathString.startsWith(args.getCodePath())) {
15212                        if (DEBUG_SD_INSTALL) {
15213                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15214                                    + " at code path: " + ps.codePathString);
15215                        }
15216
15217                        // We do have a valid package installed on sdcard
15218                        processCids.put(args, ps.codePathString);
15219                        final int uid = ps.appId;
15220                        if (uid != -1) {
15221                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15222                        }
15223                    } else {
15224                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15225                                + ps.codePathString);
15226                    }
15227                }
15228            }
15229
15230            Arrays.sort(uidArr);
15231        }
15232
15233        // Process packages with valid entries.
15234        if (isMounted) {
15235            if (DEBUG_SD_INSTALL)
15236                Log.i(TAG, "Loading packages");
15237            loadMediaPackages(processCids, uidArr);
15238            startCleaningPackages();
15239            mInstallerService.onSecureContainersAvailable();
15240        } else {
15241            if (DEBUG_SD_INSTALL)
15242                Log.i(TAG, "Unloading packages");
15243            unloadMediaPackages(processCids, uidArr, reportStatus);
15244        }
15245    }
15246
15247    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15248            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15249        final int size = infos.size();
15250        final String[] packageNames = new String[size];
15251        final int[] packageUids = new int[size];
15252        for (int i = 0; i < size; i++) {
15253            final ApplicationInfo info = infos.get(i);
15254            packageNames[i] = info.packageName;
15255            packageUids[i] = info.uid;
15256        }
15257        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15258                finishedReceiver);
15259    }
15260
15261    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15262            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15263        sendResourcesChangedBroadcast(mediaStatus, replacing,
15264                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15265    }
15266
15267    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15268            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15269        int size = pkgList.length;
15270        if (size > 0) {
15271            // Send broadcasts here
15272            Bundle extras = new Bundle();
15273            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15274            if (uidArr != null) {
15275                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15276            }
15277            if (replacing) {
15278                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15279            }
15280            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15281                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15282            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15283        }
15284    }
15285
15286   /*
15287     * Look at potentially valid container ids from processCids If package
15288     * information doesn't match the one on record or package scanning fails,
15289     * the cid is added to list of removeCids. We currently don't delete stale
15290     * containers.
15291     */
15292    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
15293        ArrayList<String> pkgList = new ArrayList<String>();
15294        Set<AsecInstallArgs> keys = processCids.keySet();
15295
15296        for (AsecInstallArgs args : keys) {
15297            String codePath = processCids.get(args);
15298            if (DEBUG_SD_INSTALL)
15299                Log.i(TAG, "Loading container : " + args.cid);
15300            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15301            try {
15302                // Make sure there are no container errors first.
15303                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15304                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15305                            + " when installing from sdcard");
15306                    continue;
15307                }
15308                // Check code path here.
15309                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15310                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15311                            + " does not match one in settings " + codePath);
15312                    continue;
15313                }
15314                // Parse package
15315                int parseFlags = mDefParseFlags;
15316                if (args.isExternalAsec()) {
15317                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15318                }
15319                if (args.isFwdLocked()) {
15320                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15321                }
15322
15323                synchronized (mInstallLock) {
15324                    PackageParser.Package pkg = null;
15325                    try {
15326                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15327                    } catch (PackageManagerException e) {
15328                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15329                    }
15330                    // Scan the package
15331                    if (pkg != null) {
15332                        /*
15333                         * TODO why is the lock being held? doPostInstall is
15334                         * called in other places without the lock. This needs
15335                         * to be straightened out.
15336                         */
15337                        // writer
15338                        synchronized (mPackages) {
15339                            retCode = PackageManager.INSTALL_SUCCEEDED;
15340                            pkgList.add(pkg.packageName);
15341                            // Post process args
15342                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15343                                    pkg.applicationInfo.uid);
15344                        }
15345                    } else {
15346                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15347                    }
15348                }
15349
15350            } finally {
15351                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15352                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15353                }
15354            }
15355        }
15356        // writer
15357        synchronized (mPackages) {
15358            // If the platform SDK has changed since the last time we booted,
15359            // we need to re-grant app permission to catch any new ones that
15360            // appear. This is really a hack, and means that apps can in some
15361            // cases get permissions that the user didn't initially explicitly
15362            // allow... it would be nice to have some better way to handle
15363            // this situation.
15364            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
15365            if (regrantPermissions)
15366                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
15367                        + mSdkVersion + "; regranting permissions for external storage");
15368            mSettings.mExternalSdkPlatform = mSdkVersion;
15369
15370            // Make sure group IDs have been assigned, and any permission
15371            // changes in other apps are accounted for
15372            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
15373                    | (regrantPermissions
15374                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
15375                            : 0));
15376
15377            mSettings.updateExternalDatabaseVersion();
15378
15379            // can downgrade to reader
15380            // Persist settings
15381            mSettings.writeLPr();
15382        }
15383        // Send a broadcast to let everyone know we are done processing
15384        if (pkgList.size() > 0) {
15385            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15386        }
15387    }
15388
15389   /*
15390     * Utility method to unload a list of specified containers
15391     */
15392    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15393        // Just unmount all valid containers.
15394        for (AsecInstallArgs arg : cidArgs) {
15395            synchronized (mInstallLock) {
15396                arg.doPostDeleteLI(false);
15397           }
15398       }
15399   }
15400
15401    /*
15402     * Unload packages mounted on external media. This involves deleting package
15403     * data from internal structures, sending broadcasts about diabled packages,
15404     * gc'ing to free up references, unmounting all secure containers
15405     * corresponding to packages on external media, and posting a
15406     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15407     * that we always have to post this message if status has been requested no
15408     * matter what.
15409     */
15410    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15411            final boolean reportStatus) {
15412        if (DEBUG_SD_INSTALL)
15413            Log.i(TAG, "unloading media packages");
15414        ArrayList<String> pkgList = new ArrayList<String>();
15415        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15416        final Set<AsecInstallArgs> keys = processCids.keySet();
15417        for (AsecInstallArgs args : keys) {
15418            String pkgName = args.getPackageName();
15419            if (DEBUG_SD_INSTALL)
15420                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15421            // Delete package internally
15422            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15423            synchronized (mInstallLock) {
15424                boolean res = deletePackageLI(pkgName, null, false, null, null,
15425                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15426                if (res) {
15427                    pkgList.add(pkgName);
15428                } else {
15429                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15430                    failedList.add(args);
15431                }
15432            }
15433        }
15434
15435        // reader
15436        synchronized (mPackages) {
15437            // We didn't update the settings after removing each package;
15438            // write them now for all packages.
15439            mSettings.writeLPr();
15440        }
15441
15442        // We have to absolutely send UPDATED_MEDIA_STATUS only
15443        // after confirming that all the receivers processed the ordered
15444        // broadcast when packages get disabled, force a gc to clean things up.
15445        // and unload all the containers.
15446        if (pkgList.size() > 0) {
15447            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15448                    new IIntentReceiver.Stub() {
15449                public void performReceive(Intent intent, int resultCode, String data,
15450                        Bundle extras, boolean ordered, boolean sticky,
15451                        int sendingUser) throws RemoteException {
15452                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15453                            reportStatus ? 1 : 0, 1, keys);
15454                    mHandler.sendMessage(msg);
15455                }
15456            });
15457        } else {
15458            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15459                    keys);
15460            mHandler.sendMessage(msg);
15461        }
15462    }
15463
15464    private void loadPrivatePackages(VolumeInfo vol) {
15465        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15466        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15467        synchronized (mInstallLock) {
15468        synchronized (mPackages) {
15469            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15470            for (PackageSetting ps : packages) {
15471                final PackageParser.Package pkg;
15472                try {
15473                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15474                    loaded.add(pkg.applicationInfo);
15475                } catch (PackageManagerException e) {
15476                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15477                }
15478            }
15479
15480            // TODO: regrant any permissions that changed based since original install
15481
15482            mSettings.writeLPr();
15483        }
15484        }
15485
15486        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15487        sendResourcesChangedBroadcast(true, false, loaded, null);
15488    }
15489
15490    private void unloadPrivatePackages(VolumeInfo vol) {
15491        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15492        synchronized (mInstallLock) {
15493        synchronized (mPackages) {
15494            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15495            for (PackageSetting ps : packages) {
15496                if (ps.pkg == null) continue;
15497
15498                final ApplicationInfo info = ps.pkg.applicationInfo;
15499                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15500                if (deletePackageLI(ps.name, null, false, null, null,
15501                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15502                    unloaded.add(info);
15503                } else {
15504                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15505                }
15506            }
15507
15508            mSettings.writeLPr();
15509        }
15510        }
15511
15512        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15513        sendResourcesChangedBroadcast(false, false, unloaded, null);
15514    }
15515
15516    /**
15517     * Examine all users present on given mounted volume, and destroy data
15518     * belonging to users that are no longer valid, or whose user ID has been
15519     * recycled.
15520     */
15521    private void reconcileUsers(String volumeUuid) {
15522        final File[] files = Environment.getDataUserDirectory(volumeUuid).listFiles();
15523        if (ArrayUtils.isEmpty(files)) {
15524            Slog.d(TAG, "No users found on " + volumeUuid);
15525            return;
15526        }
15527
15528        for (File file : files) {
15529            if (!file.isDirectory()) continue;
15530
15531            final int userId;
15532            final UserInfo info;
15533            try {
15534                userId = Integer.parseInt(file.getName());
15535                info = sUserManager.getUserInfo(userId);
15536            } catch (NumberFormatException e) {
15537                Slog.w(TAG, "Invalid user directory " + file);
15538                continue;
15539            }
15540
15541            boolean destroyUser = false;
15542            if (info == null) {
15543                logCriticalInfo(Log.WARN, "Destroying user directory " + file
15544                        + " because no matching user was found");
15545                destroyUser = true;
15546            } else {
15547                try {
15548                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
15549                } catch (IOException e) {
15550                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
15551                            + " because we failed to enforce serial number: " + e);
15552                    destroyUser = true;
15553                }
15554            }
15555
15556            if (destroyUser) {
15557                synchronized (mInstallLock) {
15558                    mInstaller.removeUserDataDirs(volumeUuid, userId);
15559                }
15560            }
15561        }
15562
15563        final UserManager um = mContext.getSystemService(UserManager.class);
15564        for (UserInfo user : um.getUsers()) {
15565            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
15566            if (userDir.exists()) continue;
15567
15568            try {
15569                UserManagerService.prepareUserDirectory(userDir);
15570                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
15571            } catch (IOException e) {
15572                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
15573            }
15574        }
15575    }
15576
15577    /**
15578     * Examine all apps present on given mounted volume, and destroy apps that
15579     * aren't expected, either due to uninstallation or reinstallation on
15580     * another volume.
15581     */
15582    private void reconcileApps(String volumeUuid) {
15583        final File[] files = Environment.getDataAppDirectory(volumeUuid).listFiles();
15584        if (ArrayUtils.isEmpty(files)) {
15585            Slog.d(TAG, "No apps found on " + volumeUuid);
15586            return;
15587        }
15588
15589        for (File file : files) {
15590            final boolean isPackage = (isApkFile(file) || file.isDirectory())
15591                    && !PackageInstallerService.isStageName(file.getName());
15592            if (!isPackage) {
15593                // Ignore entries which are not packages
15594                continue;
15595            }
15596
15597            boolean destroyApp = false;
15598            String packageName = null;
15599            try {
15600                final PackageLite pkg = PackageParser.parsePackageLite(file,
15601                        PackageParser.PARSE_MUST_BE_APK);
15602                packageName = pkg.packageName;
15603
15604                synchronized (mPackages) {
15605                    final PackageSetting ps = mSettings.mPackages.get(packageName);
15606                    if (ps == null) {
15607                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
15608                                + volumeUuid + " because we found no install record");
15609                        destroyApp = true;
15610                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
15611                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
15612                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
15613                        destroyApp = true;
15614                    }
15615                }
15616
15617            } catch (PackageParserException e) {
15618                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
15619                destroyApp = true;
15620            }
15621
15622            if (destroyApp) {
15623                synchronized (mInstallLock) {
15624                    if (packageName != null) {
15625                        removeDataDirsLI(volumeUuid, packageName);
15626                    }
15627                    if (file.isDirectory()) {
15628                        mInstaller.rmPackageDir(file.getAbsolutePath());
15629                    } else {
15630                        file.delete();
15631                    }
15632                }
15633            }
15634        }
15635    }
15636
15637    private void unfreezePackage(String packageName) {
15638        synchronized (mPackages) {
15639            final PackageSetting ps = mSettings.mPackages.get(packageName);
15640            if (ps != null) {
15641                ps.frozen = false;
15642            }
15643        }
15644    }
15645
15646    @Override
15647    public int movePackage(final String packageName, final String volumeUuid) {
15648        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15649
15650        final int moveId = mNextMoveId.getAndIncrement();
15651        try {
15652            movePackageInternal(packageName, volumeUuid, moveId);
15653        } catch (PackageManagerException e) {
15654            Slog.w(TAG, "Failed to move " + packageName, e);
15655            mMoveCallbacks.notifyStatusChanged(moveId,
15656                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15657        }
15658        return moveId;
15659    }
15660
15661    private void movePackageInternal(final String packageName, final String volumeUuid,
15662            final int moveId) throws PackageManagerException {
15663        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15664        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15665        final PackageManager pm = mContext.getPackageManager();
15666
15667        final boolean currentAsec;
15668        final String currentVolumeUuid;
15669        final File codeFile;
15670        final String installerPackageName;
15671        final String packageAbiOverride;
15672        final int appId;
15673        final String seinfo;
15674        final String label;
15675
15676        // reader
15677        synchronized (mPackages) {
15678            final PackageParser.Package pkg = mPackages.get(packageName);
15679            final PackageSetting ps = mSettings.mPackages.get(packageName);
15680            if (pkg == null || ps == null) {
15681                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15682            }
15683
15684            if (pkg.applicationInfo.isSystemApp()) {
15685                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15686                        "Cannot move system application");
15687            }
15688
15689            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
15690                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15691                        "Package already moved to " + volumeUuid);
15692            }
15693
15694            final File probe = new File(pkg.codePath);
15695            final File probeOat = new File(probe, "oat");
15696            if (!probe.isDirectory() || !probeOat.isDirectory()) {
15697                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15698                        "Move only supported for modern cluster style installs");
15699            }
15700
15701            if (ps.frozen) {
15702                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15703                        "Failed to move already frozen package");
15704            }
15705            ps.frozen = true;
15706
15707            currentAsec = pkg.applicationInfo.isForwardLocked()
15708                    || pkg.applicationInfo.isExternalAsec();
15709            currentVolumeUuid = ps.volumeUuid;
15710            codeFile = new File(pkg.codePath);
15711            installerPackageName = ps.installerPackageName;
15712            packageAbiOverride = ps.cpuAbiOverrideString;
15713            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15714            seinfo = pkg.applicationInfo.seinfo;
15715            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15716        }
15717
15718        // Now that we're guarded by frozen state, kill app during move
15719        killApplication(packageName, appId, "move pkg");
15720
15721        final Bundle extras = new Bundle();
15722        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15723        extras.putString(Intent.EXTRA_TITLE, label);
15724        mMoveCallbacks.notifyCreated(moveId, extras);
15725
15726        int installFlags;
15727        final boolean moveCompleteApp;
15728        final File measurePath;
15729
15730        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
15731            installFlags = INSTALL_INTERNAL;
15732            moveCompleteApp = !currentAsec;
15733            measurePath = Environment.getDataAppDirectory(volumeUuid);
15734        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
15735            installFlags = INSTALL_EXTERNAL;
15736            moveCompleteApp = false;
15737            measurePath = storage.getPrimaryPhysicalVolume().getPath();
15738        } else {
15739            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15740            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15741                    || !volume.isMountedWritable()) {
15742                unfreezePackage(packageName);
15743                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15744                        "Move location not mounted private volume");
15745            }
15746
15747            Preconditions.checkState(!currentAsec);
15748
15749            installFlags = INSTALL_INTERNAL;
15750            moveCompleteApp = true;
15751            measurePath = Environment.getDataAppDirectory(volumeUuid);
15752        }
15753
15754        final PackageStats stats = new PackageStats(null, -1);
15755        synchronized (mInstaller) {
15756            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15757                unfreezePackage(packageName);
15758                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15759                        "Failed to measure package size");
15760            }
15761        }
15762
15763        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
15764                + stats.dataSize);
15765
15766        final long startFreeBytes = measurePath.getFreeSpace();
15767        final long sizeBytes;
15768        if (moveCompleteApp) {
15769            sizeBytes = stats.codeSize + stats.dataSize;
15770        } else {
15771            sizeBytes = stats.codeSize;
15772        }
15773
15774        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
15775            unfreezePackage(packageName);
15776            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15777                    "Not enough free space to move");
15778        }
15779
15780        mMoveCallbacks.notifyStatusChanged(moveId, 10);
15781
15782        final CountDownLatch installedLatch = new CountDownLatch(1);
15783        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
15784            @Override
15785            public void onUserActionRequired(Intent intent) throws RemoteException {
15786                throw new IllegalStateException();
15787            }
15788
15789            @Override
15790            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
15791                    Bundle extras) throws RemoteException {
15792                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
15793                        + PackageManager.installStatusToString(returnCode, msg));
15794
15795                installedLatch.countDown();
15796
15797                // Regardless of success or failure of the move operation,
15798                // always unfreeze the package
15799                unfreezePackage(packageName);
15800
15801                final int status = PackageManager.installStatusToPublicStatus(returnCode);
15802                switch (status) {
15803                    case PackageInstaller.STATUS_SUCCESS:
15804                        mMoveCallbacks.notifyStatusChanged(moveId,
15805                                PackageManager.MOVE_SUCCEEDED);
15806                        break;
15807                    case PackageInstaller.STATUS_FAILURE_STORAGE:
15808                        mMoveCallbacks.notifyStatusChanged(moveId,
15809                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
15810                        break;
15811                    default:
15812                        mMoveCallbacks.notifyStatusChanged(moveId,
15813                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15814                        break;
15815                }
15816            }
15817        };
15818
15819        final MoveInfo move;
15820        if (moveCompleteApp) {
15821            // Kick off a thread to report progress estimates
15822            new Thread() {
15823                @Override
15824                public void run() {
15825                    while (true) {
15826                        try {
15827                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
15828                                break;
15829                            }
15830                        } catch (InterruptedException ignored) {
15831                        }
15832
15833                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
15834                        final int progress = 10 + (int) MathUtils.constrain(
15835                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
15836                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
15837                    }
15838                }
15839            }.start();
15840
15841            final String dataAppName = codeFile.getName();
15842            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
15843                    dataAppName, appId, seinfo);
15844        } else {
15845            move = null;
15846        }
15847
15848        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
15849
15850        final Message msg = mHandler.obtainMessage(INIT_COPY);
15851        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
15852        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
15853                installerPackageName, volumeUuid, null, user, packageAbiOverride);
15854        mHandler.sendMessage(msg);
15855    }
15856
15857    @Override
15858    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
15859        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15860
15861        final int realMoveId = mNextMoveId.getAndIncrement();
15862        final Bundle extras = new Bundle();
15863        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
15864        mMoveCallbacks.notifyCreated(realMoveId, extras);
15865
15866        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
15867            @Override
15868            public void onCreated(int moveId, Bundle extras) {
15869                // Ignored
15870            }
15871
15872            @Override
15873            public void onStatusChanged(int moveId, int status, long estMillis) {
15874                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
15875            }
15876        };
15877
15878        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15879        storage.setPrimaryStorageUuid(volumeUuid, callback);
15880        return realMoveId;
15881    }
15882
15883    @Override
15884    public int getMoveStatus(int moveId) {
15885        mContext.enforceCallingOrSelfPermission(
15886                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15887        return mMoveCallbacks.mLastStatus.get(moveId);
15888    }
15889
15890    @Override
15891    public void registerMoveCallback(IPackageMoveObserver callback) {
15892        mContext.enforceCallingOrSelfPermission(
15893                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15894        mMoveCallbacks.register(callback);
15895    }
15896
15897    @Override
15898    public void unregisterMoveCallback(IPackageMoveObserver callback) {
15899        mContext.enforceCallingOrSelfPermission(
15900                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15901        mMoveCallbacks.unregister(callback);
15902    }
15903
15904    @Override
15905    public boolean setInstallLocation(int loc) {
15906        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
15907                null);
15908        if (getInstallLocation() == loc) {
15909            return true;
15910        }
15911        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
15912                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
15913            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
15914                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
15915            return true;
15916        }
15917        return false;
15918   }
15919
15920    @Override
15921    public int getInstallLocation() {
15922        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15923                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
15924                PackageHelper.APP_INSTALL_AUTO);
15925    }
15926
15927    /** Called by UserManagerService */
15928    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
15929        mDirtyUsers.remove(userHandle);
15930        mSettings.removeUserLPw(userHandle);
15931        mPendingBroadcasts.remove(userHandle);
15932        if (mInstaller != null) {
15933            // Technically, we shouldn't be doing this with the package lock
15934            // held.  However, this is very rare, and there is already so much
15935            // other disk I/O going on, that we'll let it slide for now.
15936            final StorageManager storage = mContext.getSystemService(StorageManager.class);
15937            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
15938                final String volumeUuid = vol.getFsUuid();
15939                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
15940                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
15941            }
15942        }
15943        mUserNeedsBadging.delete(userHandle);
15944        removeUnusedPackagesLILPw(userManager, userHandle);
15945    }
15946
15947    /**
15948     * We're removing userHandle and would like to remove any downloaded packages
15949     * that are no longer in use by any other user.
15950     * @param userHandle the user being removed
15951     */
15952    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
15953        final boolean DEBUG_CLEAN_APKS = false;
15954        int [] users = userManager.getUserIdsLPr();
15955        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
15956        while (psit.hasNext()) {
15957            PackageSetting ps = psit.next();
15958            if (ps.pkg == null) {
15959                continue;
15960            }
15961            final String packageName = ps.pkg.packageName;
15962            // Skip over if system app
15963            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15964                continue;
15965            }
15966            if (DEBUG_CLEAN_APKS) {
15967                Slog.i(TAG, "Checking package " + packageName);
15968            }
15969            boolean keep = false;
15970            for (int i = 0; i < users.length; i++) {
15971                if (users[i] != userHandle && ps.getInstalled(users[i])) {
15972                    keep = true;
15973                    if (DEBUG_CLEAN_APKS) {
15974                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
15975                                + users[i]);
15976                    }
15977                    break;
15978                }
15979            }
15980            if (!keep) {
15981                if (DEBUG_CLEAN_APKS) {
15982                    Slog.i(TAG, "  Removing package " + packageName);
15983                }
15984                mHandler.post(new Runnable() {
15985                    public void run() {
15986                        deletePackageX(packageName, userHandle, 0);
15987                    } //end run
15988                });
15989            }
15990        }
15991    }
15992
15993    /** Called by UserManagerService */
15994    void createNewUserLILPw(int userHandle) {
15995        if (mInstaller != null) {
15996            mInstaller.createUserConfig(userHandle);
15997            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
15998            applyFactoryDefaultBrowserLPw(userHandle);
15999            primeDomainVerificationsLPw(userHandle);
16000        }
16001    }
16002
16003    void newUserCreated(final int userHandle) {
16004        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
16005    }
16006
16007    @Override
16008    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
16009        mContext.enforceCallingOrSelfPermission(
16010                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16011                "Only package verification agents can read the verifier device identity");
16012
16013        synchronized (mPackages) {
16014            return mSettings.getVerifierDeviceIdentityLPw();
16015        }
16016    }
16017
16018    @Override
16019    public void setPermissionEnforced(String permission, boolean enforced) {
16020        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
16021        if (READ_EXTERNAL_STORAGE.equals(permission)) {
16022            synchronized (mPackages) {
16023                if (mSettings.mReadExternalStorageEnforced == null
16024                        || mSettings.mReadExternalStorageEnforced != enforced) {
16025                    mSettings.mReadExternalStorageEnforced = enforced;
16026                    mSettings.writeLPr();
16027                }
16028            }
16029            // kill any non-foreground processes so we restart them and
16030            // grant/revoke the GID.
16031            final IActivityManager am = ActivityManagerNative.getDefault();
16032            if (am != null) {
16033                final long token = Binder.clearCallingIdentity();
16034                try {
16035                    am.killProcessesBelowForeground("setPermissionEnforcement");
16036                } catch (RemoteException e) {
16037                } finally {
16038                    Binder.restoreCallingIdentity(token);
16039                }
16040            }
16041        } else {
16042            throw new IllegalArgumentException("No selective enforcement for " + permission);
16043        }
16044    }
16045
16046    @Override
16047    @Deprecated
16048    public boolean isPermissionEnforced(String permission) {
16049        return true;
16050    }
16051
16052    @Override
16053    public boolean isStorageLow() {
16054        final long token = Binder.clearCallingIdentity();
16055        try {
16056            final DeviceStorageMonitorInternal
16057                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16058            if (dsm != null) {
16059                return dsm.isMemoryLow();
16060            } else {
16061                return false;
16062            }
16063        } finally {
16064            Binder.restoreCallingIdentity(token);
16065        }
16066    }
16067
16068    @Override
16069    public IPackageInstaller getPackageInstaller() {
16070        return mInstallerService;
16071    }
16072
16073    private boolean userNeedsBadging(int userId) {
16074        int index = mUserNeedsBadging.indexOfKey(userId);
16075        if (index < 0) {
16076            final UserInfo userInfo;
16077            final long token = Binder.clearCallingIdentity();
16078            try {
16079                userInfo = sUserManager.getUserInfo(userId);
16080            } finally {
16081                Binder.restoreCallingIdentity(token);
16082            }
16083            final boolean b;
16084            if (userInfo != null && userInfo.isManagedProfile()) {
16085                b = true;
16086            } else {
16087                b = false;
16088            }
16089            mUserNeedsBadging.put(userId, b);
16090            return b;
16091        }
16092        return mUserNeedsBadging.valueAt(index);
16093    }
16094
16095    @Override
16096    public KeySet getKeySetByAlias(String packageName, String alias) {
16097        if (packageName == null || alias == null) {
16098            return null;
16099        }
16100        synchronized(mPackages) {
16101            final PackageParser.Package pkg = mPackages.get(packageName);
16102            if (pkg == null) {
16103                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16104                throw new IllegalArgumentException("Unknown package: " + packageName);
16105            }
16106            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16107            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16108        }
16109    }
16110
16111    @Override
16112    public KeySet getSigningKeySet(String packageName) {
16113        if (packageName == null) {
16114            return null;
16115        }
16116        synchronized(mPackages) {
16117            final PackageParser.Package pkg = mPackages.get(packageName);
16118            if (pkg == null) {
16119                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16120                throw new IllegalArgumentException("Unknown package: " + packageName);
16121            }
16122            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16123                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16124                throw new SecurityException("May not access signing KeySet of other apps.");
16125            }
16126            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16127            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16128        }
16129    }
16130
16131    @Override
16132    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16133        if (packageName == null || ks == null) {
16134            return false;
16135        }
16136        synchronized(mPackages) {
16137            final PackageParser.Package pkg = mPackages.get(packageName);
16138            if (pkg == null) {
16139                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16140                throw new IllegalArgumentException("Unknown package: " + packageName);
16141            }
16142            IBinder ksh = ks.getToken();
16143            if (ksh instanceof KeySetHandle) {
16144                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16145                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16146            }
16147            return false;
16148        }
16149    }
16150
16151    @Override
16152    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16153        if (packageName == null || ks == null) {
16154            return false;
16155        }
16156        synchronized(mPackages) {
16157            final PackageParser.Package pkg = mPackages.get(packageName);
16158            if (pkg == null) {
16159                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16160                throw new IllegalArgumentException("Unknown package: " + packageName);
16161            }
16162            IBinder ksh = ks.getToken();
16163            if (ksh instanceof KeySetHandle) {
16164                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16165                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16166            }
16167            return false;
16168        }
16169    }
16170
16171    public void getUsageStatsIfNoPackageUsageInfo() {
16172        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16173            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16174            if (usm == null) {
16175                throw new IllegalStateException("UsageStatsManager must be initialized");
16176            }
16177            long now = System.currentTimeMillis();
16178            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16179            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16180                String packageName = entry.getKey();
16181                PackageParser.Package pkg = mPackages.get(packageName);
16182                if (pkg == null) {
16183                    continue;
16184                }
16185                UsageStats usage = entry.getValue();
16186                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16187                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16188            }
16189        }
16190    }
16191
16192    /**
16193     * Check and throw if the given before/after packages would be considered a
16194     * downgrade.
16195     */
16196    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16197            throws PackageManagerException {
16198        if (after.versionCode < before.mVersionCode) {
16199            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16200                    "Update version code " + after.versionCode + " is older than current "
16201                    + before.mVersionCode);
16202        } else if (after.versionCode == before.mVersionCode) {
16203            if (after.baseRevisionCode < before.baseRevisionCode) {
16204                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16205                        "Update base revision code " + after.baseRevisionCode
16206                        + " is older than current " + before.baseRevisionCode);
16207            }
16208
16209            if (!ArrayUtils.isEmpty(after.splitNames)) {
16210                for (int i = 0; i < after.splitNames.length; i++) {
16211                    final String splitName = after.splitNames[i];
16212                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16213                    if (j != -1) {
16214                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16215                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16216                                    "Update split " + splitName + " revision code "
16217                                    + after.splitRevisionCodes[i] + " is older than current "
16218                                    + before.splitRevisionCodes[j]);
16219                        }
16220                    }
16221                }
16222            }
16223        }
16224    }
16225
16226    private static class MoveCallbacks extends Handler {
16227        private static final int MSG_CREATED = 1;
16228        private static final int MSG_STATUS_CHANGED = 2;
16229
16230        private final RemoteCallbackList<IPackageMoveObserver>
16231                mCallbacks = new RemoteCallbackList<>();
16232
16233        private final SparseIntArray mLastStatus = new SparseIntArray();
16234
16235        public MoveCallbacks(Looper looper) {
16236            super(looper);
16237        }
16238
16239        public void register(IPackageMoveObserver callback) {
16240            mCallbacks.register(callback);
16241        }
16242
16243        public void unregister(IPackageMoveObserver callback) {
16244            mCallbacks.unregister(callback);
16245        }
16246
16247        @Override
16248        public void handleMessage(Message msg) {
16249            final SomeArgs args = (SomeArgs) msg.obj;
16250            final int n = mCallbacks.beginBroadcast();
16251            for (int i = 0; i < n; i++) {
16252                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16253                try {
16254                    invokeCallback(callback, msg.what, args);
16255                } catch (RemoteException ignored) {
16256                }
16257            }
16258            mCallbacks.finishBroadcast();
16259            args.recycle();
16260        }
16261
16262        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16263                throws RemoteException {
16264            switch (what) {
16265                case MSG_CREATED: {
16266                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16267                    break;
16268                }
16269                case MSG_STATUS_CHANGED: {
16270                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16271                    break;
16272                }
16273            }
16274        }
16275
16276        private void notifyCreated(int moveId, Bundle extras) {
16277            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16278
16279            final SomeArgs args = SomeArgs.obtain();
16280            args.argi1 = moveId;
16281            args.arg2 = extras;
16282            obtainMessage(MSG_CREATED, args).sendToTarget();
16283        }
16284
16285        private void notifyStatusChanged(int moveId, int status) {
16286            notifyStatusChanged(moveId, status, -1);
16287        }
16288
16289        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16290            Slog.v(TAG, "Move " + moveId + " status " + status);
16291
16292            final SomeArgs args = SomeArgs.obtain();
16293            args.argi1 = moveId;
16294            args.argi2 = status;
16295            args.arg3 = estMillis;
16296            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16297
16298            synchronized (mLastStatus) {
16299                mLastStatus.put(moveId, status);
16300            }
16301        }
16302    }
16303
16304    private final class OnPermissionChangeListeners extends Handler {
16305        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16306
16307        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16308                new RemoteCallbackList<>();
16309
16310        public OnPermissionChangeListeners(Looper looper) {
16311            super(looper);
16312        }
16313
16314        @Override
16315        public void handleMessage(Message msg) {
16316            switch (msg.what) {
16317                case MSG_ON_PERMISSIONS_CHANGED: {
16318                    final int uid = msg.arg1;
16319                    handleOnPermissionsChanged(uid);
16320                } break;
16321            }
16322        }
16323
16324        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16325            mPermissionListeners.register(listener);
16326
16327        }
16328
16329        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16330            mPermissionListeners.unregister(listener);
16331        }
16332
16333        public void onPermissionsChanged(int uid) {
16334            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16335                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16336            }
16337        }
16338
16339        private void handleOnPermissionsChanged(int uid) {
16340            final int count = mPermissionListeners.beginBroadcast();
16341            try {
16342                for (int i = 0; i < count; i++) {
16343                    IOnPermissionsChangeListener callback = mPermissionListeners
16344                            .getBroadcastItem(i);
16345                    try {
16346                        callback.onPermissionsChanged(uid);
16347                    } catch (RemoteException e) {
16348                        Log.e(TAG, "Permission listener is dead", e);
16349                    }
16350                }
16351            } finally {
16352                mPermissionListeners.finishBroadcast();
16353            }
16354        }
16355    }
16356
16357    private class PackageManagerInternalImpl extends PackageManagerInternal {
16358        @Override
16359        public void setLocationPackagesProvider(PackagesProvider provider) {
16360            synchronized (mPackages) {
16361                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16362            }
16363        }
16364
16365        @Override
16366        public void setImePackagesProvider(PackagesProvider provider) {
16367            synchronized (mPackages) {
16368                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16369            }
16370        }
16371
16372        @Override
16373        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16374            synchronized (mPackages) {
16375                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16376            }
16377        }
16378
16379        @Override
16380        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16381            synchronized (mPackages) {
16382                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16383            }
16384        }
16385
16386        @Override
16387        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16388            synchronized (mPackages) {
16389                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16390            }
16391        }
16392
16393        @Override
16394        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16395            synchronized (mPackages) {
16396                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderrLPw(provider);
16397            }
16398        }
16399
16400        @Override
16401        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16402            synchronized (mPackages) {
16403                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16404                        packageName, userId);
16405            }
16406        }
16407
16408        @Override
16409        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16410            synchronized (mPackages) {
16411                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16412                        packageName, userId);
16413            }
16414        }
16415    }
16416
16417    @Override
16418    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16419        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16420        synchronized (mPackages) {
16421            final long identity = Binder.clearCallingIdentity();
16422            try {
16423                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16424                        packageNames, userId);
16425            } finally {
16426                Binder.restoreCallingIdentity(identity);
16427            }
16428        }
16429    }
16430
16431    private static void enforceSystemOrPhoneCaller(String tag) {
16432        int callingUid = Binder.getCallingUid();
16433        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16434            throw new SecurityException(
16435                    "Cannot call " + tag + " from UID " + callingUid);
16436        }
16437    }
16438}
16439