PackageManagerService.java revision 3233a0a65c8bd2acce4b8fdfe6ce8e6c20b9a24d
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.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
26import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
27import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
28import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
29import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
30import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
32import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
33import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
34import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
36import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
37import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
38import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
39import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
41import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
42import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
44import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
45import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
46import static android.content.pm.PackageManager.INSTALL_INTERNAL;
47import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
48import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
49import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
50import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
51import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
52import static android.content.pm.PackageManager.MATCH_ALL;
53import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
54import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
55import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
56import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
57import static android.content.pm.PackageParser.isApkFile;
58import static android.os.Process.FIRST_APPLICATION_UID;
59import static android.os.Process.PACKAGE_INFO_GID;
60import static android.os.Process.SYSTEM_UID;
61import static android.system.OsConstants.O_CREAT;
62import static android.system.OsConstants.O_RDWR;
63import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
64import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
65import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
66import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
67import static com.android.internal.util.ArrayUtils.appendInt;
68import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
69import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
70import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
71import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
72import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
73
74import android.Manifest;
75import android.app.ActivityManager;
76import android.app.ActivityManagerNative;
77import android.app.AppGlobals;
78import android.app.IActivityManager;
79import android.app.admin.IDevicePolicyManager;
80import android.app.backup.IBackupManager;
81import android.app.usage.UsageStats;
82import android.app.usage.UsageStatsManager;
83import android.content.BroadcastReceiver;
84import android.content.ComponentName;
85import android.content.Context;
86import android.content.IIntentReceiver;
87import android.content.Intent;
88import android.content.IntentFilter;
89import android.content.IntentSender;
90import android.content.IntentSender.SendIntentException;
91import android.content.ServiceConnection;
92import android.content.pm.ActivityInfo;
93import android.content.pm.ApplicationInfo;
94import android.content.pm.FeatureInfo;
95import android.content.pm.IOnPermissionsChangeListener;
96import android.content.pm.IPackageDataObserver;
97import android.content.pm.IPackageDeleteObserver;
98import android.content.pm.IPackageDeleteObserver2;
99import android.content.pm.IPackageInstallObserver2;
100import android.content.pm.IPackageInstaller;
101import android.content.pm.IPackageManager;
102import android.content.pm.IPackageMoveObserver;
103import android.content.pm.IPackageStatsObserver;
104import android.content.pm.InstrumentationInfo;
105import android.content.pm.IntentFilterVerificationInfo;
106import android.content.pm.KeySet;
107import android.content.pm.ManifestDigest;
108import android.content.pm.PackageCleanItem;
109import android.content.pm.PackageInfo;
110import android.content.pm.PackageInfoLite;
111import android.content.pm.PackageInstaller;
112import android.content.pm.PackageManager;
113import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
114import android.content.pm.PackageParser;
115import android.content.pm.PackageParser.ActivityIntentInfo;
116import android.content.pm.PackageParser.PackageLite;
117import android.content.pm.PackageParser.PackageParserException;
118import android.content.pm.PackageStats;
119import android.content.pm.PackageUserState;
120import android.content.pm.ParceledListSlice;
121import android.content.pm.PermissionGroupInfo;
122import android.content.pm.PermissionInfo;
123import android.content.pm.ProviderInfo;
124import android.content.pm.ResolveInfo;
125import android.content.pm.ServiceInfo;
126import android.content.pm.Signature;
127import android.content.pm.UserInfo;
128import android.content.pm.VerificationParams;
129import android.content.pm.VerifierDeviceIdentity;
130import android.content.pm.VerifierInfo;
131import android.content.res.Resources;
132import android.hardware.display.DisplayManager;
133import android.net.Uri;
134import android.os.Binder;
135import android.os.Build;
136import android.os.Bundle;
137import android.os.Debug;
138import android.os.Environment;
139import android.os.Environment.UserEnvironment;
140import android.os.FileUtils;
141import android.os.Handler;
142import android.os.IBinder;
143import android.os.Looper;
144import android.os.Message;
145import android.os.Parcel;
146import android.os.ParcelFileDescriptor;
147import android.os.Process;
148import android.os.RemoteCallbackList;
149import android.os.RemoteException;
150import android.os.SELinux;
151import android.os.ServiceManager;
152import android.os.SystemClock;
153import android.os.SystemProperties;
154import android.os.UserHandle;
155import android.os.UserManager;
156import android.os.storage.IMountService;
157import android.os.storage.StorageEventListener;
158import android.os.storage.StorageManager;
159import android.os.storage.VolumeInfo;
160import android.os.storage.VolumeRecord;
161import android.security.KeyStore;
162import android.security.SystemKeyStore;
163import android.system.ErrnoException;
164import android.system.Os;
165import android.system.StructStat;
166import android.text.TextUtils;
167import android.text.format.DateUtils;
168import android.util.ArrayMap;
169import android.util.ArraySet;
170import android.util.AtomicFile;
171import android.util.DisplayMetrics;
172import android.util.EventLog;
173import android.util.ExceptionUtils;
174import android.util.Log;
175import android.util.LogPrinter;
176import android.util.MathUtils;
177import android.util.PrintStreamPrinter;
178import android.util.Slog;
179import android.util.SparseArray;
180import android.util.SparseBooleanArray;
181import android.util.SparseIntArray;
182import android.util.Xml;
183import android.view.Display;
184
185import dalvik.system.DexFile;
186import dalvik.system.VMRuntime;
187
188import libcore.io.IoUtils;
189import libcore.util.EmptyArray;
190
191import com.android.internal.R;
192import com.android.internal.app.IMediaContainerService;
193import com.android.internal.app.ResolverActivity;
194import com.android.internal.content.NativeLibraryHelper;
195import com.android.internal.content.PackageHelper;
196import com.android.internal.os.IParcelFileDescriptorFactory;
197import com.android.internal.os.SomeArgs;
198import com.android.internal.util.ArrayUtils;
199import com.android.internal.util.FastPrintWriter;
200import com.android.internal.util.FastXmlSerializer;
201import com.android.internal.util.IndentingPrintWriter;
202import com.android.internal.util.Preconditions;
203import com.android.server.EventLogTags;
204import com.android.server.FgThread;
205import com.android.server.IntentResolver;
206import com.android.server.LocalServices;
207import com.android.server.ServiceThread;
208import com.android.server.SystemConfig;
209import com.android.server.Watchdog;
210import com.android.server.pm.Settings.DatabaseVersion;
211import com.android.server.pm.PermissionsState.PermissionState;
212import com.android.server.storage.DeviceStorageMonitorInternal;
213
214import org.xmlpull.v1.XmlPullParser;
215import org.xmlpull.v1.XmlSerializer;
216
217import java.io.BufferedInputStream;
218import java.io.BufferedOutputStream;
219import java.io.BufferedReader;
220import java.io.ByteArrayInputStream;
221import java.io.ByteArrayOutputStream;
222import java.io.File;
223import java.io.FileDescriptor;
224import java.io.FileNotFoundException;
225import java.io.FileOutputStream;
226import java.io.FileReader;
227import java.io.FilenameFilter;
228import java.io.IOException;
229import java.io.InputStream;
230import java.io.PrintWriter;
231import java.nio.charset.StandardCharsets;
232import java.security.NoSuchAlgorithmException;
233import java.security.PublicKey;
234import java.security.cert.CertificateEncodingException;
235import java.security.cert.CertificateException;
236import java.text.SimpleDateFormat;
237import java.util.ArrayList;
238import java.util.Arrays;
239import java.util.Collection;
240import java.util.Collections;
241import java.util.Comparator;
242import java.util.Date;
243import java.util.Iterator;
244import java.util.List;
245import java.util.Map;
246import java.util.Objects;
247import java.util.Set;
248import java.util.concurrent.CountDownLatch;
249import java.util.concurrent.TimeUnit;
250import java.util.concurrent.atomic.AtomicBoolean;
251import java.util.concurrent.atomic.AtomicInteger;
252import java.util.concurrent.atomic.AtomicLong;
253
254/**
255 * Keep track of all those .apks everywhere.
256 *
257 * This is very central to the platform's security; please run the unit
258 * tests whenever making modifications here:
259 *
260mmm frameworks/base/tests/AndroidTests
261adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
262adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
263 *
264 * {@hide}
265 */
266public class PackageManagerService extends IPackageManager.Stub {
267    static final String TAG = "PackageManager";
268    static final boolean DEBUG_SETTINGS = false;
269    static final boolean DEBUG_PREFERRED = false;
270    static final boolean DEBUG_UPGRADE = false;
271    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
272    private static final boolean DEBUG_BACKUP = true;
273    private static final boolean DEBUG_INSTALL = false;
274    private static final boolean DEBUG_REMOVE = false;
275    private static final boolean DEBUG_BROADCASTS = false;
276    private static final boolean DEBUG_SHOW_INFO = false;
277    private static final boolean DEBUG_PACKAGE_INFO = false;
278    private static final boolean DEBUG_INTENT_MATCHING = false;
279    private static final boolean DEBUG_PACKAGE_SCANNING = false;
280    private static final boolean DEBUG_VERIFY = false;
281    private static final boolean DEBUG_DEXOPT = false;
282    private static final boolean DEBUG_ABI_SELECTION = false;
283
284    private static final int RADIO_UID = Process.PHONE_UID;
285    private static final int LOG_UID = Process.LOG_UID;
286    private static final int NFC_UID = Process.NFC_UID;
287    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
288    private static final int SHELL_UID = Process.SHELL_UID;
289
290    // Cap the size of permission trees that 3rd party apps can define
291    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
292
293    // Suffix used during package installation when copying/moving
294    // package apks to install directory.
295    private static final String INSTALL_PACKAGE_SUFFIX = "-";
296
297    static final int SCAN_NO_DEX = 1<<1;
298    static final int SCAN_FORCE_DEX = 1<<2;
299    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
300    static final int SCAN_NEW_INSTALL = 1<<4;
301    static final int SCAN_NO_PATHS = 1<<5;
302    static final int SCAN_UPDATE_TIME = 1<<6;
303    static final int SCAN_DEFER_DEX = 1<<7;
304    static final int SCAN_BOOTING = 1<<8;
305    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
306    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
307    static final int SCAN_REQUIRE_KNOWN = 1<<12;
308    static final int SCAN_MOVE = 1<<13;
309
310    static final int REMOVE_CHATTY = 1<<16;
311
312    private static final int[] EMPTY_INT_ARRAY = new int[0];
313
314    /**
315     * Timeout (in milliseconds) after which the watchdog should declare that
316     * our handler thread is wedged.  The usual default for such things is one
317     * minute but we sometimes do very lengthy I/O operations on this thread,
318     * such as installing multi-gigabyte applications, so ours needs to be longer.
319     */
320    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
321
322    /**
323     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
324     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
325     * settings entry if available, otherwise we use the hardcoded default.  If it's been
326     * more than this long since the last fstrim, we force one during the boot sequence.
327     *
328     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
329     * one gets run at the next available charging+idle time.  This final mandatory
330     * no-fstrim check kicks in only of the other scheduling criteria is never met.
331     */
332    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
333
334    /**
335     * Whether verification is enabled by default.
336     */
337    private static final boolean DEFAULT_VERIFY_ENABLE = true;
338
339    /**
340     * The default maximum time to wait for the verification agent to return in
341     * milliseconds.
342     */
343    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
344
345    /**
346     * The default response for package verification timeout.
347     *
348     * This can be either PackageManager.VERIFICATION_ALLOW or
349     * PackageManager.VERIFICATION_REJECT.
350     */
351    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
352
353    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
354
355    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
356            DEFAULT_CONTAINER_PACKAGE,
357            "com.android.defcontainer.DefaultContainerService");
358
359    private static final String KILL_APP_REASON_GIDS_CHANGED =
360            "permission grant or revoke changed gids";
361
362    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
363            "permissions revoked";
364
365    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
366
367    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
368
369    /** Permission grant: not grant the permission. */
370    private static final int GRANT_DENIED = 1;
371
372    /** Permission grant: grant the permission as an install permission. */
373    private static final int GRANT_INSTALL = 2;
374
375    /** Permission grant: grant the permission as an install permission for a legacy app. */
376    private static final int GRANT_INSTALL_LEGACY = 3;
377
378    /** Permission grant: grant the permission as a runtime one. */
379    private static final int GRANT_RUNTIME = 4;
380
381    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
382    private static final int GRANT_UPGRADE = 5;
383
384    final ServiceThread mHandlerThread;
385
386    final PackageHandler mHandler;
387
388    /**
389     * Messages for {@link #mHandler} that need to wait for system ready before
390     * being dispatched.
391     */
392    private ArrayList<Message> mPostSystemReadyMessages;
393
394    final int mSdkVersion = Build.VERSION.SDK_INT;
395
396    final Context mContext;
397    final boolean mFactoryTest;
398    final boolean mOnlyCore;
399    final boolean mLazyDexOpt;
400    final long mDexOptLRUThresholdInMills;
401    final DisplayMetrics mMetrics;
402    final int mDefParseFlags;
403    final String[] mSeparateProcesses;
404    final boolean mIsUpgrade;
405
406    // This is where all application persistent data goes.
407    final File mAppDataDir;
408
409    // This is where all application persistent data goes for secondary users.
410    final File mUserAppDataDir;
411
412    /** The location for ASEC container files on internal storage. */
413    final String mAsecInternalPath;
414
415    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
416    // LOCK HELD.  Can be called with mInstallLock held.
417    final Installer mInstaller;
418
419    /** Directory where installed third-party apps stored */
420    final File mAppInstallDir;
421
422    /**
423     * Directory to which applications installed internally have their
424     * 32 bit native libraries copied.
425     */
426    private File mAppLib32InstallDir;
427
428    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
429    // apps.
430    final File mDrmAppPrivateInstallDir;
431
432    // ----------------------------------------------------------------
433
434    // Lock for state used when installing and doing other long running
435    // operations.  Methods that must be called with this lock held have
436    // the suffix "LI".
437    final Object mInstallLock = new Object();
438
439    // ----------------------------------------------------------------
440
441    // Keys are String (package name), values are Package.  This also serves
442    // as the lock for the global state.  Methods that must be called with
443    // this lock held have the prefix "LP".
444    final ArrayMap<String, PackageParser.Package> mPackages =
445            new ArrayMap<String, PackageParser.Package>();
446
447    // Tracks available target package names -> overlay package paths.
448    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
449        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
450
451    final Settings mSettings;
452    boolean mRestoredSettings;
453
454    // System configuration read by SystemConfig.
455    final int[] mGlobalGids;
456    final SparseArray<ArraySet<String>> mSystemPermissions;
457    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
458
459    // If mac_permissions.xml was found for seinfo labeling.
460    boolean mFoundPolicyFile;
461
462    // If a recursive restorecon of /data/data/<pkg> is needed.
463    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
464
465    public static final class SharedLibraryEntry {
466        public final String path;
467        public final String apk;
468
469        SharedLibraryEntry(String _path, String _apk) {
470            path = _path;
471            apk = _apk;
472        }
473    }
474
475    // Currently known shared libraries.
476    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
477            new ArrayMap<String, SharedLibraryEntry>();
478
479    // All available activities, for your resolving pleasure.
480    final ActivityIntentResolver mActivities =
481            new ActivityIntentResolver();
482
483    // All available receivers, for your resolving pleasure.
484    final ActivityIntentResolver mReceivers =
485            new ActivityIntentResolver();
486
487    // All available services, for your resolving pleasure.
488    final ServiceIntentResolver mServices = new ServiceIntentResolver();
489
490    // All available providers, for your resolving pleasure.
491    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
492
493    // Mapping from provider base names (first directory in content URI codePath)
494    // to the provider information.
495    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
496            new ArrayMap<String, PackageParser.Provider>();
497
498    // Mapping from instrumentation class names to info about them.
499    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
500            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
501
502    // Mapping from permission names to info about them.
503    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
504            new ArrayMap<String, PackageParser.PermissionGroup>();
505
506    // Packages whose data we have transfered into another package, thus
507    // should no longer exist.
508    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
509
510    // Broadcast actions that are only available to the system.
511    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
512
513    /** List of packages waiting for verification. */
514    final SparseArray<PackageVerificationState> mPendingVerification
515            = new SparseArray<PackageVerificationState>();
516
517    /** Set of packages associated with each app op permission. */
518    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
519
520    final PackageInstallerService mInstallerService;
521
522    private final PackageDexOptimizer mPackageDexOptimizer;
523
524    private AtomicInteger mNextMoveId = new AtomicInteger();
525    private final MoveCallbacks mMoveCallbacks;
526
527    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
528
529    // Cache of users who need badging.
530    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
531
532    /** Token for keys in mPendingVerification. */
533    private int mPendingVerificationToken = 0;
534
535    volatile boolean mSystemReady;
536    volatile boolean mSafeMode;
537    volatile boolean mHasSystemUidErrors;
538
539    ApplicationInfo mAndroidApplication;
540    final ActivityInfo mResolveActivity = new ActivityInfo();
541    final ResolveInfo mResolveInfo = new ResolveInfo();
542    ComponentName mResolveComponentName;
543    PackageParser.Package mPlatformPackage;
544    ComponentName mCustomResolverComponentName;
545
546    boolean mResolverReplaced = false;
547
548    private final ComponentName mIntentFilterVerifierComponent;
549    private int mIntentFilterVerificationToken = 0;
550
551    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
552            = new SparseArray<IntentFilterVerificationState>();
553
554    private interface IntentFilterVerifier<T extends IntentFilter> {
555        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
556                                               T filter, String packageName);
557        void startVerifications(int userId);
558        void receiveVerificationResponse(int verificationId);
559    }
560
561    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
562        private Context mContext;
563        private ComponentName mIntentFilterVerifierComponent;
564        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
565
566        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
567            mContext = context;
568            mIntentFilterVerifierComponent = verifierComponent;
569        }
570
571        private String getDefaultScheme() {
572            return IntentFilter.SCHEME_HTTPS;
573        }
574
575        @Override
576        public void startVerifications(int userId) {
577            // Launch verifications requests
578            int count = mCurrentIntentFilterVerifications.size();
579            for (int n=0; n<count; n++) {
580                int verificationId = mCurrentIntentFilterVerifications.get(n);
581                final IntentFilterVerificationState ivs =
582                        mIntentFilterVerificationStates.get(verificationId);
583
584                String packageName = ivs.getPackageName();
585
586                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
587                final int filterCount = filters.size();
588                ArraySet<String> domainsSet = new ArraySet<>();
589                for (int m=0; m<filterCount; m++) {
590                    PackageParser.ActivityIntentInfo filter = filters.get(m);
591                    domainsSet.addAll(filter.getHostsList());
592                }
593                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
594                synchronized (mPackages) {
595                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
596                            packageName, domainsList) != null) {
597                        scheduleWriteSettingsLocked();
598                    }
599                }
600                sendVerificationRequest(userId, verificationId, ivs);
601            }
602            mCurrentIntentFilterVerifications.clear();
603        }
604
605        private void sendVerificationRequest(int userId, int verificationId,
606                IntentFilterVerificationState ivs) {
607
608            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
609            verificationIntent.putExtra(
610                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
611                    verificationId);
612            verificationIntent.putExtra(
613                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
614                    getDefaultScheme());
615            verificationIntent.putExtra(
616                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
617                    ivs.getHostsString());
618            verificationIntent.putExtra(
619                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
620                    ivs.getPackageName());
621            verificationIntent.setComponent(mIntentFilterVerifierComponent);
622            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
623
624            UserHandle user = new UserHandle(userId);
625            mContext.sendBroadcastAsUser(verificationIntent, user);
626            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
627                    "Sending IntenFilter verification broadcast");
628        }
629
630        public void receiveVerificationResponse(int verificationId) {
631            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
632
633            final boolean verified = ivs.isVerified();
634
635            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
636            final int count = filters.size();
637            for (int n=0; n<count; n++) {
638                PackageParser.ActivityIntentInfo filter = filters.get(n);
639                filter.setVerified(verified);
640
641                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
642                        + " verified with result:" + verified + " and hosts:"
643                        + ivs.getHostsString());
644            }
645
646            mIntentFilterVerificationStates.remove(verificationId);
647
648            final String packageName = ivs.getPackageName();
649            IntentFilterVerificationInfo ivi = null;
650
651            synchronized (mPackages) {
652                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
653            }
654            if (ivi == null) {
655                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
656                        + verificationId + " packageName:" + packageName);
657                return;
658            }
659            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
660                    "Updating IntentFilterVerificationInfo for verificationId:" + verificationId);
661
662            synchronized (mPackages) {
663                if (verified) {
664                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
665                } else {
666                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
667                }
668                scheduleWriteSettingsLocked();
669
670                final int userId = ivs.getUserId();
671                if (userId != UserHandle.USER_ALL) {
672                    final int userStatus =
673                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
674
675                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
676                    boolean needUpdate = false;
677
678                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
679                    // already been set by the User thru the Disambiguation dialog
680                    switch (userStatus) {
681                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
682                            if (verified) {
683                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
684                            } else {
685                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
686                            }
687                            needUpdate = true;
688                            break;
689
690                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
691                            if (verified) {
692                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
693                                needUpdate = true;
694                            }
695                            break;
696
697                        default:
698                            // Nothing to do
699                    }
700
701                    if (needUpdate) {
702                        mSettings.updateIntentFilterVerificationStatusLPw(
703                                packageName, updatedStatus, userId);
704                        scheduleWritePackageRestrictionsLocked(userId);
705                    }
706                }
707            }
708        }
709
710        @Override
711        public boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
712                    ActivityIntentInfo filter, String packageName) {
713            if (!(filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
714                    filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
715                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
716                        "IntentFilter does not contain HTTP nor HTTPS data scheme");
717                return false;
718            }
719            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
720            if (ivs == null) {
721                ivs = createDomainVerificationState(verifierId, userId, verificationId,
722                        packageName);
723            }
724            if (!hasValidDomains(filter)) {
725                return false;
726            }
727            ivs.addFilter(filter);
728            return true;
729        }
730
731        private IntentFilterVerificationState createDomainVerificationState(int verifierId,
732                int userId, int verificationId, String packageName) {
733            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
734                    verifierId, userId, packageName);
735            ivs.setPendingState();
736            synchronized (mPackages) {
737                mIntentFilterVerificationStates.append(verificationId, ivs);
738                mCurrentIntentFilterVerifications.add(verificationId);
739            }
740            return ivs;
741        }
742    }
743
744    private static boolean hasValidDomains(ActivityIntentInfo filter) {
745        boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
746                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS);
747        if (!hasHTTPorHTTPS) {
748            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
749                    "IntentFilter does not contain any HTTP or HTTPS data scheme");
750            return false;
751        }
752        return true;
753    }
754
755    private IntentFilterVerifier mIntentFilterVerifier;
756
757    // Set of pending broadcasts for aggregating enable/disable of components.
758    static class PendingPackageBroadcasts {
759        // for each user id, a map of <package name -> components within that package>
760        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
761
762        public PendingPackageBroadcasts() {
763            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
764        }
765
766        public ArrayList<String> get(int userId, String packageName) {
767            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
768            return packages.get(packageName);
769        }
770
771        public void put(int userId, String packageName, ArrayList<String> components) {
772            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
773            packages.put(packageName, components);
774        }
775
776        public void remove(int userId, String packageName) {
777            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
778            if (packages != null) {
779                packages.remove(packageName);
780            }
781        }
782
783        public void remove(int userId) {
784            mUidMap.remove(userId);
785        }
786
787        public int userIdCount() {
788            return mUidMap.size();
789        }
790
791        public int userIdAt(int n) {
792            return mUidMap.keyAt(n);
793        }
794
795        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
796            return mUidMap.get(userId);
797        }
798
799        public int size() {
800            // total number of pending broadcast entries across all userIds
801            int num = 0;
802            for (int i = 0; i< mUidMap.size(); i++) {
803                num += mUidMap.valueAt(i).size();
804            }
805            return num;
806        }
807
808        public void clear() {
809            mUidMap.clear();
810        }
811
812        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
813            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
814            if (map == null) {
815                map = new ArrayMap<String, ArrayList<String>>();
816                mUidMap.put(userId, map);
817            }
818            return map;
819        }
820    }
821    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
822
823    // Service Connection to remote media container service to copy
824    // package uri's from external media onto secure containers
825    // or internal storage.
826    private IMediaContainerService mContainerService = null;
827
828    static final int SEND_PENDING_BROADCAST = 1;
829    static final int MCS_BOUND = 3;
830    static final int END_COPY = 4;
831    static final int INIT_COPY = 5;
832    static final int MCS_UNBIND = 6;
833    static final int START_CLEANING_PACKAGE = 7;
834    static final int FIND_INSTALL_LOC = 8;
835    static final int POST_INSTALL = 9;
836    static final int MCS_RECONNECT = 10;
837    static final int MCS_GIVE_UP = 11;
838    static final int UPDATED_MEDIA_STATUS = 12;
839    static final int WRITE_SETTINGS = 13;
840    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
841    static final int PACKAGE_VERIFIED = 15;
842    static final int CHECK_PENDING_VERIFICATION = 16;
843    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
844    static final int INTENT_FILTER_VERIFIED = 18;
845
846    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
847
848    // Delay time in millisecs
849    static final int BROADCAST_DELAY = 10 * 1000;
850
851    static UserManagerService sUserManager;
852
853    // Stores a list of users whose package restrictions file needs to be updated
854    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
855
856    final private DefaultContainerConnection mDefContainerConn =
857            new DefaultContainerConnection();
858    class DefaultContainerConnection implements ServiceConnection {
859        public void onServiceConnected(ComponentName name, IBinder service) {
860            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
861            IMediaContainerService imcs =
862                IMediaContainerService.Stub.asInterface(service);
863            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
864        }
865
866        public void onServiceDisconnected(ComponentName name) {
867            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
868        }
869    };
870
871    // Recordkeeping of restore-after-install operations that are currently in flight
872    // between the Package Manager and the Backup Manager
873    class PostInstallData {
874        public InstallArgs args;
875        public PackageInstalledInfo res;
876
877        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
878            args = _a;
879            res = _r;
880        }
881    };
882    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
883    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
884
885    // backup/restore of preferred activity state
886    private static final String TAG_PREFERRED_BACKUP = "pa";
887
888    private final String mRequiredVerifierPackage;
889
890    private final PackageUsage mPackageUsage = new PackageUsage();
891
892    private class PackageUsage {
893        private static final int WRITE_INTERVAL
894            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
895
896        private final Object mFileLock = new Object();
897        private final AtomicLong mLastWritten = new AtomicLong(0);
898        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
899
900        private boolean mIsHistoricalPackageUsageAvailable = true;
901
902        boolean isHistoricalPackageUsageAvailable() {
903            return mIsHistoricalPackageUsageAvailable;
904        }
905
906        void write(boolean force) {
907            if (force) {
908                writeInternal();
909                return;
910            }
911            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
912                && !DEBUG_DEXOPT) {
913                return;
914            }
915            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
916                new Thread("PackageUsage_DiskWriter") {
917                    @Override
918                    public void run() {
919                        try {
920                            writeInternal();
921                        } finally {
922                            mBackgroundWriteRunning.set(false);
923                        }
924                    }
925                }.start();
926            }
927        }
928
929        private void writeInternal() {
930            synchronized (mPackages) {
931                synchronized (mFileLock) {
932                    AtomicFile file = getFile();
933                    FileOutputStream f = null;
934                    try {
935                        f = file.startWrite();
936                        BufferedOutputStream out = new BufferedOutputStream(f);
937                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
938                        StringBuilder sb = new StringBuilder();
939                        for (PackageParser.Package pkg : mPackages.values()) {
940                            if (pkg.mLastPackageUsageTimeInMills == 0) {
941                                continue;
942                            }
943                            sb.setLength(0);
944                            sb.append(pkg.packageName);
945                            sb.append(' ');
946                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
947                            sb.append('\n');
948                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
949                        }
950                        out.flush();
951                        file.finishWrite(f);
952                    } catch (IOException e) {
953                        if (f != null) {
954                            file.failWrite(f);
955                        }
956                        Log.e(TAG, "Failed to write package usage times", e);
957                    }
958                }
959            }
960            mLastWritten.set(SystemClock.elapsedRealtime());
961        }
962
963        void readLP() {
964            synchronized (mFileLock) {
965                AtomicFile file = getFile();
966                BufferedInputStream in = null;
967                try {
968                    in = new BufferedInputStream(file.openRead());
969                    StringBuffer sb = new StringBuffer();
970                    while (true) {
971                        String packageName = readToken(in, sb, ' ');
972                        if (packageName == null) {
973                            break;
974                        }
975                        String timeInMillisString = readToken(in, sb, '\n');
976                        if (timeInMillisString == null) {
977                            throw new IOException("Failed to find last usage time for package "
978                                                  + packageName);
979                        }
980                        PackageParser.Package pkg = mPackages.get(packageName);
981                        if (pkg == null) {
982                            continue;
983                        }
984                        long timeInMillis;
985                        try {
986                            timeInMillis = Long.parseLong(timeInMillisString.toString());
987                        } catch (NumberFormatException e) {
988                            throw new IOException("Failed to parse " + timeInMillisString
989                                                  + " as a long.", e);
990                        }
991                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
992                    }
993                } catch (FileNotFoundException expected) {
994                    mIsHistoricalPackageUsageAvailable = false;
995                } catch (IOException e) {
996                    Log.w(TAG, "Failed to read package usage times", e);
997                } finally {
998                    IoUtils.closeQuietly(in);
999                }
1000            }
1001            mLastWritten.set(SystemClock.elapsedRealtime());
1002        }
1003
1004        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1005                throws IOException {
1006            sb.setLength(0);
1007            while (true) {
1008                int ch = in.read();
1009                if (ch == -1) {
1010                    if (sb.length() == 0) {
1011                        return null;
1012                    }
1013                    throw new IOException("Unexpected EOF");
1014                }
1015                if (ch == endOfToken) {
1016                    return sb.toString();
1017                }
1018                sb.append((char)ch);
1019            }
1020        }
1021
1022        private AtomicFile getFile() {
1023            File dataDir = Environment.getDataDirectory();
1024            File systemDir = new File(dataDir, "system");
1025            File fname = new File(systemDir, "package-usage.list");
1026            return new AtomicFile(fname);
1027        }
1028    }
1029
1030    class PackageHandler extends Handler {
1031        private boolean mBound = false;
1032        final ArrayList<HandlerParams> mPendingInstalls =
1033            new ArrayList<HandlerParams>();
1034
1035        private boolean connectToService() {
1036            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1037                    " DefaultContainerService");
1038            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1039            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1040            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1041                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1042                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1043                mBound = true;
1044                return true;
1045            }
1046            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1047            return false;
1048        }
1049
1050        private void disconnectService() {
1051            mContainerService = null;
1052            mBound = false;
1053            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1054            mContext.unbindService(mDefContainerConn);
1055            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1056        }
1057
1058        PackageHandler(Looper looper) {
1059            super(looper);
1060        }
1061
1062        public void handleMessage(Message msg) {
1063            try {
1064                doHandleMessage(msg);
1065            } finally {
1066                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1067            }
1068        }
1069
1070        void doHandleMessage(Message msg) {
1071            switch (msg.what) {
1072                case INIT_COPY: {
1073                    HandlerParams params = (HandlerParams) msg.obj;
1074                    int idx = mPendingInstalls.size();
1075                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1076                    // If a bind was already initiated we dont really
1077                    // need to do anything. The pending install
1078                    // will be processed later on.
1079                    if (!mBound) {
1080                        // If this is the only one pending we might
1081                        // have to bind to the service again.
1082                        if (!connectToService()) {
1083                            Slog.e(TAG, "Failed to bind to media container service");
1084                            params.serviceError();
1085                            return;
1086                        } else {
1087                            // Once we bind to the service, the first
1088                            // pending request will be processed.
1089                            mPendingInstalls.add(idx, params);
1090                        }
1091                    } else {
1092                        mPendingInstalls.add(idx, params);
1093                        // Already bound to the service. Just make
1094                        // sure we trigger off processing the first request.
1095                        if (idx == 0) {
1096                            mHandler.sendEmptyMessage(MCS_BOUND);
1097                        }
1098                    }
1099                    break;
1100                }
1101                case MCS_BOUND: {
1102                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1103                    if (msg.obj != null) {
1104                        mContainerService = (IMediaContainerService) msg.obj;
1105                    }
1106                    if (mContainerService == null) {
1107                        // Something seriously wrong. Bail out
1108                        Slog.e(TAG, "Cannot bind to media container service");
1109                        for (HandlerParams params : mPendingInstalls) {
1110                            // Indicate service bind error
1111                            params.serviceError();
1112                        }
1113                        mPendingInstalls.clear();
1114                    } else if (mPendingInstalls.size() > 0) {
1115                        HandlerParams params = mPendingInstalls.get(0);
1116                        if (params != null) {
1117                            if (params.startCopy()) {
1118                                // We are done...  look for more work or to
1119                                // go idle.
1120                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1121                                        "Checking for more work or unbind...");
1122                                // Delete pending install
1123                                if (mPendingInstalls.size() > 0) {
1124                                    mPendingInstalls.remove(0);
1125                                }
1126                                if (mPendingInstalls.size() == 0) {
1127                                    if (mBound) {
1128                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1129                                                "Posting delayed MCS_UNBIND");
1130                                        removeMessages(MCS_UNBIND);
1131                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1132                                        // Unbind after a little delay, to avoid
1133                                        // continual thrashing.
1134                                        sendMessageDelayed(ubmsg, 10000);
1135                                    }
1136                                } else {
1137                                    // There are more pending requests in queue.
1138                                    // Just post MCS_BOUND message to trigger processing
1139                                    // of next pending install.
1140                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1141                                            "Posting MCS_BOUND for next work");
1142                                    mHandler.sendEmptyMessage(MCS_BOUND);
1143                                }
1144                            }
1145                        }
1146                    } else {
1147                        // Should never happen ideally.
1148                        Slog.w(TAG, "Empty queue");
1149                    }
1150                    break;
1151                }
1152                case MCS_RECONNECT: {
1153                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1154                    if (mPendingInstalls.size() > 0) {
1155                        if (mBound) {
1156                            disconnectService();
1157                        }
1158                        if (!connectToService()) {
1159                            Slog.e(TAG, "Failed to bind to media container service");
1160                            for (HandlerParams params : mPendingInstalls) {
1161                                // Indicate service bind error
1162                                params.serviceError();
1163                            }
1164                            mPendingInstalls.clear();
1165                        }
1166                    }
1167                    break;
1168                }
1169                case MCS_UNBIND: {
1170                    // If there is no actual work left, then time to unbind.
1171                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1172
1173                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1174                        if (mBound) {
1175                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1176
1177                            disconnectService();
1178                        }
1179                    } else if (mPendingInstalls.size() > 0) {
1180                        // There are more pending requests in queue.
1181                        // Just post MCS_BOUND message to trigger processing
1182                        // of next pending install.
1183                        mHandler.sendEmptyMessage(MCS_BOUND);
1184                    }
1185
1186                    break;
1187                }
1188                case MCS_GIVE_UP: {
1189                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1190                    mPendingInstalls.remove(0);
1191                    break;
1192                }
1193                case SEND_PENDING_BROADCAST: {
1194                    String packages[];
1195                    ArrayList<String> components[];
1196                    int size = 0;
1197                    int uids[];
1198                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1199                    synchronized (mPackages) {
1200                        if (mPendingBroadcasts == null) {
1201                            return;
1202                        }
1203                        size = mPendingBroadcasts.size();
1204                        if (size <= 0) {
1205                            // Nothing to be done. Just return
1206                            return;
1207                        }
1208                        packages = new String[size];
1209                        components = new ArrayList[size];
1210                        uids = new int[size];
1211                        int i = 0;  // filling out the above arrays
1212
1213                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1214                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1215                            Iterator<Map.Entry<String, ArrayList<String>>> it
1216                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1217                                            .entrySet().iterator();
1218                            while (it.hasNext() && i < size) {
1219                                Map.Entry<String, ArrayList<String>> ent = it.next();
1220                                packages[i] = ent.getKey();
1221                                components[i] = ent.getValue();
1222                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1223                                uids[i] = (ps != null)
1224                                        ? UserHandle.getUid(packageUserId, ps.appId)
1225                                        : -1;
1226                                i++;
1227                            }
1228                        }
1229                        size = i;
1230                        mPendingBroadcasts.clear();
1231                    }
1232                    // Send broadcasts
1233                    for (int i = 0; i < size; i++) {
1234                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1235                    }
1236                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1237                    break;
1238                }
1239                case START_CLEANING_PACKAGE: {
1240                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1241                    final String packageName = (String)msg.obj;
1242                    final int userId = msg.arg1;
1243                    final boolean andCode = msg.arg2 != 0;
1244                    synchronized (mPackages) {
1245                        if (userId == UserHandle.USER_ALL) {
1246                            int[] users = sUserManager.getUserIds();
1247                            for (int user : users) {
1248                                mSettings.addPackageToCleanLPw(
1249                                        new PackageCleanItem(user, packageName, andCode));
1250                            }
1251                        } else {
1252                            mSettings.addPackageToCleanLPw(
1253                                    new PackageCleanItem(userId, packageName, andCode));
1254                        }
1255                    }
1256                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1257                    startCleaningPackages();
1258                } break;
1259                case POST_INSTALL: {
1260                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1261                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1262                    mRunningInstalls.delete(msg.arg1);
1263                    boolean deleteOld = false;
1264
1265                    if (data != null) {
1266                        InstallArgs args = data.args;
1267                        PackageInstalledInfo res = data.res;
1268
1269                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1270                            res.removedInfo.sendBroadcast(false, true, false);
1271                            Bundle extras = new Bundle(1);
1272                            extras.putInt(Intent.EXTRA_UID, res.uid);
1273
1274                            // Now that we successfully installed the package, grant runtime
1275                            // permissions if requested before broadcasting the install.
1276                            if ((args.installFlags
1277                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1278                                grantRequestedRuntimePermissions(res.pkg,
1279                                        args.user.getIdentifier());
1280                            }
1281
1282                            // Determine the set of users who are adding this
1283                            // package for the first time vs. those who are seeing
1284                            // an update.
1285                            int[] firstUsers;
1286                            int[] updateUsers = new int[0];
1287                            if (res.origUsers == null || res.origUsers.length == 0) {
1288                                firstUsers = res.newUsers;
1289                            } else {
1290                                firstUsers = new int[0];
1291                                for (int i=0; i<res.newUsers.length; i++) {
1292                                    int user = res.newUsers[i];
1293                                    boolean isNew = true;
1294                                    for (int j=0; j<res.origUsers.length; j++) {
1295                                        if (res.origUsers[j] == user) {
1296                                            isNew = false;
1297                                            break;
1298                                        }
1299                                    }
1300                                    if (isNew) {
1301                                        int[] newFirst = new int[firstUsers.length+1];
1302                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1303                                                firstUsers.length);
1304                                        newFirst[firstUsers.length] = user;
1305                                        firstUsers = newFirst;
1306                                    } else {
1307                                        int[] newUpdate = new int[updateUsers.length+1];
1308                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1309                                                updateUsers.length);
1310                                        newUpdate[updateUsers.length] = user;
1311                                        updateUsers = newUpdate;
1312                                    }
1313                                }
1314                            }
1315                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1316                                    res.pkg.applicationInfo.packageName,
1317                                    extras, null, null, firstUsers);
1318                            final boolean update = res.removedInfo.removedPackage != null;
1319                            if (update) {
1320                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1321                            }
1322                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1323                                    res.pkg.applicationInfo.packageName,
1324                                    extras, null, null, updateUsers);
1325                            if (update) {
1326                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1327                                        res.pkg.applicationInfo.packageName,
1328                                        extras, null, null, updateUsers);
1329                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1330                                        null, null,
1331                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1332
1333                                // treat asec-hosted packages like removable media on upgrade
1334                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1335                                    if (DEBUG_INSTALL) {
1336                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1337                                                + " is ASEC-hosted -> AVAILABLE");
1338                                    }
1339                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1340                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1341                                    pkgList.add(res.pkg.applicationInfo.packageName);
1342                                    sendResourcesChangedBroadcast(true, true,
1343                                            pkgList,uidArray, null);
1344                                }
1345                            }
1346                            if (res.removedInfo.args != null) {
1347                                // Remove the replaced package's older resources safely now
1348                                deleteOld = true;
1349                            }
1350
1351                            // Log current value of "unknown sources" setting
1352                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1353                                getUnknownSourcesSettings());
1354                        }
1355                        // Force a gc to clear up things
1356                        Runtime.getRuntime().gc();
1357                        // We delete after a gc for applications  on sdcard.
1358                        if (deleteOld) {
1359                            synchronized (mInstallLock) {
1360                                res.removedInfo.args.doPostDeleteLI(true);
1361                            }
1362                        }
1363                        if (args.observer != null) {
1364                            try {
1365                                Bundle extras = extrasForInstallResult(res);
1366                                args.observer.onPackageInstalled(res.name, res.returnCode,
1367                                        res.returnMsg, extras);
1368                            } catch (RemoteException e) {
1369                                Slog.i(TAG, "Observer no longer exists.");
1370                            }
1371                        }
1372                    } else {
1373                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1374                    }
1375                } break;
1376                case UPDATED_MEDIA_STATUS: {
1377                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1378                    boolean reportStatus = msg.arg1 == 1;
1379                    boolean doGc = msg.arg2 == 1;
1380                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1381                    if (doGc) {
1382                        // Force a gc to clear up stale containers.
1383                        Runtime.getRuntime().gc();
1384                    }
1385                    if (msg.obj != null) {
1386                        @SuppressWarnings("unchecked")
1387                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1388                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1389                        // Unload containers
1390                        unloadAllContainers(args);
1391                    }
1392                    if (reportStatus) {
1393                        try {
1394                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1395                            PackageHelper.getMountService().finishMediaUpdate();
1396                        } catch (RemoteException e) {
1397                            Log.e(TAG, "MountService not running?");
1398                        }
1399                    }
1400                } break;
1401                case WRITE_SETTINGS: {
1402                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1403                    synchronized (mPackages) {
1404                        removeMessages(WRITE_SETTINGS);
1405                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1406                        mSettings.writeLPr();
1407                        mDirtyUsers.clear();
1408                    }
1409                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1410                } break;
1411                case WRITE_PACKAGE_RESTRICTIONS: {
1412                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1413                    synchronized (mPackages) {
1414                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1415                        for (int userId : mDirtyUsers) {
1416                            mSettings.writePackageRestrictionsLPr(userId);
1417                        }
1418                        mDirtyUsers.clear();
1419                    }
1420                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1421                } break;
1422                case CHECK_PENDING_VERIFICATION: {
1423                    final int verificationId = msg.arg1;
1424                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1425
1426                    if ((state != null) && !state.timeoutExtended()) {
1427                        final InstallArgs args = state.getInstallArgs();
1428                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1429
1430                        Slog.i(TAG, "Verification timed out for " + originUri);
1431                        mPendingVerification.remove(verificationId);
1432
1433                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1434
1435                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1436                            Slog.i(TAG, "Continuing with installation of " + originUri);
1437                            state.setVerifierResponse(Binder.getCallingUid(),
1438                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1439                            broadcastPackageVerified(verificationId, originUri,
1440                                    PackageManager.VERIFICATION_ALLOW,
1441                                    state.getInstallArgs().getUser());
1442                            try {
1443                                ret = args.copyApk(mContainerService, true);
1444                            } catch (RemoteException e) {
1445                                Slog.e(TAG, "Could not contact the ContainerService");
1446                            }
1447                        } else {
1448                            broadcastPackageVerified(verificationId, originUri,
1449                                    PackageManager.VERIFICATION_REJECT,
1450                                    state.getInstallArgs().getUser());
1451                        }
1452
1453                        processPendingInstall(args, ret);
1454                        mHandler.sendEmptyMessage(MCS_UNBIND);
1455                    }
1456                    break;
1457                }
1458                case PACKAGE_VERIFIED: {
1459                    final int verificationId = msg.arg1;
1460
1461                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1462                    if (state == null) {
1463                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1464                        break;
1465                    }
1466
1467                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1468
1469                    state.setVerifierResponse(response.callerUid, response.code);
1470
1471                    if (state.isVerificationComplete()) {
1472                        mPendingVerification.remove(verificationId);
1473
1474                        final InstallArgs args = state.getInstallArgs();
1475                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1476
1477                        int ret;
1478                        if (state.isInstallAllowed()) {
1479                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1480                            broadcastPackageVerified(verificationId, originUri,
1481                                    response.code, state.getInstallArgs().getUser());
1482                            try {
1483                                ret = args.copyApk(mContainerService, true);
1484                            } catch (RemoteException e) {
1485                                Slog.e(TAG, "Could not contact the ContainerService");
1486                            }
1487                        } else {
1488                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1489                        }
1490
1491                        processPendingInstall(args, ret);
1492
1493                        mHandler.sendEmptyMessage(MCS_UNBIND);
1494                    }
1495
1496                    break;
1497                }
1498                case START_INTENT_FILTER_VERIFICATIONS: {
1499                    int userId = msg.arg1;
1500                    int verifierUid = msg.arg2;
1501                    PackageParser.Package pkg = (PackageParser.Package)msg.obj;
1502
1503                    verifyIntentFiltersIfNeeded(userId, verifierUid, pkg);
1504                    break;
1505                }
1506                case INTENT_FILTER_VERIFIED: {
1507                    final int verificationId = msg.arg1;
1508
1509                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1510                            verificationId);
1511                    if (state == null) {
1512                        Slog.w(TAG, "Invalid IntentFilter verification token "
1513                                + verificationId + " received");
1514                        break;
1515                    }
1516
1517                    final int userId = state.getUserId();
1518
1519                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1520                            "Processing IntentFilter verification with token:"
1521                            + verificationId + " and userId:" + userId);
1522
1523                    final IntentFilterVerificationResponse response =
1524                            (IntentFilterVerificationResponse) msg.obj;
1525
1526                    state.setVerifierResponse(response.callerUid, response.code);
1527
1528                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1529                            "IntentFilter verification with token:" + verificationId
1530                            + " and userId:" + userId
1531                            + " is settings verifier response with response code:"
1532                            + response.code);
1533
1534                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1535                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1536                                + response.getFailedDomainsString());
1537                    }
1538
1539                    if (state.isVerificationComplete()) {
1540                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1541                    } else {
1542                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1543                                "IntentFilter verification with token:" + verificationId
1544                                + " was not said to be complete");
1545                    }
1546
1547                    break;
1548                }
1549            }
1550        }
1551    }
1552
1553    private StorageEventListener mStorageListener = new StorageEventListener() {
1554        @Override
1555        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1556            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1557                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1558                    // TODO: ensure that private directories exist for all active users
1559                    // TODO: remove user data whose serial number doesn't match
1560                    loadPrivatePackages(vol);
1561                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1562                    unloadPrivatePackages(vol);
1563                }
1564            }
1565
1566            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1567                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1568                    updateExternalMediaStatus(true, false);
1569                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1570                    updateExternalMediaStatus(false, false);
1571                }
1572            }
1573        }
1574
1575        @Override
1576        public void onVolumeForgotten(String fsUuid) {
1577            // TODO: remove all packages hosted on this uuid
1578        }
1579    };
1580
1581    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) {
1582        if (userId >= UserHandle.USER_OWNER) {
1583            grantRequestedRuntimePermissionsForUser(pkg, userId);
1584        } else if (userId == UserHandle.USER_ALL) {
1585            for (int someUserId : UserManagerService.getInstance().getUserIds()) {
1586                grantRequestedRuntimePermissionsForUser(pkg, someUserId);
1587            }
1588        }
1589
1590        // We could have touched GID membership, so flush out packages.list
1591        synchronized (mPackages) {
1592            mSettings.writePackageListLPr();
1593        }
1594    }
1595
1596    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) {
1597        SettingBase sb = (SettingBase) pkg.mExtras;
1598        if (sb == null) {
1599            return;
1600        }
1601
1602        PermissionsState permissionsState = sb.getPermissionsState();
1603
1604        for (String permission : pkg.requestedPermissions) {
1605            BasePermission bp = mSettings.mPermissions.get(permission);
1606            if (bp != null && bp.isRuntime()) {
1607                permissionsState.grantRuntimePermission(bp, userId);
1608            }
1609        }
1610    }
1611
1612    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1613        Bundle extras = null;
1614        switch (res.returnCode) {
1615            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1616                extras = new Bundle();
1617                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1618                        res.origPermission);
1619                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1620                        res.origPackage);
1621                break;
1622            }
1623            case PackageManager.INSTALL_SUCCEEDED: {
1624                extras = new Bundle();
1625                extras.putBoolean(Intent.EXTRA_REPLACING,
1626                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1627                break;
1628            }
1629        }
1630        return extras;
1631    }
1632
1633    void scheduleWriteSettingsLocked() {
1634        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1635            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1636        }
1637    }
1638
1639    void scheduleWritePackageRestrictionsLocked(int userId) {
1640        if (!sUserManager.exists(userId)) return;
1641        mDirtyUsers.add(userId);
1642        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1643            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1644        }
1645    }
1646
1647    public static PackageManagerService main(Context context, Installer installer,
1648            boolean factoryTest, boolean onlyCore) {
1649        PackageManagerService m = new PackageManagerService(context, installer,
1650                factoryTest, onlyCore);
1651        ServiceManager.addService("package", m);
1652        return m;
1653    }
1654
1655    static String[] splitString(String str, char sep) {
1656        int count = 1;
1657        int i = 0;
1658        while ((i=str.indexOf(sep, i)) >= 0) {
1659            count++;
1660            i++;
1661        }
1662
1663        String[] res = new String[count];
1664        i=0;
1665        count = 0;
1666        int lastI=0;
1667        while ((i=str.indexOf(sep, i)) >= 0) {
1668            res[count] = str.substring(lastI, i);
1669            count++;
1670            i++;
1671            lastI = i;
1672        }
1673        res[count] = str.substring(lastI, str.length());
1674        return res;
1675    }
1676
1677    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1678        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1679                Context.DISPLAY_SERVICE);
1680        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1681    }
1682
1683    public PackageManagerService(Context context, Installer installer,
1684            boolean factoryTest, boolean onlyCore) {
1685        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1686                SystemClock.uptimeMillis());
1687
1688        if (mSdkVersion <= 0) {
1689            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1690        }
1691
1692        mContext = context;
1693        mFactoryTest = factoryTest;
1694        mOnlyCore = onlyCore;
1695        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1696        mMetrics = new DisplayMetrics();
1697        mSettings = new Settings(mPackages);
1698        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1699                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1700        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1701                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1702        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1703                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1704        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1705                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1706        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1707                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1708        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1709                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1710
1711        // TODO: add a property to control this?
1712        long dexOptLRUThresholdInMinutes;
1713        if (mLazyDexOpt) {
1714            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1715        } else {
1716            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1717        }
1718        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1719
1720        String separateProcesses = SystemProperties.get("debug.separate_processes");
1721        if (separateProcesses != null && separateProcesses.length() > 0) {
1722            if ("*".equals(separateProcesses)) {
1723                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1724                mSeparateProcesses = null;
1725                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1726            } else {
1727                mDefParseFlags = 0;
1728                mSeparateProcesses = separateProcesses.split(",");
1729                Slog.w(TAG, "Running with debug.separate_processes: "
1730                        + separateProcesses);
1731            }
1732        } else {
1733            mDefParseFlags = 0;
1734            mSeparateProcesses = null;
1735        }
1736
1737        mInstaller = installer;
1738        mPackageDexOptimizer = new PackageDexOptimizer(this);
1739        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1740
1741        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1742                FgThread.get().getLooper());
1743
1744        getDefaultDisplayMetrics(context, mMetrics);
1745
1746        SystemConfig systemConfig = SystemConfig.getInstance();
1747        mGlobalGids = systemConfig.getGlobalGids();
1748        mSystemPermissions = systemConfig.getSystemPermissions();
1749        mAvailableFeatures = systemConfig.getAvailableFeatures();
1750
1751        synchronized (mInstallLock) {
1752        // writer
1753        synchronized (mPackages) {
1754            mHandlerThread = new ServiceThread(TAG,
1755                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1756            mHandlerThread.start();
1757            mHandler = new PackageHandler(mHandlerThread.getLooper());
1758            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1759
1760            File dataDir = Environment.getDataDirectory();
1761            mAppDataDir = new File(dataDir, "data");
1762            mAppInstallDir = new File(dataDir, "app");
1763            mAppLib32InstallDir = new File(dataDir, "app-lib");
1764            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1765            mUserAppDataDir = new File(dataDir, "user");
1766            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1767
1768            sUserManager = new UserManagerService(context, this,
1769                    mInstallLock, mPackages);
1770
1771            // Propagate permission configuration in to package manager.
1772            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1773                    = systemConfig.getPermissions();
1774            for (int i=0; i<permConfig.size(); i++) {
1775                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1776                BasePermission bp = mSettings.mPermissions.get(perm.name);
1777                if (bp == null) {
1778                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1779                    mSettings.mPermissions.put(perm.name, bp);
1780                }
1781                if (perm.gids != null) {
1782                    bp.setGids(perm.gids, perm.perUser);
1783                }
1784            }
1785
1786            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1787            for (int i=0; i<libConfig.size(); i++) {
1788                mSharedLibraries.put(libConfig.keyAt(i),
1789                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1790            }
1791
1792            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1793
1794            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1795                    mSdkVersion, mOnlyCore);
1796
1797            String customResolverActivity = Resources.getSystem().getString(
1798                    R.string.config_customResolverActivity);
1799            if (TextUtils.isEmpty(customResolverActivity)) {
1800                customResolverActivity = null;
1801            } else {
1802                mCustomResolverComponentName = ComponentName.unflattenFromString(
1803                        customResolverActivity);
1804            }
1805
1806            long startTime = SystemClock.uptimeMillis();
1807
1808            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1809                    startTime);
1810
1811            // Set flag to monitor and not change apk file paths when
1812            // scanning install directories.
1813            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1814
1815            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1816
1817            /**
1818             * Add everything in the in the boot class path to the
1819             * list of process files because dexopt will have been run
1820             * if necessary during zygote startup.
1821             */
1822            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1823            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1824
1825            if (bootClassPath != null) {
1826                String[] bootClassPathElements = splitString(bootClassPath, ':');
1827                for (String element : bootClassPathElements) {
1828                    alreadyDexOpted.add(element);
1829                }
1830            } else {
1831                Slog.w(TAG, "No BOOTCLASSPATH found!");
1832            }
1833
1834            if (systemServerClassPath != null) {
1835                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1836                for (String element : systemServerClassPathElements) {
1837                    alreadyDexOpted.add(element);
1838                }
1839            } else {
1840                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1841            }
1842
1843            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1844            final String[] dexCodeInstructionSets =
1845                    getDexCodeInstructionSets(
1846                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1847
1848            /**
1849             * Ensure all external libraries have had dexopt run on them.
1850             */
1851            if (mSharedLibraries.size() > 0) {
1852                // NOTE: For now, we're compiling these system "shared libraries"
1853                // (and framework jars) into all available architectures. It's possible
1854                // to compile them only when we come across an app that uses them (there's
1855                // already logic for that in scanPackageLI) but that adds some complexity.
1856                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1857                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1858                        final String lib = libEntry.path;
1859                        if (lib == null) {
1860                            continue;
1861                        }
1862
1863                        try {
1864                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1865                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1866                                alreadyDexOpted.add(lib);
1867                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1868                            }
1869                        } catch (FileNotFoundException e) {
1870                            Slog.w(TAG, "Library not found: " + lib);
1871                        } catch (IOException e) {
1872                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1873                                    + e.getMessage());
1874                        }
1875                    }
1876                }
1877            }
1878
1879            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1880
1881            // Gross hack for now: we know this file doesn't contain any
1882            // code, so don't dexopt it to avoid the resulting log spew.
1883            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1884
1885            // Gross hack for now: we know this file is only part of
1886            // the boot class path for art, so don't dexopt it to
1887            // avoid the resulting log spew.
1888            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1889
1890            /**
1891             * There are a number of commands implemented in Java, which
1892             * we currently need to do the dexopt on so that they can be
1893             * run from a non-root shell.
1894             */
1895            String[] frameworkFiles = frameworkDir.list();
1896            if (frameworkFiles != null) {
1897                // TODO: We could compile these only for the most preferred ABI. We should
1898                // first double check that the dex files for these commands are not referenced
1899                // by other system apps.
1900                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1901                    for (int i=0; i<frameworkFiles.length; i++) {
1902                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1903                        String path = libPath.getPath();
1904                        // Skip the file if we already did it.
1905                        if (alreadyDexOpted.contains(path)) {
1906                            continue;
1907                        }
1908                        // Skip the file if it is not a type we want to dexopt.
1909                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1910                            continue;
1911                        }
1912                        try {
1913                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
1914                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1915                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1916                            }
1917                        } catch (FileNotFoundException e) {
1918                            Slog.w(TAG, "Jar not found: " + path);
1919                        } catch (IOException e) {
1920                            Slog.w(TAG, "Exception reading jar: " + path, e);
1921                        }
1922                    }
1923                }
1924            }
1925
1926            // Collect vendor overlay packages.
1927            // (Do this before scanning any apps.)
1928            // For security and version matching reason, only consider
1929            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1930            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1931            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1932                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1933
1934            // Find base frameworks (resource packages without code).
1935            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1936                    | PackageParser.PARSE_IS_SYSTEM_DIR
1937                    | PackageParser.PARSE_IS_PRIVILEGED,
1938                    scanFlags | SCAN_NO_DEX, 0);
1939
1940            // Collected privileged system packages.
1941            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1942            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1943                    | PackageParser.PARSE_IS_SYSTEM_DIR
1944                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1945
1946            // Collect ordinary system packages.
1947            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
1948            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1949                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1950
1951            // Collect all vendor packages.
1952            File vendorAppDir = new File("/vendor/app");
1953            try {
1954                vendorAppDir = vendorAppDir.getCanonicalFile();
1955            } catch (IOException e) {
1956                // failed to look up canonical path, continue with original one
1957            }
1958            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1959                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1960
1961            // Collect all OEM packages.
1962            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
1963            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1964                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1965
1966            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1967            mInstaller.moveFiles();
1968
1969            // Prune any system packages that no longer exist.
1970            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1971            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
1972            if (!mOnlyCore) {
1973                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1974                while (psit.hasNext()) {
1975                    PackageSetting ps = psit.next();
1976
1977                    /*
1978                     * If this is not a system app, it can't be a
1979                     * disable system app.
1980                     */
1981                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1982                        continue;
1983                    }
1984
1985                    /*
1986                     * If the package is scanned, it's not erased.
1987                     */
1988                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1989                    if (scannedPkg != null) {
1990                        /*
1991                         * If the system app is both scanned and in the
1992                         * disabled packages list, then it must have been
1993                         * added via OTA. Remove it from the currently
1994                         * scanned package so the previously user-installed
1995                         * application can be scanned.
1996                         */
1997                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1998                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
1999                                    + ps.name + "; removing system app.  Last known codePath="
2000                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2001                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2002                                    + scannedPkg.mVersionCode);
2003                            removePackageLI(ps, true);
2004                            expectingBetter.put(ps.name, ps.codePath);
2005                        }
2006
2007                        continue;
2008                    }
2009
2010                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2011                        psit.remove();
2012                        logCriticalInfo(Log.WARN, "System package " + ps.name
2013                                + " no longer exists; wiping its data");
2014                        removeDataDirsLI(null, ps.name);
2015                    } else {
2016                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2017                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2018                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2019                        }
2020                    }
2021                }
2022            }
2023
2024            //look for any incomplete package installations
2025            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2026            //clean up list
2027            for(int i = 0; i < deletePkgsList.size(); i++) {
2028                //clean up here
2029                cleanupInstallFailedPackage(deletePkgsList.get(i));
2030            }
2031            //delete tmp files
2032            deleteTempPackageFiles();
2033
2034            // Remove any shared userIDs that have no associated packages
2035            mSettings.pruneSharedUsersLPw();
2036
2037            if (!mOnlyCore) {
2038                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2039                        SystemClock.uptimeMillis());
2040                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2041
2042                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2043                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2044
2045                /**
2046                 * Remove disable package settings for any updated system
2047                 * apps that were removed via an OTA. If they're not a
2048                 * previously-updated app, remove them completely.
2049                 * Otherwise, just revoke their system-level permissions.
2050                 */
2051                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2052                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2053                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2054
2055                    String msg;
2056                    if (deletedPkg == null) {
2057                        msg = "Updated system package " + deletedAppName
2058                                + " no longer exists; wiping its data";
2059                        removeDataDirsLI(null, deletedAppName);
2060                    } else {
2061                        msg = "Updated system app + " + deletedAppName
2062                                + " no longer present; removing system privileges for "
2063                                + deletedAppName;
2064
2065                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2066
2067                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2068                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2069                    }
2070                    logCriticalInfo(Log.WARN, msg);
2071                }
2072
2073                /**
2074                 * Make sure all system apps that we expected to appear on
2075                 * the userdata partition actually showed up. If they never
2076                 * appeared, crawl back and revive the system version.
2077                 */
2078                for (int i = 0; i < expectingBetter.size(); i++) {
2079                    final String packageName = expectingBetter.keyAt(i);
2080                    if (!mPackages.containsKey(packageName)) {
2081                        final File scanFile = expectingBetter.valueAt(i);
2082
2083                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2084                                + " but never showed up; reverting to system");
2085
2086                        final int reparseFlags;
2087                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2088                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2089                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2090                                    | PackageParser.PARSE_IS_PRIVILEGED;
2091                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2092                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2093                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2094                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2095                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2096                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2097                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2098                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2099                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2100                        } else {
2101                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2102                            continue;
2103                        }
2104
2105                        mSettings.enableSystemPackageLPw(packageName);
2106
2107                        try {
2108                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2109                        } catch (PackageManagerException e) {
2110                            Slog.e(TAG, "Failed to parse original system package: "
2111                                    + e.getMessage());
2112                        }
2113                    }
2114                }
2115            }
2116
2117            // Now that we know all of the shared libraries, update all clients to have
2118            // the correct library paths.
2119            updateAllSharedLibrariesLPw();
2120
2121            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2122                // NOTE: We ignore potential failures here during a system scan (like
2123                // the rest of the commands above) because there's precious little we
2124                // can do about it. A settings error is reported, though.
2125                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2126                        false /* force dexopt */, false /* defer dexopt */);
2127            }
2128
2129            // Now that we know all the packages we are keeping,
2130            // read and update their last usage times.
2131            mPackageUsage.readLP();
2132
2133            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2134                    SystemClock.uptimeMillis());
2135            Slog.i(TAG, "Time to scan packages: "
2136                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2137                    + " seconds");
2138
2139            // If the platform SDK has changed since the last time we booted,
2140            // we need to re-grant app permission to catch any new ones that
2141            // appear.  This is really a hack, and means that apps can in some
2142            // cases get permissions that the user didn't initially explicitly
2143            // allow...  it would be nice to have some better way to handle
2144            // this situation.
2145            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
2146                    != mSdkVersion;
2147            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
2148                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
2149                    + "; regranting permissions for internal storage");
2150            mSettings.mInternalSdkPlatform = mSdkVersion;
2151
2152            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
2153                    | (regrantPermissions
2154                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
2155                            : 0));
2156
2157            // If this is the first boot, and it is a normal boot, then
2158            // we need to initialize the default preferred apps.
2159            if (!mRestoredSettings && !onlyCore) {
2160                mSettings.readDefaultPreferredAppsLPw(this, 0);
2161            }
2162
2163            // If this is first boot after an OTA, and a normal boot, then
2164            // we need to clear code cache directories.
2165            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
2166            if (mIsUpgrade && !onlyCore) {
2167                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2168                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2169                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2170                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2171                }
2172                mSettings.mFingerprint = Build.FINGERPRINT;
2173            }
2174
2175            primeDomainVerificationsLPw();
2176            checkDefaultBrowser();
2177
2178            // All the changes are done during package scanning.
2179            mSettings.updateInternalDatabaseVersion();
2180
2181            // can downgrade to reader
2182            mSettings.writeLPr();
2183
2184            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2185                    SystemClock.uptimeMillis());
2186
2187            mRequiredVerifierPackage = getRequiredVerifierLPr();
2188
2189            mInstallerService = new PackageInstallerService(context, this);
2190
2191            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2192            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2193                    mIntentFilterVerifierComponent);
2194
2195        } // synchronized (mPackages)
2196        } // synchronized (mInstallLock)
2197
2198        // Now after opening every single application zip, make sure they
2199        // are all flushed.  Not really needed, but keeps things nice and
2200        // tidy.
2201        Runtime.getRuntime().gc();
2202    }
2203
2204    @Override
2205    public boolean isFirstBoot() {
2206        return !mRestoredSettings;
2207    }
2208
2209    @Override
2210    public boolean isOnlyCoreApps() {
2211        return mOnlyCore;
2212    }
2213
2214    @Override
2215    public boolean isUpgrade() {
2216        return mIsUpgrade;
2217    }
2218
2219    private String getRequiredVerifierLPr() {
2220        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2221        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2222                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2223
2224        String requiredVerifier = null;
2225
2226        final int N = receivers.size();
2227        for (int i = 0; i < N; i++) {
2228            final ResolveInfo info = receivers.get(i);
2229
2230            if (info.activityInfo == null) {
2231                continue;
2232            }
2233
2234            final String packageName = info.activityInfo.packageName;
2235
2236            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2237                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2238                continue;
2239            }
2240
2241            if (requiredVerifier != null) {
2242                throw new RuntimeException("There can be only one required verifier");
2243            }
2244
2245            requiredVerifier = packageName;
2246        }
2247
2248        return requiredVerifier;
2249    }
2250
2251    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2252        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2253        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2254                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2255
2256        ComponentName verifierComponentName = null;
2257
2258        int priority = -1000;
2259        final int N = receivers.size();
2260        for (int i = 0; i < N; i++) {
2261            final ResolveInfo info = receivers.get(i);
2262
2263            if (info.activityInfo == null) {
2264                continue;
2265            }
2266
2267            final String packageName = info.activityInfo.packageName;
2268
2269            final PackageSetting ps = mSettings.mPackages.get(packageName);
2270            if (ps == null) {
2271                continue;
2272            }
2273
2274            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2275                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2276                continue;
2277            }
2278
2279            // Select the IntentFilterVerifier with the highest priority
2280            if (priority < info.priority) {
2281                priority = info.priority;
2282                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2283                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2284                        + verifierComponentName + " with priority: " + info.priority);
2285            }
2286        }
2287
2288        return verifierComponentName;
2289    }
2290
2291    private void primeDomainVerificationsLPw() {
2292        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications");
2293        boolean updated = false;
2294        ArraySet<String> allHostsSet = new ArraySet<>();
2295        for (PackageParser.Package pkg : mPackages.values()) {
2296            final String packageName = pkg.packageName;
2297            if (!hasDomainURLs(pkg)) {
2298                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " +
2299                            "package with no domain URLs: " + packageName);
2300                continue;
2301            }
2302            if (!pkg.isSystemApp()) {
2303                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2304                        "No priming domain verifications for a non system package : " +
2305                                packageName);
2306                continue;
2307            }
2308            for (PackageParser.Activity a : pkg.activities) {
2309                for (ActivityIntentInfo filter : a.intents) {
2310                    if (hasValidDomains(filter)) {
2311                        allHostsSet.addAll(filter.getHostsList());
2312                    }
2313                }
2314            }
2315            if (allHostsSet.size() == 0) {
2316                allHostsSet.add("*");
2317            }
2318            ArrayList<String> allHostsList = new ArrayList<>(allHostsSet);
2319            IntentFilterVerificationInfo ivi =
2320                    mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList);
2321            if (ivi != null) {
2322                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2323                        "Priming domain verifications for package: " + packageName +
2324                        " with hosts:" + ivi.getDomainsString());
2325                ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
2326                updated = true;
2327            }
2328            else {
2329                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2330                        "No priming domain verifications for package: " + packageName);
2331            }
2332            allHostsSet.clear();
2333        }
2334        if (updated) {
2335            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2336                    "Will need to write primed domain verifications");
2337        }
2338        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications");
2339    }
2340
2341    private void checkDefaultBrowser() {
2342        final int myUserId = UserHandle.myUserId();
2343        final String packageName = getDefaultBrowserPackageName(myUserId);
2344        PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2345        if (info == null) {
2346            Slog.w(TAG, "Clearing default Browser as its package is no more installed: " +
2347                    packageName);
2348            setDefaultBrowserPackageName(null, myUserId);
2349        }
2350    }
2351
2352    @Override
2353    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2354            throws RemoteException {
2355        try {
2356            return super.onTransact(code, data, reply, flags);
2357        } catch (RuntimeException e) {
2358            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2359                Slog.wtf(TAG, "Package Manager Crash", e);
2360            }
2361            throw e;
2362        }
2363    }
2364
2365    void cleanupInstallFailedPackage(PackageSetting ps) {
2366        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2367
2368        removeDataDirsLI(ps.volumeUuid, ps.name);
2369        if (ps.codePath != null) {
2370            if (ps.codePath.isDirectory()) {
2371                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2372            } else {
2373                ps.codePath.delete();
2374            }
2375        }
2376        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2377            if (ps.resourcePath.isDirectory()) {
2378                FileUtils.deleteContents(ps.resourcePath);
2379            }
2380            ps.resourcePath.delete();
2381        }
2382        mSettings.removePackageLPw(ps.name);
2383    }
2384
2385    static int[] appendInts(int[] cur, int[] add) {
2386        if (add == null) return cur;
2387        if (cur == null) return add;
2388        final int N = add.length;
2389        for (int i=0; i<N; i++) {
2390            cur = appendInt(cur, add[i]);
2391        }
2392        return cur;
2393    }
2394
2395    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2396        if (!sUserManager.exists(userId)) return null;
2397        final PackageSetting ps = (PackageSetting) p.mExtras;
2398        if (ps == null) {
2399            return null;
2400        }
2401
2402        final PermissionsState permissionsState = ps.getPermissionsState();
2403
2404        final int[] gids = permissionsState.computeGids(userId);
2405        final Set<String> permissions = permissionsState.getPermissions(userId);
2406        final PackageUserState state = ps.readUserState(userId);
2407
2408        return PackageParser.generatePackageInfo(p, gids, flags,
2409                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2410    }
2411
2412    @Override
2413    public boolean isPackageFrozen(String packageName) {
2414        synchronized (mPackages) {
2415            final PackageSetting ps = mSettings.mPackages.get(packageName);
2416            if (ps != null) {
2417                return ps.frozen;
2418            }
2419        }
2420        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2421        return true;
2422    }
2423
2424    @Override
2425    public boolean isPackageAvailable(String packageName, int userId) {
2426        if (!sUserManager.exists(userId)) return false;
2427        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2428        synchronized (mPackages) {
2429            PackageParser.Package p = mPackages.get(packageName);
2430            if (p != null) {
2431                final PackageSetting ps = (PackageSetting) p.mExtras;
2432                if (ps != null) {
2433                    final PackageUserState state = ps.readUserState(userId);
2434                    if (state != null) {
2435                        return PackageParser.isAvailable(state);
2436                    }
2437                }
2438            }
2439        }
2440        return false;
2441    }
2442
2443    @Override
2444    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2445        if (!sUserManager.exists(userId)) return null;
2446        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2447        // reader
2448        synchronized (mPackages) {
2449            PackageParser.Package p = mPackages.get(packageName);
2450            if (DEBUG_PACKAGE_INFO)
2451                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2452            if (p != null) {
2453                return generatePackageInfo(p, flags, userId);
2454            }
2455            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2456                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2457            }
2458        }
2459        return null;
2460    }
2461
2462    @Override
2463    public String[] currentToCanonicalPackageNames(String[] names) {
2464        String[] out = new String[names.length];
2465        // reader
2466        synchronized (mPackages) {
2467            for (int i=names.length-1; i>=0; i--) {
2468                PackageSetting ps = mSettings.mPackages.get(names[i]);
2469                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2470            }
2471        }
2472        return out;
2473    }
2474
2475    @Override
2476    public String[] canonicalToCurrentPackageNames(String[] names) {
2477        String[] out = new String[names.length];
2478        // reader
2479        synchronized (mPackages) {
2480            for (int i=names.length-1; i>=0; i--) {
2481                String cur = mSettings.mRenamedPackages.get(names[i]);
2482                out[i] = cur != null ? cur : names[i];
2483            }
2484        }
2485        return out;
2486    }
2487
2488    @Override
2489    public int getPackageUid(String packageName, int userId) {
2490        if (!sUserManager.exists(userId)) return -1;
2491        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2492
2493        // reader
2494        synchronized (mPackages) {
2495            PackageParser.Package p = mPackages.get(packageName);
2496            if(p != null) {
2497                return UserHandle.getUid(userId, p.applicationInfo.uid);
2498            }
2499            PackageSetting ps = mSettings.mPackages.get(packageName);
2500            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2501                return -1;
2502            }
2503            p = ps.pkg;
2504            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2505        }
2506    }
2507
2508    @Override
2509    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2510        if (!sUserManager.exists(userId)) {
2511            return null;
2512        }
2513
2514        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2515                "getPackageGids");
2516
2517        // reader
2518        synchronized (mPackages) {
2519            PackageParser.Package p = mPackages.get(packageName);
2520            if (DEBUG_PACKAGE_INFO) {
2521                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2522            }
2523            if (p != null) {
2524                PackageSetting ps = (PackageSetting) p.mExtras;
2525                return ps.getPermissionsState().computeGids(userId);
2526            }
2527        }
2528
2529        return null;
2530    }
2531
2532    static PermissionInfo generatePermissionInfo(
2533            BasePermission bp, int flags) {
2534        if (bp.perm != null) {
2535            return PackageParser.generatePermissionInfo(bp.perm, flags);
2536        }
2537        PermissionInfo pi = new PermissionInfo();
2538        pi.name = bp.name;
2539        pi.packageName = bp.sourcePackage;
2540        pi.nonLocalizedLabel = bp.name;
2541        pi.protectionLevel = bp.protectionLevel;
2542        return pi;
2543    }
2544
2545    @Override
2546    public PermissionInfo getPermissionInfo(String name, int flags) {
2547        // reader
2548        synchronized (mPackages) {
2549            final BasePermission p = mSettings.mPermissions.get(name);
2550            if (p != null) {
2551                return generatePermissionInfo(p, flags);
2552            }
2553            return null;
2554        }
2555    }
2556
2557    @Override
2558    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2559        // reader
2560        synchronized (mPackages) {
2561            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2562            for (BasePermission p : mSettings.mPermissions.values()) {
2563                if (group == null) {
2564                    if (p.perm == null || p.perm.info.group == null) {
2565                        out.add(generatePermissionInfo(p, flags));
2566                    }
2567                } else {
2568                    if (p.perm != null && group.equals(p.perm.info.group)) {
2569                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2570                    }
2571                }
2572            }
2573
2574            if (out.size() > 0) {
2575                return out;
2576            }
2577            return mPermissionGroups.containsKey(group) ? out : null;
2578        }
2579    }
2580
2581    @Override
2582    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2583        // reader
2584        synchronized (mPackages) {
2585            return PackageParser.generatePermissionGroupInfo(
2586                    mPermissionGroups.get(name), flags);
2587        }
2588    }
2589
2590    @Override
2591    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2592        // reader
2593        synchronized (mPackages) {
2594            final int N = mPermissionGroups.size();
2595            ArrayList<PermissionGroupInfo> out
2596                    = new ArrayList<PermissionGroupInfo>(N);
2597            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2598                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2599            }
2600            return out;
2601        }
2602    }
2603
2604    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2605            int userId) {
2606        if (!sUserManager.exists(userId)) return null;
2607        PackageSetting ps = mSettings.mPackages.get(packageName);
2608        if (ps != null) {
2609            if (ps.pkg == null) {
2610                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2611                        flags, userId);
2612                if (pInfo != null) {
2613                    return pInfo.applicationInfo;
2614                }
2615                return null;
2616            }
2617            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2618                    ps.readUserState(userId), userId);
2619        }
2620        return null;
2621    }
2622
2623    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2624            int userId) {
2625        if (!sUserManager.exists(userId)) return null;
2626        PackageSetting ps = mSettings.mPackages.get(packageName);
2627        if (ps != null) {
2628            PackageParser.Package pkg = ps.pkg;
2629            if (pkg == null) {
2630                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2631                    return null;
2632                }
2633                // Only data remains, so we aren't worried about code paths
2634                pkg = new PackageParser.Package(packageName);
2635                pkg.applicationInfo.packageName = packageName;
2636                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2637                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2638                pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid,
2639                        packageName, userId).getAbsolutePath();
2640                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2641                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2642            }
2643            return generatePackageInfo(pkg, flags, userId);
2644        }
2645        return null;
2646    }
2647
2648    @Override
2649    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2650        if (!sUserManager.exists(userId)) return null;
2651        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2652        // writer
2653        synchronized (mPackages) {
2654            PackageParser.Package p = mPackages.get(packageName);
2655            if (DEBUG_PACKAGE_INFO) Log.v(
2656                    TAG, "getApplicationInfo " + packageName
2657                    + ": " + p);
2658            if (p != null) {
2659                PackageSetting ps = mSettings.mPackages.get(packageName);
2660                if (ps == null) return null;
2661                // Note: isEnabledLP() does not apply here - always return info
2662                return PackageParser.generateApplicationInfo(
2663                        p, flags, ps.readUserState(userId), userId);
2664            }
2665            if ("android".equals(packageName)||"system".equals(packageName)) {
2666                return mAndroidApplication;
2667            }
2668            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2669                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2670            }
2671        }
2672        return null;
2673    }
2674
2675    @Override
2676    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2677            final IPackageDataObserver observer) {
2678        mContext.enforceCallingOrSelfPermission(
2679                android.Manifest.permission.CLEAR_APP_CACHE, null);
2680        // Queue up an async operation since clearing cache may take a little while.
2681        mHandler.post(new Runnable() {
2682            public void run() {
2683                mHandler.removeCallbacks(this);
2684                int retCode = -1;
2685                synchronized (mInstallLock) {
2686                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2687                    if (retCode < 0) {
2688                        Slog.w(TAG, "Couldn't clear application caches");
2689                    }
2690                }
2691                if (observer != null) {
2692                    try {
2693                        observer.onRemoveCompleted(null, (retCode >= 0));
2694                    } catch (RemoteException e) {
2695                        Slog.w(TAG, "RemoveException when invoking call back");
2696                    }
2697                }
2698            }
2699        });
2700    }
2701
2702    @Override
2703    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2704            final IntentSender pi) {
2705        mContext.enforceCallingOrSelfPermission(
2706                android.Manifest.permission.CLEAR_APP_CACHE, null);
2707        // Queue up an async operation since clearing cache may take a little while.
2708        mHandler.post(new Runnable() {
2709            public void run() {
2710                mHandler.removeCallbacks(this);
2711                int retCode = -1;
2712                synchronized (mInstallLock) {
2713                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2714                    if (retCode < 0) {
2715                        Slog.w(TAG, "Couldn't clear application caches");
2716                    }
2717                }
2718                if(pi != null) {
2719                    try {
2720                        // Callback via pending intent
2721                        int code = (retCode >= 0) ? 1 : 0;
2722                        pi.sendIntent(null, code, null,
2723                                null, null);
2724                    } catch (SendIntentException e1) {
2725                        Slog.i(TAG, "Failed to send pending intent");
2726                    }
2727                }
2728            }
2729        });
2730    }
2731
2732    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2733        synchronized (mInstallLock) {
2734            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2735                throw new IOException("Failed to free enough space");
2736            }
2737        }
2738    }
2739
2740    @Override
2741    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2742        if (!sUserManager.exists(userId)) return null;
2743        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2744        synchronized (mPackages) {
2745            PackageParser.Activity a = mActivities.mActivities.get(component);
2746
2747            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2748            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2749                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2750                if (ps == null) return null;
2751                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2752                        userId);
2753            }
2754            if (mResolveComponentName.equals(component)) {
2755                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2756                        new PackageUserState(), userId);
2757            }
2758        }
2759        return null;
2760    }
2761
2762    @Override
2763    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2764            String resolvedType) {
2765        synchronized (mPackages) {
2766            PackageParser.Activity a = mActivities.mActivities.get(component);
2767            if (a == null) {
2768                return false;
2769            }
2770            for (int i=0; i<a.intents.size(); i++) {
2771                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2772                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2773                    return true;
2774                }
2775            }
2776            return false;
2777        }
2778    }
2779
2780    @Override
2781    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2782        if (!sUserManager.exists(userId)) return null;
2783        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2784        synchronized (mPackages) {
2785            PackageParser.Activity a = mReceivers.mActivities.get(component);
2786            if (DEBUG_PACKAGE_INFO) Log.v(
2787                TAG, "getReceiverInfo " + component + ": " + a);
2788            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2789                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2790                if (ps == null) return null;
2791                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2792                        userId);
2793            }
2794        }
2795        return null;
2796    }
2797
2798    @Override
2799    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2800        if (!sUserManager.exists(userId)) return null;
2801        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2802        synchronized (mPackages) {
2803            PackageParser.Service s = mServices.mServices.get(component);
2804            if (DEBUG_PACKAGE_INFO) Log.v(
2805                TAG, "getServiceInfo " + component + ": " + s);
2806            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2807                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2808                if (ps == null) return null;
2809                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2810                        userId);
2811            }
2812        }
2813        return null;
2814    }
2815
2816    @Override
2817    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2818        if (!sUserManager.exists(userId)) return null;
2819        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2820        synchronized (mPackages) {
2821            PackageParser.Provider p = mProviders.mProviders.get(component);
2822            if (DEBUG_PACKAGE_INFO) Log.v(
2823                TAG, "getProviderInfo " + component + ": " + p);
2824            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2825                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2826                if (ps == null) return null;
2827                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2828                        userId);
2829            }
2830        }
2831        return null;
2832    }
2833
2834    @Override
2835    public String[] getSystemSharedLibraryNames() {
2836        Set<String> libSet;
2837        synchronized (mPackages) {
2838            libSet = mSharedLibraries.keySet();
2839            int size = libSet.size();
2840            if (size > 0) {
2841                String[] libs = new String[size];
2842                libSet.toArray(libs);
2843                return libs;
2844            }
2845        }
2846        return null;
2847    }
2848
2849    /**
2850     * @hide
2851     */
2852    PackageParser.Package findSharedNonSystemLibrary(String libName) {
2853        synchronized (mPackages) {
2854            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
2855            if (lib != null && lib.apk != null) {
2856                return mPackages.get(lib.apk);
2857            }
2858        }
2859        return null;
2860    }
2861
2862    @Override
2863    public FeatureInfo[] getSystemAvailableFeatures() {
2864        Collection<FeatureInfo> featSet;
2865        synchronized (mPackages) {
2866            featSet = mAvailableFeatures.values();
2867            int size = featSet.size();
2868            if (size > 0) {
2869                FeatureInfo[] features = new FeatureInfo[size+1];
2870                featSet.toArray(features);
2871                FeatureInfo fi = new FeatureInfo();
2872                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2873                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2874                features[size] = fi;
2875                return features;
2876            }
2877        }
2878        return null;
2879    }
2880
2881    @Override
2882    public boolean hasSystemFeature(String name) {
2883        synchronized (mPackages) {
2884            return mAvailableFeatures.containsKey(name);
2885        }
2886    }
2887
2888    private void checkValidCaller(int uid, int userId) {
2889        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2890            return;
2891
2892        throw new SecurityException("Caller uid=" + uid
2893                + " is not privileged to communicate with user=" + userId);
2894    }
2895
2896    @Override
2897    public int checkPermission(String permName, String pkgName, int userId) {
2898        if (!sUserManager.exists(userId)) {
2899            return PackageManager.PERMISSION_DENIED;
2900        }
2901
2902        synchronized (mPackages) {
2903            final PackageParser.Package p = mPackages.get(pkgName);
2904            if (p != null && p.mExtras != null) {
2905                final PackageSetting ps = (PackageSetting) p.mExtras;
2906                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2907                    return PackageManager.PERMISSION_GRANTED;
2908                }
2909            }
2910        }
2911
2912        return PackageManager.PERMISSION_DENIED;
2913    }
2914
2915    @Override
2916    public int checkUidPermission(String permName, int uid) {
2917        final int userId = UserHandle.getUserId(uid);
2918
2919        if (!sUserManager.exists(userId)) {
2920            return PackageManager.PERMISSION_DENIED;
2921        }
2922
2923        synchronized (mPackages) {
2924            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2925            if (obj != null) {
2926                final SettingBase ps = (SettingBase) obj;
2927                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2928                    return PackageManager.PERMISSION_GRANTED;
2929                }
2930            } else {
2931                ArraySet<String> perms = mSystemPermissions.get(uid);
2932                if (perms != null && perms.contains(permName)) {
2933                    return PackageManager.PERMISSION_GRANTED;
2934                }
2935            }
2936        }
2937
2938        return PackageManager.PERMISSION_DENIED;
2939    }
2940
2941    /**
2942     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2943     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2944     * @param checkShell TODO(yamasani):
2945     * @param message the message to log on security exception
2946     */
2947    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2948            boolean checkShell, String message) {
2949        if (userId < 0) {
2950            throw new IllegalArgumentException("Invalid userId " + userId);
2951        }
2952        if (checkShell) {
2953            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
2954        }
2955        if (userId == UserHandle.getUserId(callingUid)) return;
2956        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2957            if (requireFullPermission) {
2958                mContext.enforceCallingOrSelfPermission(
2959                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2960            } else {
2961                try {
2962                    mContext.enforceCallingOrSelfPermission(
2963                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2964                } catch (SecurityException se) {
2965                    mContext.enforceCallingOrSelfPermission(
2966                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2967                }
2968            }
2969        }
2970    }
2971
2972    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
2973        if (callingUid == Process.SHELL_UID) {
2974            if (userHandle >= 0
2975                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
2976                throw new SecurityException("Shell does not have permission to access user "
2977                        + userHandle);
2978            } else if (userHandle < 0) {
2979                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
2980                        + Debug.getCallers(3));
2981            }
2982        }
2983    }
2984
2985    private BasePermission findPermissionTreeLP(String permName) {
2986        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2987            if (permName.startsWith(bp.name) &&
2988                    permName.length() > bp.name.length() &&
2989                    permName.charAt(bp.name.length()) == '.') {
2990                return bp;
2991            }
2992        }
2993        return null;
2994    }
2995
2996    private BasePermission checkPermissionTreeLP(String permName) {
2997        if (permName != null) {
2998            BasePermission bp = findPermissionTreeLP(permName);
2999            if (bp != null) {
3000                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3001                    return bp;
3002                }
3003                throw new SecurityException("Calling uid "
3004                        + Binder.getCallingUid()
3005                        + " is not allowed to add to permission tree "
3006                        + bp.name + " owned by uid " + bp.uid);
3007            }
3008        }
3009        throw new SecurityException("No permission tree found for " + permName);
3010    }
3011
3012    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3013        if (s1 == null) {
3014            return s2 == null;
3015        }
3016        if (s2 == null) {
3017            return false;
3018        }
3019        if (s1.getClass() != s2.getClass()) {
3020            return false;
3021        }
3022        return s1.equals(s2);
3023    }
3024
3025    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3026        if (pi1.icon != pi2.icon) return false;
3027        if (pi1.logo != pi2.logo) return false;
3028        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3029        if (!compareStrings(pi1.name, pi2.name)) return false;
3030        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3031        // We'll take care of setting this one.
3032        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3033        // These are not currently stored in settings.
3034        //if (!compareStrings(pi1.group, pi2.group)) return false;
3035        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3036        //if (pi1.labelRes != pi2.labelRes) return false;
3037        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3038        return true;
3039    }
3040
3041    int permissionInfoFootprint(PermissionInfo info) {
3042        int size = info.name.length();
3043        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3044        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3045        return size;
3046    }
3047
3048    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3049        int size = 0;
3050        for (BasePermission perm : mSettings.mPermissions.values()) {
3051            if (perm.uid == tree.uid) {
3052                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3053            }
3054        }
3055        return size;
3056    }
3057
3058    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3059        // We calculate the max size of permissions defined by this uid and throw
3060        // if that plus the size of 'info' would exceed our stated maximum.
3061        if (tree.uid != Process.SYSTEM_UID) {
3062            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3063            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3064                throw new SecurityException("Permission tree size cap exceeded");
3065            }
3066        }
3067    }
3068
3069    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3070        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3071            throw new SecurityException("Label must be specified in permission");
3072        }
3073        BasePermission tree = checkPermissionTreeLP(info.name);
3074        BasePermission bp = mSettings.mPermissions.get(info.name);
3075        boolean added = bp == null;
3076        boolean changed = true;
3077        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3078        if (added) {
3079            enforcePermissionCapLocked(info, tree);
3080            bp = new BasePermission(info.name, tree.sourcePackage,
3081                    BasePermission.TYPE_DYNAMIC);
3082        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3083            throw new SecurityException(
3084                    "Not allowed to modify non-dynamic permission "
3085                    + info.name);
3086        } else {
3087            if (bp.protectionLevel == fixedLevel
3088                    && bp.perm.owner.equals(tree.perm.owner)
3089                    && bp.uid == tree.uid
3090                    && comparePermissionInfos(bp.perm.info, info)) {
3091                changed = false;
3092            }
3093        }
3094        bp.protectionLevel = fixedLevel;
3095        info = new PermissionInfo(info);
3096        info.protectionLevel = fixedLevel;
3097        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3098        bp.perm.info.packageName = tree.perm.info.packageName;
3099        bp.uid = tree.uid;
3100        if (added) {
3101            mSettings.mPermissions.put(info.name, bp);
3102        }
3103        if (changed) {
3104            if (!async) {
3105                mSettings.writeLPr();
3106            } else {
3107                scheduleWriteSettingsLocked();
3108            }
3109        }
3110        return added;
3111    }
3112
3113    @Override
3114    public boolean addPermission(PermissionInfo info) {
3115        synchronized (mPackages) {
3116            return addPermissionLocked(info, false);
3117        }
3118    }
3119
3120    @Override
3121    public boolean addPermissionAsync(PermissionInfo info) {
3122        synchronized (mPackages) {
3123            return addPermissionLocked(info, true);
3124        }
3125    }
3126
3127    @Override
3128    public void removePermission(String name) {
3129        synchronized (mPackages) {
3130            checkPermissionTreeLP(name);
3131            BasePermission bp = mSettings.mPermissions.get(name);
3132            if (bp != null) {
3133                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3134                    throw new SecurityException(
3135                            "Not allowed to modify non-dynamic permission "
3136                            + name);
3137                }
3138                mSettings.mPermissions.remove(name);
3139                mSettings.writeLPr();
3140            }
3141        }
3142    }
3143
3144    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3145            BasePermission bp) {
3146        int index = pkg.requestedPermissions.indexOf(bp.name);
3147        if (index == -1) {
3148            throw new SecurityException("Package " + pkg.packageName
3149                    + " has not requested permission " + bp.name);
3150        }
3151        if (!bp.isRuntime()) {
3152            throw new SecurityException("Permission " + bp.name
3153                    + " is not a changeable permission type");
3154        }
3155    }
3156
3157    @Override
3158    public void grantRuntimePermission(String packageName, String name, int userId) {
3159        if (!sUserManager.exists(userId)) {
3160            Log.e(TAG, "No such user:" + userId);
3161            return;
3162        }
3163
3164        mContext.enforceCallingOrSelfPermission(
3165                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3166                "grantRuntimePermission");
3167
3168        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3169                "grantRuntimePermission");
3170
3171        boolean gidsChanged = false;
3172        final SettingBase sb;
3173
3174        synchronized (mPackages) {
3175            final PackageParser.Package pkg = mPackages.get(packageName);
3176            if (pkg == null) {
3177                throw new IllegalArgumentException("Unknown package: " + packageName);
3178            }
3179
3180            final BasePermission bp = mSettings.mPermissions.get(name);
3181            if (bp == null) {
3182                throw new IllegalArgumentException("Unknown permission: " + name);
3183            }
3184
3185            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3186
3187            sb = (SettingBase) pkg.mExtras;
3188            if (sb == null) {
3189                throw new IllegalArgumentException("Unknown package: " + packageName);
3190            }
3191
3192            final PermissionsState permissionsState = sb.getPermissionsState();
3193
3194            final int flags = permissionsState.getPermissionFlags(name, userId);
3195            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3196                throw new SecurityException("Cannot grant system fixed permission: "
3197                        + name + " for package: " + packageName);
3198            }
3199
3200            final int result = permissionsState.grantRuntimePermission(bp, userId);
3201            switch (result) {
3202                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3203                    return;
3204                }
3205
3206                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3207                    gidsChanged = true;
3208                } break;
3209            }
3210
3211            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3212
3213            // Not critical if that is lost - app has to request again.
3214            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3215        }
3216
3217        if (gidsChanged) {
3218            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3219        }
3220    }
3221
3222    @Override
3223    public void revokeRuntimePermission(String packageName, String name, int userId) {
3224        if (!sUserManager.exists(userId)) {
3225            Log.e(TAG, "No such user:" + userId);
3226            return;
3227        }
3228
3229        mContext.enforceCallingOrSelfPermission(
3230                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3231                "revokeRuntimePermission");
3232
3233        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3234                "revokeRuntimePermission");
3235
3236        final SettingBase sb;
3237
3238        synchronized (mPackages) {
3239            final PackageParser.Package pkg = mPackages.get(packageName);
3240            if (pkg == null) {
3241                throw new IllegalArgumentException("Unknown package: " + packageName);
3242            }
3243
3244            final BasePermission bp = mSettings.mPermissions.get(name);
3245            if (bp == null) {
3246                throw new IllegalArgumentException("Unknown permission: " + name);
3247            }
3248
3249            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3250
3251            sb = (SettingBase) pkg.mExtras;
3252            if (sb == null) {
3253                throw new IllegalArgumentException("Unknown package: " + packageName);
3254            }
3255
3256            final PermissionsState permissionsState = sb.getPermissionsState();
3257
3258            final int flags = permissionsState.getPermissionFlags(name, userId);
3259            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3260                throw new SecurityException("Cannot revoke system fixed permission: "
3261                        + name + " for package: " + packageName);
3262            }
3263
3264            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3265                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3266                return;
3267            }
3268
3269            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3270
3271            // Critical, after this call app should never have the permission.
3272            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3273        }
3274
3275        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3276    }
3277
3278    @Override
3279    public int getPermissionFlags(String name, String packageName, int userId) {
3280        if (!sUserManager.exists(userId)) {
3281            return 0;
3282        }
3283
3284        mContext.enforceCallingOrSelfPermission(
3285                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3286                "getPermissionFlags");
3287
3288        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3289                "getPermissionFlags");
3290
3291        synchronized (mPackages) {
3292            final PackageParser.Package pkg = mPackages.get(packageName);
3293            if (pkg == null) {
3294                throw new IllegalArgumentException("Unknown package: " + packageName);
3295            }
3296
3297            final BasePermission bp = mSettings.mPermissions.get(name);
3298            if (bp == null) {
3299                throw new IllegalArgumentException("Unknown permission: " + name);
3300            }
3301
3302            SettingBase sb = (SettingBase) pkg.mExtras;
3303            if (sb == null) {
3304                throw new IllegalArgumentException("Unknown package: " + packageName);
3305            }
3306
3307            PermissionsState permissionsState = sb.getPermissionsState();
3308            return permissionsState.getPermissionFlags(name, userId);
3309        }
3310    }
3311
3312    @Override
3313    public void updatePermissionFlags(String name, String packageName, int flagMask,
3314            int flagValues, int userId) {
3315        if (!sUserManager.exists(userId)) {
3316            return;
3317        }
3318
3319        mContext.enforceCallingOrSelfPermission(
3320                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3321                "updatePermissionFlags");
3322
3323        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3324                "updatePermissionFlags");
3325
3326        // Only the system can change policy flags.
3327        if (getCallingUid() != Process.SYSTEM_UID) {
3328            flagMask &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED;
3329            flagValues &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED;
3330        }
3331
3332        // Only the package manager can change system flags.
3333        flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3334        flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3335
3336        synchronized (mPackages) {
3337            final PackageParser.Package pkg = mPackages.get(packageName);
3338            if (pkg == null) {
3339                throw new IllegalArgumentException("Unknown package: " + packageName);
3340            }
3341
3342            final BasePermission bp = mSettings.mPermissions.get(name);
3343            if (bp == null) {
3344                throw new IllegalArgumentException("Unknown permission: " + name);
3345            }
3346
3347            SettingBase sb = (SettingBase) pkg.mExtras;
3348            if (sb == null) {
3349                throw new IllegalArgumentException("Unknown package: " + packageName);
3350            }
3351
3352            PermissionsState permissionsState = sb.getPermissionsState();
3353
3354            // Only the package manager can change flags for system component permissions.
3355            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3356            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3357                return;
3358            }
3359
3360            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3361                // Install and runtime permissions are stored in different places,
3362                // so figure out what permission changed and persist the change.
3363                if (permissionsState.getInstallPermissionState(name) != null) {
3364                    scheduleWriteSettingsLocked();
3365                } else if (permissionsState.getRuntimePermissionState(name, userId) != null) {
3366                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3367                }
3368            }
3369        }
3370    }
3371
3372    @Override
3373    public boolean shouldShowRequestPermissionRationale(String permissionName,
3374            String packageName, int userId) {
3375        if (UserHandle.getCallingUserId() != userId) {
3376            mContext.enforceCallingPermission(
3377                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3378                    "canShowRequestPermissionRationale for user " + userId);
3379        }
3380
3381        final int uid = getPackageUid(packageName, userId);
3382        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3383            return false;
3384        }
3385
3386        if (checkPermission(permissionName, packageName, userId)
3387                == PackageManager.PERMISSION_GRANTED) {
3388            return false;
3389        }
3390
3391        final int flags;
3392
3393        final long identity = Binder.clearCallingIdentity();
3394        try {
3395            flags = getPermissionFlags(permissionName,
3396                    packageName, userId);
3397        } finally {
3398            Binder.restoreCallingIdentity(identity);
3399        }
3400
3401        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3402                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3403                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3404
3405        if ((flags & fixedFlags) != 0) {
3406            return false;
3407        }
3408
3409        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3410    }
3411
3412    @Override
3413    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3414        mContext.enforceCallingOrSelfPermission(
3415                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3416                "addOnPermissionsChangeListener");
3417
3418        synchronized (mPackages) {
3419            mOnPermissionChangeListeners.addListenerLocked(listener);
3420        }
3421    }
3422
3423    @Override
3424    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3425        synchronized (mPackages) {
3426            mOnPermissionChangeListeners.removeListenerLocked(listener);
3427        }
3428    }
3429
3430    @Override
3431    public boolean isProtectedBroadcast(String actionName) {
3432        synchronized (mPackages) {
3433            return mProtectedBroadcasts.contains(actionName);
3434        }
3435    }
3436
3437    @Override
3438    public int checkSignatures(String pkg1, String pkg2) {
3439        synchronized (mPackages) {
3440            final PackageParser.Package p1 = mPackages.get(pkg1);
3441            final PackageParser.Package p2 = mPackages.get(pkg2);
3442            if (p1 == null || p1.mExtras == null
3443                    || p2 == null || p2.mExtras == null) {
3444                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3445            }
3446            return compareSignatures(p1.mSignatures, p2.mSignatures);
3447        }
3448    }
3449
3450    @Override
3451    public int checkUidSignatures(int uid1, int uid2) {
3452        // Map to base uids.
3453        uid1 = UserHandle.getAppId(uid1);
3454        uid2 = UserHandle.getAppId(uid2);
3455        // reader
3456        synchronized (mPackages) {
3457            Signature[] s1;
3458            Signature[] s2;
3459            Object obj = mSettings.getUserIdLPr(uid1);
3460            if (obj != null) {
3461                if (obj instanceof SharedUserSetting) {
3462                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3463                } else if (obj instanceof PackageSetting) {
3464                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3465                } else {
3466                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3467                }
3468            } else {
3469                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3470            }
3471            obj = mSettings.getUserIdLPr(uid2);
3472            if (obj != null) {
3473                if (obj instanceof SharedUserSetting) {
3474                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3475                } else if (obj instanceof PackageSetting) {
3476                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3477                } else {
3478                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3479                }
3480            } else {
3481                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3482            }
3483            return compareSignatures(s1, s2);
3484        }
3485    }
3486
3487    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3488        final long identity = Binder.clearCallingIdentity();
3489        try {
3490            if (sb instanceof SharedUserSetting) {
3491                SharedUserSetting sus = (SharedUserSetting) sb;
3492                final int packageCount = sus.packages.size();
3493                for (int i = 0; i < packageCount; i++) {
3494                    PackageSetting susPs = sus.packages.valueAt(i);
3495                    if (userId == UserHandle.USER_ALL) {
3496                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3497                    } else {
3498                        final int uid = UserHandle.getUid(userId, susPs.appId);
3499                        killUid(uid, reason);
3500                    }
3501                }
3502            } else if (sb instanceof PackageSetting) {
3503                PackageSetting ps = (PackageSetting) sb;
3504                if (userId == UserHandle.USER_ALL) {
3505                    killApplication(ps.pkg.packageName, ps.appId, reason);
3506                } else {
3507                    final int uid = UserHandle.getUid(userId, ps.appId);
3508                    killUid(uid, reason);
3509                }
3510            }
3511        } finally {
3512            Binder.restoreCallingIdentity(identity);
3513        }
3514    }
3515
3516    private static void killUid(int uid, String reason) {
3517        IActivityManager am = ActivityManagerNative.getDefault();
3518        if (am != null) {
3519            try {
3520                am.killUid(uid, reason);
3521            } catch (RemoteException e) {
3522                /* ignore - same process */
3523            }
3524        }
3525    }
3526
3527    /**
3528     * Compares two sets of signatures. Returns:
3529     * <br />
3530     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3531     * <br />
3532     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3533     * <br />
3534     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3535     * <br />
3536     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3537     * <br />
3538     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3539     */
3540    static int compareSignatures(Signature[] s1, Signature[] s2) {
3541        if (s1 == null) {
3542            return s2 == null
3543                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3544                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3545        }
3546
3547        if (s2 == null) {
3548            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3549        }
3550
3551        if (s1.length != s2.length) {
3552            return PackageManager.SIGNATURE_NO_MATCH;
3553        }
3554
3555        // Since both signature sets are of size 1, we can compare without HashSets.
3556        if (s1.length == 1) {
3557            return s1[0].equals(s2[0]) ?
3558                    PackageManager.SIGNATURE_MATCH :
3559                    PackageManager.SIGNATURE_NO_MATCH;
3560        }
3561
3562        ArraySet<Signature> set1 = new ArraySet<Signature>();
3563        for (Signature sig : s1) {
3564            set1.add(sig);
3565        }
3566        ArraySet<Signature> set2 = new ArraySet<Signature>();
3567        for (Signature sig : s2) {
3568            set2.add(sig);
3569        }
3570        // Make sure s2 contains all signatures in s1.
3571        if (set1.equals(set2)) {
3572            return PackageManager.SIGNATURE_MATCH;
3573        }
3574        return PackageManager.SIGNATURE_NO_MATCH;
3575    }
3576
3577    /**
3578     * If the database version for this type of package (internal storage or
3579     * external storage) is less than the version where package signatures
3580     * were updated, return true.
3581     */
3582    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3583        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3584                DatabaseVersion.SIGNATURE_END_ENTITY))
3585                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3586                        DatabaseVersion.SIGNATURE_END_ENTITY));
3587    }
3588
3589    /**
3590     * Used for backward compatibility to make sure any packages with
3591     * certificate chains get upgraded to the new style. {@code existingSigs}
3592     * will be in the old format (since they were stored on disk from before the
3593     * system upgrade) and {@code scannedSigs} will be in the newer format.
3594     */
3595    private int compareSignaturesCompat(PackageSignatures existingSigs,
3596            PackageParser.Package scannedPkg) {
3597        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3598            return PackageManager.SIGNATURE_NO_MATCH;
3599        }
3600
3601        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3602        for (Signature sig : existingSigs.mSignatures) {
3603            existingSet.add(sig);
3604        }
3605        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3606        for (Signature sig : scannedPkg.mSignatures) {
3607            try {
3608                Signature[] chainSignatures = sig.getChainSignatures();
3609                for (Signature chainSig : chainSignatures) {
3610                    scannedCompatSet.add(chainSig);
3611                }
3612            } catch (CertificateEncodingException e) {
3613                scannedCompatSet.add(sig);
3614            }
3615        }
3616        /*
3617         * Make sure the expanded scanned set contains all signatures in the
3618         * existing one.
3619         */
3620        if (scannedCompatSet.equals(existingSet)) {
3621            // Migrate the old signatures to the new scheme.
3622            existingSigs.assignSignatures(scannedPkg.mSignatures);
3623            // The new KeySets will be re-added later in the scanning process.
3624            synchronized (mPackages) {
3625                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3626            }
3627            return PackageManager.SIGNATURE_MATCH;
3628        }
3629        return PackageManager.SIGNATURE_NO_MATCH;
3630    }
3631
3632    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3633        if (isExternal(scannedPkg)) {
3634            return mSettings.isExternalDatabaseVersionOlderThan(
3635                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3636        } else {
3637            return mSettings.isInternalDatabaseVersionOlderThan(
3638                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3639        }
3640    }
3641
3642    private int compareSignaturesRecover(PackageSignatures existingSigs,
3643            PackageParser.Package scannedPkg) {
3644        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3645            return PackageManager.SIGNATURE_NO_MATCH;
3646        }
3647
3648        String msg = null;
3649        try {
3650            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3651                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3652                        + scannedPkg.packageName);
3653                return PackageManager.SIGNATURE_MATCH;
3654            }
3655        } catch (CertificateException e) {
3656            msg = e.getMessage();
3657        }
3658
3659        logCriticalInfo(Log.INFO,
3660                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3661        return PackageManager.SIGNATURE_NO_MATCH;
3662    }
3663
3664    @Override
3665    public String[] getPackagesForUid(int uid) {
3666        uid = UserHandle.getAppId(uid);
3667        // reader
3668        synchronized (mPackages) {
3669            Object obj = mSettings.getUserIdLPr(uid);
3670            if (obj instanceof SharedUserSetting) {
3671                final SharedUserSetting sus = (SharedUserSetting) obj;
3672                final int N = sus.packages.size();
3673                final String[] res = new String[N];
3674                final Iterator<PackageSetting> it = sus.packages.iterator();
3675                int i = 0;
3676                while (it.hasNext()) {
3677                    res[i++] = it.next().name;
3678                }
3679                return res;
3680            } else if (obj instanceof PackageSetting) {
3681                final PackageSetting ps = (PackageSetting) obj;
3682                return new String[] { ps.name };
3683            }
3684        }
3685        return null;
3686    }
3687
3688    @Override
3689    public String getNameForUid(int uid) {
3690        // reader
3691        synchronized (mPackages) {
3692            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3693            if (obj instanceof SharedUserSetting) {
3694                final SharedUserSetting sus = (SharedUserSetting) obj;
3695                return sus.name + ":" + sus.userId;
3696            } else if (obj instanceof PackageSetting) {
3697                final PackageSetting ps = (PackageSetting) obj;
3698                return ps.name;
3699            }
3700        }
3701        return null;
3702    }
3703
3704    @Override
3705    public int getUidForSharedUser(String sharedUserName) {
3706        if(sharedUserName == null) {
3707            return -1;
3708        }
3709        // reader
3710        synchronized (mPackages) {
3711            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
3712            if (suid == null) {
3713                return -1;
3714            }
3715            return suid.userId;
3716        }
3717    }
3718
3719    @Override
3720    public int getFlagsForUid(int uid) {
3721        synchronized (mPackages) {
3722            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3723            if (obj instanceof SharedUserSetting) {
3724                final SharedUserSetting sus = (SharedUserSetting) obj;
3725                return sus.pkgFlags;
3726            } else if (obj instanceof PackageSetting) {
3727                final PackageSetting ps = (PackageSetting) obj;
3728                return ps.pkgFlags;
3729            }
3730        }
3731        return 0;
3732    }
3733
3734    @Override
3735    public int getPrivateFlagsForUid(int uid) {
3736        synchronized (mPackages) {
3737            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3738            if (obj instanceof SharedUserSetting) {
3739                final SharedUserSetting sus = (SharedUserSetting) obj;
3740                return sus.pkgPrivateFlags;
3741            } else if (obj instanceof PackageSetting) {
3742                final PackageSetting ps = (PackageSetting) obj;
3743                return ps.pkgPrivateFlags;
3744            }
3745        }
3746        return 0;
3747    }
3748
3749    @Override
3750    public boolean isUidPrivileged(int uid) {
3751        uid = UserHandle.getAppId(uid);
3752        // reader
3753        synchronized (mPackages) {
3754            Object obj = mSettings.getUserIdLPr(uid);
3755            if (obj instanceof SharedUserSetting) {
3756                final SharedUserSetting sus = (SharedUserSetting) obj;
3757                final Iterator<PackageSetting> it = sus.packages.iterator();
3758                while (it.hasNext()) {
3759                    if (it.next().isPrivileged()) {
3760                        return true;
3761                    }
3762                }
3763            } else if (obj instanceof PackageSetting) {
3764                final PackageSetting ps = (PackageSetting) obj;
3765                return ps.isPrivileged();
3766            }
3767        }
3768        return false;
3769    }
3770
3771    @Override
3772    public String[] getAppOpPermissionPackages(String permissionName) {
3773        synchronized (mPackages) {
3774            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
3775            if (pkgs == null) {
3776                return null;
3777            }
3778            return pkgs.toArray(new String[pkgs.size()]);
3779        }
3780    }
3781
3782    @Override
3783    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3784            int flags, int userId) {
3785        if (!sUserManager.exists(userId)) return null;
3786        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
3787        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3788        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3789    }
3790
3791    @Override
3792    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3793            IntentFilter filter, int match, ComponentName activity) {
3794        final int userId = UserHandle.getCallingUserId();
3795        if (DEBUG_PREFERRED) {
3796            Log.v(TAG, "setLastChosenActivity intent=" + intent
3797                + " resolvedType=" + resolvedType
3798                + " flags=" + flags
3799                + " filter=" + filter
3800                + " match=" + match
3801                + " activity=" + activity);
3802            filter.dump(new PrintStreamPrinter(System.out), "    ");
3803        }
3804        intent.setComponent(null);
3805        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3806        // Find any earlier preferred or last chosen entries and nuke them
3807        findPreferredActivity(intent, resolvedType,
3808                flags, query, 0, false, true, false, userId);
3809        // Add the new activity as the last chosen for this filter
3810        addPreferredActivityInternal(filter, match, null, activity, false, userId,
3811                "Setting last chosen");
3812    }
3813
3814    @Override
3815    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
3816        final int userId = UserHandle.getCallingUserId();
3817        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
3818        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3819        return findPreferredActivity(intent, resolvedType, flags, query, 0,
3820                false, false, false, userId);
3821    }
3822
3823    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
3824            int flags, List<ResolveInfo> query, int userId) {
3825        if (query != null) {
3826            final int N = query.size();
3827            if (N == 1) {
3828                return query.get(0);
3829            } else if (N > 1) {
3830                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3831                // If there is more than one activity with the same priority,
3832                // then let the user decide between them.
3833                ResolveInfo r0 = query.get(0);
3834                ResolveInfo r1 = query.get(1);
3835                if (DEBUG_INTENT_MATCHING || debug) {
3836                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
3837                            + r1.activityInfo.name + "=" + r1.priority);
3838                }
3839                // If the first activity has a higher priority, or a different
3840                // default, then it is always desireable to pick it.
3841                if (r0.priority != r1.priority
3842                        || r0.preferredOrder != r1.preferredOrder
3843                        || r0.isDefault != r1.isDefault) {
3844                    return query.get(0);
3845                }
3846                // If we have saved a preference for a preferred activity for
3847                // this Intent, use that.
3848                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3849                        flags, query, r0.priority, true, false, debug, userId);
3850                if (ri != null) {
3851                    return ri;
3852                }
3853                if (userId != 0) {
3854                    ri = new ResolveInfo(mResolveInfo);
3855                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3856                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3857                            ri.activityInfo.applicationInfo);
3858                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3859                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3860                    return ri;
3861                }
3862                return mResolveInfo;
3863            }
3864        }
3865        return null;
3866    }
3867
3868    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3869            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3870        final int N = query.size();
3871        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3872                .get(userId);
3873        // Get the list of persistent preferred activities that handle the intent
3874        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3875        List<PersistentPreferredActivity> pprefs = ppir != null
3876                ? ppir.queryIntent(intent, resolvedType,
3877                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3878                : null;
3879        if (pprefs != null && pprefs.size() > 0) {
3880            final int M = pprefs.size();
3881            for (int i=0; i<M; i++) {
3882                final PersistentPreferredActivity ppa = pprefs.get(i);
3883                if (DEBUG_PREFERRED || debug) {
3884                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3885                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3886                            + "\n  component=" + ppa.mComponent);
3887                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3888                }
3889                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3890                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3891                if (DEBUG_PREFERRED || debug) {
3892                    Slog.v(TAG, "Found persistent preferred activity:");
3893                    if (ai != null) {
3894                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3895                    } else {
3896                        Slog.v(TAG, "  null");
3897                    }
3898                }
3899                if (ai == null) {
3900                    // This previously registered persistent preferred activity
3901                    // component is no longer known. Ignore it and do NOT remove it.
3902                    continue;
3903                }
3904                for (int j=0; j<N; j++) {
3905                    final ResolveInfo ri = query.get(j);
3906                    if (!ri.activityInfo.applicationInfo.packageName
3907                            .equals(ai.applicationInfo.packageName)) {
3908                        continue;
3909                    }
3910                    if (!ri.activityInfo.name.equals(ai.name)) {
3911                        continue;
3912                    }
3913                    //  Found a persistent preference that can handle the intent.
3914                    if (DEBUG_PREFERRED || debug) {
3915                        Slog.v(TAG, "Returning persistent preferred activity: " +
3916                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3917                    }
3918                    return ri;
3919                }
3920            }
3921        }
3922        return null;
3923    }
3924
3925    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3926            List<ResolveInfo> query, int priority, boolean always,
3927            boolean removeMatches, boolean debug, int userId) {
3928        if (!sUserManager.exists(userId)) return null;
3929        // writer
3930        synchronized (mPackages) {
3931            if (intent.getSelector() != null) {
3932                intent = intent.getSelector();
3933            }
3934            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3935
3936            // Try to find a matching persistent preferred activity.
3937            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3938                    debug, userId);
3939
3940            // If a persistent preferred activity matched, use it.
3941            if (pri != null) {
3942                return pri;
3943            }
3944
3945            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3946            // Get the list of preferred activities that handle the intent
3947            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3948            List<PreferredActivity> prefs = pir != null
3949                    ? pir.queryIntent(intent, resolvedType,
3950                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3951                    : null;
3952            if (prefs != null && prefs.size() > 0) {
3953                boolean changed = false;
3954                try {
3955                    // First figure out how good the original match set is.
3956                    // We will only allow preferred activities that came
3957                    // from the same match quality.
3958                    int match = 0;
3959
3960                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3961
3962                    final int N = query.size();
3963                    for (int j=0; j<N; j++) {
3964                        final ResolveInfo ri = query.get(j);
3965                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3966                                + ": 0x" + Integer.toHexString(match));
3967                        if (ri.match > match) {
3968                            match = ri.match;
3969                        }
3970                    }
3971
3972                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3973                            + Integer.toHexString(match));
3974
3975                    match &= IntentFilter.MATCH_CATEGORY_MASK;
3976                    final int M = prefs.size();
3977                    for (int i=0; i<M; i++) {
3978                        final PreferredActivity pa = prefs.get(i);
3979                        if (DEBUG_PREFERRED || debug) {
3980                            Slog.v(TAG, "Checking PreferredActivity ds="
3981                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3982                                    + "\n  component=" + pa.mPref.mComponent);
3983                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3984                        }
3985                        if (pa.mPref.mMatch != match) {
3986                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3987                                    + Integer.toHexString(pa.mPref.mMatch));
3988                            continue;
3989                        }
3990                        // If it's not an "always" type preferred activity and that's what we're
3991                        // looking for, skip it.
3992                        if (always && !pa.mPref.mAlways) {
3993                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3994                            continue;
3995                        }
3996                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3997                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3998                        if (DEBUG_PREFERRED || debug) {
3999                            Slog.v(TAG, "Found preferred activity:");
4000                            if (ai != null) {
4001                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4002                            } else {
4003                                Slog.v(TAG, "  null");
4004                            }
4005                        }
4006                        if (ai == null) {
4007                            // This previously registered preferred activity
4008                            // component is no longer known.  Most likely an update
4009                            // to the app was installed and in the new version this
4010                            // component no longer exists.  Clean it up by removing
4011                            // it from the preferred activities list, and skip it.
4012                            Slog.w(TAG, "Removing dangling preferred activity: "
4013                                    + pa.mPref.mComponent);
4014                            pir.removeFilter(pa);
4015                            changed = true;
4016                            continue;
4017                        }
4018                        for (int j=0; j<N; j++) {
4019                            final ResolveInfo ri = query.get(j);
4020                            if (!ri.activityInfo.applicationInfo.packageName
4021                                    .equals(ai.applicationInfo.packageName)) {
4022                                continue;
4023                            }
4024                            if (!ri.activityInfo.name.equals(ai.name)) {
4025                                continue;
4026                            }
4027
4028                            if (removeMatches) {
4029                                pir.removeFilter(pa);
4030                                changed = true;
4031                                if (DEBUG_PREFERRED) {
4032                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4033                                }
4034                                break;
4035                            }
4036
4037                            // Okay we found a previously set preferred or last chosen app.
4038                            // If the result set is different from when this
4039                            // was created, we need to clear it and re-ask the
4040                            // user their preference, if we're looking for an "always" type entry.
4041                            if (always && !pa.mPref.sameSet(query)) {
4042                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4043                                        + intent + " type " + resolvedType);
4044                                if (DEBUG_PREFERRED) {
4045                                    Slog.v(TAG, "Removing preferred activity since set changed "
4046                                            + pa.mPref.mComponent);
4047                                }
4048                                pir.removeFilter(pa);
4049                                // Re-add the filter as a "last chosen" entry (!always)
4050                                PreferredActivity lastChosen = new PreferredActivity(
4051                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4052                                pir.addFilter(lastChosen);
4053                                changed = true;
4054                                return null;
4055                            }
4056
4057                            // Yay! Either the set matched or we're looking for the last chosen
4058                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4059                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4060                            return ri;
4061                        }
4062                    }
4063                } finally {
4064                    if (changed) {
4065                        if (DEBUG_PREFERRED) {
4066                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4067                        }
4068                        scheduleWritePackageRestrictionsLocked(userId);
4069                    }
4070                }
4071            }
4072        }
4073        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4074        return null;
4075    }
4076
4077    /*
4078     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4079     */
4080    @Override
4081    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4082            int targetUserId) {
4083        mContext.enforceCallingOrSelfPermission(
4084                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4085        List<CrossProfileIntentFilter> matches =
4086                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4087        if (matches != null) {
4088            int size = matches.size();
4089            for (int i = 0; i < size; i++) {
4090                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4091            }
4092        }
4093        return false;
4094    }
4095
4096    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4097            String resolvedType, int userId) {
4098        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4099        if (resolver != null) {
4100            return resolver.queryIntent(intent, resolvedType, false, userId);
4101        }
4102        return null;
4103    }
4104
4105    @Override
4106    public List<ResolveInfo> queryIntentActivities(Intent intent,
4107            String resolvedType, int flags, int userId) {
4108        if (!sUserManager.exists(userId)) return Collections.emptyList();
4109        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4110        ComponentName comp = intent.getComponent();
4111        if (comp == null) {
4112            if (intent.getSelector() != null) {
4113                intent = intent.getSelector();
4114                comp = intent.getComponent();
4115            }
4116        }
4117
4118        if (comp != null) {
4119            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4120            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4121            if (ai != null) {
4122                final ResolveInfo ri = new ResolveInfo();
4123                ri.activityInfo = ai;
4124                list.add(ri);
4125            }
4126            return list;
4127        }
4128
4129        // reader
4130        synchronized (mPackages) {
4131            final String pkgName = intent.getPackage();
4132            if (pkgName == null) {
4133                List<CrossProfileIntentFilter> matchingFilters =
4134                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4135                // Check for results that need to skip the current profile.
4136                ResolveInfo resolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4137                        resolvedType, flags, userId);
4138                if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) {
4139                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4140                    result.add(resolveInfo);
4141                    return filterIfNotPrimaryUser(result, userId);
4142                }
4143
4144                // Check for results in the current profile.
4145                List<ResolveInfo> result = mActivities.queryIntent(
4146                        intent, resolvedType, flags, userId);
4147
4148                // Check for cross profile results.
4149                resolveInfo = queryCrossProfileIntents(
4150                        matchingFilters, intent, resolvedType, flags, userId);
4151                if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) {
4152                    result.add(resolveInfo);
4153                    Collections.sort(result, mResolvePrioritySorter);
4154                }
4155                result = filterIfNotPrimaryUser(result, userId);
4156                if (result.size() > 1 && hasWebURI(intent)) {
4157                    return filterCandidatesWithDomainPreferedActivitiesLPr(flags, result);
4158                }
4159                return result;
4160            }
4161            final PackageParser.Package pkg = mPackages.get(pkgName);
4162            if (pkg != null) {
4163                return filterIfNotPrimaryUser(
4164                        mActivities.queryIntentForPackage(
4165                                intent, resolvedType, flags, pkg.activities, userId),
4166                        userId);
4167            }
4168            return new ArrayList<ResolveInfo>();
4169        }
4170    }
4171
4172    private boolean isUserEnabled(int userId) {
4173        long callingId = Binder.clearCallingIdentity();
4174        try {
4175            UserInfo userInfo = sUserManager.getUserInfo(userId);
4176            return userInfo != null && userInfo.isEnabled();
4177        } finally {
4178            Binder.restoreCallingIdentity(callingId);
4179        }
4180    }
4181
4182    /**
4183     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4184     *
4185     * @return filtered list
4186     */
4187    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4188        if (userId == UserHandle.USER_OWNER) {
4189            return resolveInfos;
4190        }
4191        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4192            ResolveInfo info = resolveInfos.get(i);
4193            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4194                resolveInfos.remove(i);
4195            }
4196        }
4197        return resolveInfos;
4198    }
4199
4200    private static boolean hasWebURI(Intent intent) {
4201        if (intent.getData() == null) {
4202            return false;
4203        }
4204        final String scheme = intent.getScheme();
4205        if (TextUtils.isEmpty(scheme)) {
4206            return false;
4207        }
4208        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4209    }
4210
4211    private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPr(
4212            int flags, List<ResolveInfo> candidates) {
4213        if (DEBUG_PREFERRED) {
4214            Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " +
4215                    candidates.size());
4216        }
4217
4218        final int userId = UserHandle.getCallingUserId();
4219        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4220        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4221        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4222        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4223        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4224
4225        synchronized (mPackages) {
4226            final int count = candidates.size();
4227            // First, try to use the domain prefered App. Partition the candidates into four lists:
4228            // one for the final results, one for the "do not use ever", one for "undefined status"
4229            // and finally one for "Browser App type".
4230            for (int n=0; n<count; n++) {
4231                ResolveInfo info = candidates.get(n);
4232                String packageName = info.activityInfo.packageName;
4233                PackageSetting ps = mSettings.mPackages.get(packageName);
4234                if (ps != null) {
4235                    // Add to the special match all list (Browser use case)
4236                    if (info.handleAllWebDataURI) {
4237                        matchAllList.add(info);
4238                        continue;
4239                    }
4240                    // Try to get the status from User settings first
4241                    int status = getDomainVerificationStatusLPr(ps, userId);
4242                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4243                        alwaysList.add(info);
4244                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4245                        neverList.add(info);
4246                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4247                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4248                        undefinedList.add(info);
4249                    }
4250                }
4251            }
4252            // First try to add the "always" if there is any
4253            if (alwaysList.size() > 0) {
4254                result.addAll(alwaysList);
4255            } else {
4256                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4257                result.addAll(undefinedList);
4258                // Also add Browsers (all of them or only the default one)
4259                if ((flags & MATCH_ALL) != 0) {
4260                    result.addAll(matchAllList);
4261                } else {
4262                    // Try to add the Default Browser if we can
4263                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(
4264                            UserHandle.myUserId());
4265                    if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
4266                        boolean defaultBrowserFound = false;
4267                        final int browserCount = matchAllList.size();
4268                        for (int n=0; n<browserCount; n++) {
4269                            ResolveInfo browser = matchAllList.get(n);
4270                            if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4271                                result.add(browser);
4272                                defaultBrowserFound = true;
4273                                break;
4274                            }
4275                        }
4276                        if (!defaultBrowserFound) {
4277                            result.addAll(matchAllList);
4278                        }
4279                    } else {
4280                        result.addAll(matchAllList);
4281                    }
4282                }
4283
4284                // If there is nothing selected, add all candidates and remove the ones that the User
4285                // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4286                if (result.size() == 0) {
4287                    result.addAll(candidates);
4288                    result.removeAll(neverList);
4289                }
4290            }
4291        }
4292        if (DEBUG_PREFERRED) {
4293            Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " +
4294                    result.size());
4295        }
4296        return result;
4297    }
4298
4299    private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4300        int status = ps.getDomainVerificationStatusForUser(userId);
4301        // if none available, get the master status
4302        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4303            if (ps.getIntentFilterVerificationInfo() != null) {
4304                status = ps.getIntentFilterVerificationInfo().getStatus();
4305            }
4306        }
4307        return status;
4308    }
4309
4310    private ResolveInfo querySkipCurrentProfileIntents(
4311            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4312            int flags, int sourceUserId) {
4313        if (matchingFilters != null) {
4314            int size = matchingFilters.size();
4315            for (int i = 0; i < size; i ++) {
4316                CrossProfileIntentFilter filter = matchingFilters.get(i);
4317                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4318                    // Checking if there are activities in the target user that can handle the
4319                    // intent.
4320                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4321                            flags, sourceUserId);
4322                    if (resolveInfo != null) {
4323                        return resolveInfo;
4324                    }
4325                }
4326            }
4327        }
4328        return null;
4329    }
4330
4331    // Return matching ResolveInfo if any for skip current profile intent filters.
4332    private ResolveInfo queryCrossProfileIntents(
4333            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4334            int flags, int sourceUserId) {
4335        if (matchingFilters != null) {
4336            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4337            // match the same intent. For performance reasons, it is better not to
4338            // run queryIntent twice for the same userId
4339            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4340            int size = matchingFilters.size();
4341            for (int i = 0; i < size; i++) {
4342                CrossProfileIntentFilter filter = matchingFilters.get(i);
4343                int targetUserId = filter.getTargetUserId();
4344                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4345                        && !alreadyTriedUserIds.get(targetUserId)) {
4346                    // Checking if there are activities in the target user that can handle the
4347                    // intent.
4348                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4349                            flags, sourceUserId);
4350                    if (resolveInfo != null) return resolveInfo;
4351                    alreadyTriedUserIds.put(targetUserId, true);
4352                }
4353            }
4354        }
4355        return null;
4356    }
4357
4358    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4359            String resolvedType, int flags, int sourceUserId) {
4360        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4361                resolvedType, flags, filter.getTargetUserId());
4362        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4363            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4364        }
4365        return null;
4366    }
4367
4368    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4369            int sourceUserId, int targetUserId) {
4370        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4371        String className;
4372        if (targetUserId == UserHandle.USER_OWNER) {
4373            className = FORWARD_INTENT_TO_USER_OWNER;
4374        } else {
4375            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4376        }
4377        ComponentName forwardingActivityComponentName = new ComponentName(
4378                mAndroidApplication.packageName, className);
4379        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4380                sourceUserId);
4381        if (targetUserId == UserHandle.USER_OWNER) {
4382            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4383            forwardingResolveInfo.noResourceId = true;
4384        }
4385        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4386        forwardingResolveInfo.priority = 0;
4387        forwardingResolveInfo.preferredOrder = 0;
4388        forwardingResolveInfo.match = 0;
4389        forwardingResolveInfo.isDefault = true;
4390        forwardingResolveInfo.filter = filter;
4391        forwardingResolveInfo.targetUserId = targetUserId;
4392        return forwardingResolveInfo;
4393    }
4394
4395    @Override
4396    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4397            Intent[] specifics, String[] specificTypes, Intent intent,
4398            String resolvedType, int flags, int userId) {
4399        if (!sUserManager.exists(userId)) return Collections.emptyList();
4400        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4401                false, "query intent activity options");
4402        final String resultsAction = intent.getAction();
4403
4404        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4405                | PackageManager.GET_RESOLVED_FILTER, userId);
4406
4407        if (DEBUG_INTENT_MATCHING) {
4408            Log.v(TAG, "Query " + intent + ": " + results);
4409        }
4410
4411        int specificsPos = 0;
4412        int N;
4413
4414        // todo: note that the algorithm used here is O(N^2).  This
4415        // isn't a problem in our current environment, but if we start running
4416        // into situations where we have more than 5 or 10 matches then this
4417        // should probably be changed to something smarter...
4418
4419        // First we go through and resolve each of the specific items
4420        // that were supplied, taking care of removing any corresponding
4421        // duplicate items in the generic resolve list.
4422        if (specifics != null) {
4423            for (int i=0; i<specifics.length; i++) {
4424                final Intent sintent = specifics[i];
4425                if (sintent == null) {
4426                    continue;
4427                }
4428
4429                if (DEBUG_INTENT_MATCHING) {
4430                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4431                }
4432
4433                String action = sintent.getAction();
4434                if (resultsAction != null && resultsAction.equals(action)) {
4435                    // If this action was explicitly requested, then don't
4436                    // remove things that have it.
4437                    action = null;
4438                }
4439
4440                ResolveInfo ri = null;
4441                ActivityInfo ai = null;
4442
4443                ComponentName comp = sintent.getComponent();
4444                if (comp == null) {
4445                    ri = resolveIntent(
4446                        sintent,
4447                        specificTypes != null ? specificTypes[i] : null,
4448                            flags, userId);
4449                    if (ri == null) {
4450                        continue;
4451                    }
4452                    if (ri == mResolveInfo) {
4453                        // ACK!  Must do something better with this.
4454                    }
4455                    ai = ri.activityInfo;
4456                    comp = new ComponentName(ai.applicationInfo.packageName,
4457                            ai.name);
4458                } else {
4459                    ai = getActivityInfo(comp, flags, userId);
4460                    if (ai == null) {
4461                        continue;
4462                    }
4463                }
4464
4465                // Look for any generic query activities that are duplicates
4466                // of this specific one, and remove them from the results.
4467                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4468                N = results.size();
4469                int j;
4470                for (j=specificsPos; j<N; j++) {
4471                    ResolveInfo sri = results.get(j);
4472                    if ((sri.activityInfo.name.equals(comp.getClassName())
4473                            && sri.activityInfo.applicationInfo.packageName.equals(
4474                                    comp.getPackageName()))
4475                        || (action != null && sri.filter.matchAction(action))) {
4476                        results.remove(j);
4477                        if (DEBUG_INTENT_MATCHING) Log.v(
4478                            TAG, "Removing duplicate item from " + j
4479                            + " due to specific " + specificsPos);
4480                        if (ri == null) {
4481                            ri = sri;
4482                        }
4483                        j--;
4484                        N--;
4485                    }
4486                }
4487
4488                // Add this specific item to its proper place.
4489                if (ri == null) {
4490                    ri = new ResolveInfo();
4491                    ri.activityInfo = ai;
4492                }
4493                results.add(specificsPos, ri);
4494                ri.specificIndex = i;
4495                specificsPos++;
4496            }
4497        }
4498
4499        // Now we go through the remaining generic results and remove any
4500        // duplicate actions that are found here.
4501        N = results.size();
4502        for (int i=specificsPos; i<N-1; i++) {
4503            final ResolveInfo rii = results.get(i);
4504            if (rii.filter == null) {
4505                continue;
4506            }
4507
4508            // Iterate over all of the actions of this result's intent
4509            // filter...  typically this should be just one.
4510            final Iterator<String> it = rii.filter.actionsIterator();
4511            if (it == null) {
4512                continue;
4513            }
4514            while (it.hasNext()) {
4515                final String action = it.next();
4516                if (resultsAction != null && resultsAction.equals(action)) {
4517                    // If this action was explicitly requested, then don't
4518                    // remove things that have it.
4519                    continue;
4520                }
4521                for (int j=i+1; j<N; j++) {
4522                    final ResolveInfo rij = results.get(j);
4523                    if (rij.filter != null && rij.filter.hasAction(action)) {
4524                        results.remove(j);
4525                        if (DEBUG_INTENT_MATCHING) Log.v(
4526                            TAG, "Removing duplicate item from " + j
4527                            + " due to action " + action + " at " + i);
4528                        j--;
4529                        N--;
4530                    }
4531                }
4532            }
4533
4534            // If the caller didn't request filter information, drop it now
4535            // so we don't have to marshall/unmarshall it.
4536            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4537                rii.filter = null;
4538            }
4539        }
4540
4541        // Filter out the caller activity if so requested.
4542        if (caller != null) {
4543            N = results.size();
4544            for (int i=0; i<N; i++) {
4545                ActivityInfo ainfo = results.get(i).activityInfo;
4546                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
4547                        && caller.getClassName().equals(ainfo.name)) {
4548                    results.remove(i);
4549                    break;
4550                }
4551            }
4552        }
4553
4554        // If the caller didn't request filter information,
4555        // drop them now so we don't have to
4556        // marshall/unmarshall it.
4557        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4558            N = results.size();
4559            for (int i=0; i<N; i++) {
4560                results.get(i).filter = null;
4561            }
4562        }
4563
4564        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
4565        return results;
4566    }
4567
4568    @Override
4569    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
4570            int userId) {
4571        if (!sUserManager.exists(userId)) return Collections.emptyList();
4572        ComponentName comp = intent.getComponent();
4573        if (comp == null) {
4574            if (intent.getSelector() != null) {
4575                intent = intent.getSelector();
4576                comp = intent.getComponent();
4577            }
4578        }
4579        if (comp != null) {
4580            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4581            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
4582            if (ai != null) {
4583                ResolveInfo ri = new ResolveInfo();
4584                ri.activityInfo = ai;
4585                list.add(ri);
4586            }
4587            return list;
4588        }
4589
4590        // reader
4591        synchronized (mPackages) {
4592            String pkgName = intent.getPackage();
4593            if (pkgName == null) {
4594                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
4595            }
4596            final PackageParser.Package pkg = mPackages.get(pkgName);
4597            if (pkg != null) {
4598                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
4599                        userId);
4600            }
4601            return null;
4602        }
4603    }
4604
4605    @Override
4606    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
4607        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
4608        if (!sUserManager.exists(userId)) return null;
4609        if (query != null) {
4610            if (query.size() >= 1) {
4611                // If there is more than one service with the same priority,
4612                // just arbitrarily pick the first one.
4613                return query.get(0);
4614            }
4615        }
4616        return null;
4617    }
4618
4619    @Override
4620    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
4621            int userId) {
4622        if (!sUserManager.exists(userId)) return Collections.emptyList();
4623        ComponentName comp = intent.getComponent();
4624        if (comp == null) {
4625            if (intent.getSelector() != null) {
4626                intent = intent.getSelector();
4627                comp = intent.getComponent();
4628            }
4629        }
4630        if (comp != null) {
4631            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4632            final ServiceInfo si = getServiceInfo(comp, flags, userId);
4633            if (si != null) {
4634                final ResolveInfo ri = new ResolveInfo();
4635                ri.serviceInfo = si;
4636                list.add(ri);
4637            }
4638            return list;
4639        }
4640
4641        // reader
4642        synchronized (mPackages) {
4643            String pkgName = intent.getPackage();
4644            if (pkgName == null) {
4645                return mServices.queryIntent(intent, resolvedType, flags, userId);
4646            }
4647            final PackageParser.Package pkg = mPackages.get(pkgName);
4648            if (pkg != null) {
4649                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
4650                        userId);
4651            }
4652            return null;
4653        }
4654    }
4655
4656    @Override
4657    public List<ResolveInfo> queryIntentContentProviders(
4658            Intent intent, String resolvedType, int flags, int userId) {
4659        if (!sUserManager.exists(userId)) return Collections.emptyList();
4660        ComponentName comp = intent.getComponent();
4661        if (comp == null) {
4662            if (intent.getSelector() != null) {
4663                intent = intent.getSelector();
4664                comp = intent.getComponent();
4665            }
4666        }
4667        if (comp != null) {
4668            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4669            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
4670            if (pi != null) {
4671                final ResolveInfo ri = new ResolveInfo();
4672                ri.providerInfo = pi;
4673                list.add(ri);
4674            }
4675            return list;
4676        }
4677
4678        // reader
4679        synchronized (mPackages) {
4680            String pkgName = intent.getPackage();
4681            if (pkgName == null) {
4682                return mProviders.queryIntent(intent, resolvedType, flags, userId);
4683            }
4684            final PackageParser.Package pkg = mPackages.get(pkgName);
4685            if (pkg != null) {
4686                return mProviders.queryIntentForPackage(
4687                        intent, resolvedType, flags, pkg.providers, userId);
4688            }
4689            return null;
4690        }
4691    }
4692
4693    @Override
4694    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
4695        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4696
4697        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
4698
4699        // writer
4700        synchronized (mPackages) {
4701            ArrayList<PackageInfo> list;
4702            if (listUninstalled) {
4703                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
4704                for (PackageSetting ps : mSettings.mPackages.values()) {
4705                    PackageInfo pi;
4706                    if (ps.pkg != null) {
4707                        pi = generatePackageInfo(ps.pkg, flags, userId);
4708                    } else {
4709                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4710                    }
4711                    if (pi != null) {
4712                        list.add(pi);
4713                    }
4714                }
4715            } else {
4716                list = new ArrayList<PackageInfo>(mPackages.size());
4717                for (PackageParser.Package p : mPackages.values()) {
4718                    PackageInfo pi = generatePackageInfo(p, flags, userId);
4719                    if (pi != null) {
4720                        list.add(pi);
4721                    }
4722                }
4723            }
4724
4725            return new ParceledListSlice<PackageInfo>(list);
4726        }
4727    }
4728
4729    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
4730            String[] permissions, boolean[] tmp, int flags, int userId) {
4731        int numMatch = 0;
4732        final PermissionsState permissionsState = ps.getPermissionsState();
4733        for (int i=0; i<permissions.length; i++) {
4734            final String permission = permissions[i];
4735            if (permissionsState.hasPermission(permission, userId)) {
4736                tmp[i] = true;
4737                numMatch++;
4738            } else {
4739                tmp[i] = false;
4740            }
4741        }
4742        if (numMatch == 0) {
4743            return;
4744        }
4745        PackageInfo pi;
4746        if (ps.pkg != null) {
4747            pi = generatePackageInfo(ps.pkg, flags, userId);
4748        } else {
4749            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4750        }
4751        // The above might return null in cases of uninstalled apps or install-state
4752        // skew across users/profiles.
4753        if (pi != null) {
4754            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
4755                if (numMatch == permissions.length) {
4756                    pi.requestedPermissions = permissions;
4757                } else {
4758                    pi.requestedPermissions = new String[numMatch];
4759                    numMatch = 0;
4760                    for (int i=0; i<permissions.length; i++) {
4761                        if (tmp[i]) {
4762                            pi.requestedPermissions[numMatch] = permissions[i];
4763                            numMatch++;
4764                        }
4765                    }
4766                }
4767            }
4768            list.add(pi);
4769        }
4770    }
4771
4772    @Override
4773    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
4774            String[] permissions, int flags, int userId) {
4775        if (!sUserManager.exists(userId)) return null;
4776        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4777
4778        // writer
4779        synchronized (mPackages) {
4780            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
4781            boolean[] tmpBools = new boolean[permissions.length];
4782            if (listUninstalled) {
4783                for (PackageSetting ps : mSettings.mPackages.values()) {
4784                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
4785                }
4786            } else {
4787                for (PackageParser.Package pkg : mPackages.values()) {
4788                    PackageSetting ps = (PackageSetting)pkg.mExtras;
4789                    if (ps != null) {
4790                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
4791                                userId);
4792                    }
4793                }
4794            }
4795
4796            return new ParceledListSlice<PackageInfo>(list);
4797        }
4798    }
4799
4800    @Override
4801    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
4802        if (!sUserManager.exists(userId)) return null;
4803        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4804
4805        // writer
4806        synchronized (mPackages) {
4807            ArrayList<ApplicationInfo> list;
4808            if (listUninstalled) {
4809                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
4810                for (PackageSetting ps : mSettings.mPackages.values()) {
4811                    ApplicationInfo ai;
4812                    if (ps.pkg != null) {
4813                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4814                                ps.readUserState(userId), userId);
4815                    } else {
4816                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
4817                    }
4818                    if (ai != null) {
4819                        list.add(ai);
4820                    }
4821                }
4822            } else {
4823                list = new ArrayList<ApplicationInfo>(mPackages.size());
4824                for (PackageParser.Package p : mPackages.values()) {
4825                    if (p.mExtras != null) {
4826                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4827                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
4828                        if (ai != null) {
4829                            list.add(ai);
4830                        }
4831                    }
4832                }
4833            }
4834
4835            return new ParceledListSlice<ApplicationInfo>(list);
4836        }
4837    }
4838
4839    public List<ApplicationInfo> getPersistentApplications(int flags) {
4840        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
4841
4842        // reader
4843        synchronized (mPackages) {
4844            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
4845            final int userId = UserHandle.getCallingUserId();
4846            while (i.hasNext()) {
4847                final PackageParser.Package p = i.next();
4848                if (p.applicationInfo != null
4849                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
4850                        && (!mSafeMode || isSystemApp(p))) {
4851                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
4852                    if (ps != null) {
4853                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4854                                ps.readUserState(userId), userId);
4855                        if (ai != null) {
4856                            finalList.add(ai);
4857                        }
4858                    }
4859                }
4860            }
4861        }
4862
4863        return finalList;
4864    }
4865
4866    @Override
4867    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
4868        if (!sUserManager.exists(userId)) return null;
4869        // reader
4870        synchronized (mPackages) {
4871            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
4872            PackageSetting ps = provider != null
4873                    ? mSettings.mPackages.get(provider.owner.packageName)
4874                    : null;
4875            return ps != null
4876                    && mSettings.isEnabledLPr(provider.info, flags, userId)
4877                    && (!mSafeMode || (provider.info.applicationInfo.flags
4878                            &ApplicationInfo.FLAG_SYSTEM) != 0)
4879                    ? PackageParser.generateProviderInfo(provider, flags,
4880                            ps.readUserState(userId), userId)
4881                    : null;
4882        }
4883    }
4884
4885    /**
4886     * @deprecated
4887     */
4888    @Deprecated
4889    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
4890        // reader
4891        synchronized (mPackages) {
4892            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
4893                    .entrySet().iterator();
4894            final int userId = UserHandle.getCallingUserId();
4895            while (i.hasNext()) {
4896                Map.Entry<String, PackageParser.Provider> entry = i.next();
4897                PackageParser.Provider p = entry.getValue();
4898                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4899
4900                if (ps != null && p.syncable
4901                        && (!mSafeMode || (p.info.applicationInfo.flags
4902                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
4903                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
4904                            ps.readUserState(userId), userId);
4905                    if (info != null) {
4906                        outNames.add(entry.getKey());
4907                        outInfo.add(info);
4908                    }
4909                }
4910            }
4911        }
4912    }
4913
4914    @Override
4915    public List<ProviderInfo> queryContentProviders(String processName,
4916            int uid, int flags) {
4917        ArrayList<ProviderInfo> finalList = null;
4918        // reader
4919        synchronized (mPackages) {
4920            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
4921            final int userId = processName != null ?
4922                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
4923            while (i.hasNext()) {
4924                final PackageParser.Provider p = i.next();
4925                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4926                if (ps != null && p.info.authority != null
4927                        && (processName == null
4928                                || (p.info.processName.equals(processName)
4929                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
4930                        && mSettings.isEnabledLPr(p.info, flags, userId)
4931                        && (!mSafeMode
4932                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
4933                    if (finalList == null) {
4934                        finalList = new ArrayList<ProviderInfo>(3);
4935                    }
4936                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
4937                            ps.readUserState(userId), userId);
4938                    if (info != null) {
4939                        finalList.add(info);
4940                    }
4941                }
4942            }
4943        }
4944
4945        if (finalList != null) {
4946            Collections.sort(finalList, mProviderInitOrderSorter);
4947        }
4948
4949        return finalList;
4950    }
4951
4952    @Override
4953    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
4954            int flags) {
4955        // reader
4956        synchronized (mPackages) {
4957            final PackageParser.Instrumentation i = mInstrumentation.get(name);
4958            return PackageParser.generateInstrumentationInfo(i, flags);
4959        }
4960    }
4961
4962    @Override
4963    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4964            int flags) {
4965        ArrayList<InstrumentationInfo> finalList =
4966            new ArrayList<InstrumentationInfo>();
4967
4968        // reader
4969        synchronized (mPackages) {
4970            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4971            while (i.hasNext()) {
4972                final PackageParser.Instrumentation p = i.next();
4973                if (targetPackage == null
4974                        || targetPackage.equals(p.info.targetPackage)) {
4975                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4976                            flags);
4977                    if (ii != null) {
4978                        finalList.add(ii);
4979                    }
4980                }
4981            }
4982        }
4983
4984        return finalList;
4985    }
4986
4987    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4988        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4989        if (overlays == null) {
4990            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4991            return;
4992        }
4993        for (PackageParser.Package opkg : overlays.values()) {
4994            // Not much to do if idmap fails: we already logged the error
4995            // and we certainly don't want to abort installation of pkg simply
4996            // because an overlay didn't fit properly. For these reasons,
4997            // ignore the return value of createIdmapForPackagePairLI.
4998            createIdmapForPackagePairLI(pkg, opkg);
4999        }
5000    }
5001
5002    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5003            PackageParser.Package opkg) {
5004        if (!opkg.mTrustedOverlay) {
5005            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5006                    opkg.baseCodePath + ": overlay not trusted");
5007            return false;
5008        }
5009        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5010        if (overlaySet == null) {
5011            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5012                    opkg.baseCodePath + " but target package has no known overlays");
5013            return false;
5014        }
5015        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5016        // TODO: generate idmap for split APKs
5017        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5018            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5019                    + opkg.baseCodePath);
5020            return false;
5021        }
5022        PackageParser.Package[] overlayArray =
5023            overlaySet.values().toArray(new PackageParser.Package[0]);
5024        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5025            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5026                return p1.mOverlayPriority - p2.mOverlayPriority;
5027            }
5028        };
5029        Arrays.sort(overlayArray, cmp);
5030
5031        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5032        int i = 0;
5033        for (PackageParser.Package p : overlayArray) {
5034            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5035        }
5036        return true;
5037    }
5038
5039    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5040        final File[] files = dir.listFiles();
5041        if (ArrayUtils.isEmpty(files)) {
5042            Log.d(TAG, "No files in app dir " + dir);
5043            return;
5044        }
5045
5046        if (DEBUG_PACKAGE_SCANNING) {
5047            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5048                    + " flags=0x" + Integer.toHexString(parseFlags));
5049        }
5050
5051        for (File file : files) {
5052            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5053                    && !PackageInstallerService.isStageName(file.getName());
5054            if (!isPackage) {
5055                // Ignore entries which are not packages
5056                continue;
5057            }
5058            try {
5059                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5060                        scanFlags, currentTime, null);
5061            } catch (PackageManagerException e) {
5062                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5063
5064                // Delete invalid userdata apps
5065                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5066                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5067                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5068                    if (file.isDirectory()) {
5069                        mInstaller.rmPackageDir(file.getAbsolutePath());
5070                    } else {
5071                        file.delete();
5072                    }
5073                }
5074            }
5075        }
5076    }
5077
5078    private static File getSettingsProblemFile() {
5079        File dataDir = Environment.getDataDirectory();
5080        File systemDir = new File(dataDir, "system");
5081        File fname = new File(systemDir, "uiderrors.txt");
5082        return fname;
5083    }
5084
5085    static void reportSettingsProblem(int priority, String msg) {
5086        logCriticalInfo(priority, msg);
5087    }
5088
5089    static void logCriticalInfo(int priority, String msg) {
5090        Slog.println(priority, TAG, msg);
5091        EventLogTags.writePmCriticalInfo(msg);
5092        try {
5093            File fname = getSettingsProblemFile();
5094            FileOutputStream out = new FileOutputStream(fname, true);
5095            PrintWriter pw = new FastPrintWriter(out);
5096            SimpleDateFormat formatter = new SimpleDateFormat();
5097            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5098            pw.println(dateString + ": " + msg);
5099            pw.close();
5100            FileUtils.setPermissions(
5101                    fname.toString(),
5102                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5103                    -1, -1);
5104        } catch (java.io.IOException e) {
5105        }
5106    }
5107
5108    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5109            PackageParser.Package pkg, File srcFile, int parseFlags)
5110            throws PackageManagerException {
5111        if (ps != null
5112                && ps.codePath.equals(srcFile)
5113                && ps.timeStamp == srcFile.lastModified()
5114                && !isCompatSignatureUpdateNeeded(pkg)
5115                && !isRecoverSignatureUpdateNeeded(pkg)) {
5116            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5117            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5118            ArraySet<PublicKey> signingKs;
5119            synchronized (mPackages) {
5120                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5121            }
5122            if (ps.signatures.mSignatures != null
5123                    && ps.signatures.mSignatures.length != 0
5124                    && signingKs != null) {
5125                // Optimization: reuse the existing cached certificates
5126                // if the package appears to be unchanged.
5127                pkg.mSignatures = ps.signatures.mSignatures;
5128                pkg.mSigningKeys = signingKs;
5129                return;
5130            }
5131
5132            Slog.w(TAG, "PackageSetting for " + ps.name
5133                    + " is missing signatures.  Collecting certs again to recover them.");
5134        } else {
5135            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5136        }
5137
5138        try {
5139            pp.collectCertificates(pkg, parseFlags);
5140            pp.collectManifestDigest(pkg);
5141        } catch (PackageParserException e) {
5142            throw PackageManagerException.from(e);
5143        }
5144    }
5145
5146    /*
5147     *  Scan a package and return the newly parsed package.
5148     *  Returns null in case of errors and the error code is stored in mLastScanError
5149     */
5150    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5151            long currentTime, UserHandle user) throws PackageManagerException {
5152        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5153        parseFlags |= mDefParseFlags;
5154        PackageParser pp = new PackageParser();
5155        pp.setSeparateProcesses(mSeparateProcesses);
5156        pp.setOnlyCoreApps(mOnlyCore);
5157        pp.setDisplayMetrics(mMetrics);
5158
5159        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5160            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5161        }
5162
5163        final PackageParser.Package pkg;
5164        try {
5165            pkg = pp.parsePackage(scanFile, parseFlags);
5166        } catch (PackageParserException e) {
5167            throw PackageManagerException.from(e);
5168        }
5169
5170        PackageSetting ps = null;
5171        PackageSetting updatedPkg;
5172        // reader
5173        synchronized (mPackages) {
5174            // Look to see if we already know about this package.
5175            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5176            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5177                // This package has been renamed to its original name.  Let's
5178                // use that.
5179                ps = mSettings.peekPackageLPr(oldName);
5180            }
5181            // If there was no original package, see one for the real package name.
5182            if (ps == null) {
5183                ps = mSettings.peekPackageLPr(pkg.packageName);
5184            }
5185            // Check to see if this package could be hiding/updating a system
5186            // package.  Must look for it either under the original or real
5187            // package name depending on our state.
5188            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5189            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5190        }
5191        boolean updatedPkgBetter = false;
5192        // First check if this is a system package that may involve an update
5193        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5194            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5195            // it needs to drop FLAG_PRIVILEGED.
5196            if (locationIsPrivileged(scanFile)) {
5197                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5198            } else {
5199                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5200            }
5201
5202            if (ps != null && !ps.codePath.equals(scanFile)) {
5203                // The path has changed from what was last scanned...  check the
5204                // version of the new path against what we have stored to determine
5205                // what to do.
5206                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5207                if (pkg.mVersionCode <= ps.versionCode) {
5208                    // The system package has been updated and the code path does not match
5209                    // Ignore entry. Skip it.
5210                    Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5211                            + " ignored: updated version " + ps.versionCode
5212                            + " better than this " + pkg.mVersionCode);
5213                    if (!updatedPkg.codePath.equals(scanFile)) {
5214                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5215                                + ps.name + " changing from " + updatedPkg.codePathString
5216                                + " to " + scanFile);
5217                        updatedPkg.codePath = scanFile;
5218                        updatedPkg.codePathString = scanFile.toString();
5219                        updatedPkg.resourcePath = scanFile;
5220                        updatedPkg.resourcePathString = scanFile.toString();
5221                    }
5222                    updatedPkg.pkg = pkg;
5223                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
5224                } else {
5225                    // The current app on the system partition is better than
5226                    // what we have updated to on the data partition; switch
5227                    // back to the system partition version.
5228                    // At this point, its safely assumed that package installation for
5229                    // apps in system partition will go through. If not there won't be a working
5230                    // version of the app
5231                    // writer
5232                    synchronized (mPackages) {
5233                        // Just remove the loaded entries from package lists.
5234                        mPackages.remove(ps.name);
5235                    }
5236
5237                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5238                            + " reverting from " + ps.codePathString
5239                            + ": new version " + pkg.mVersionCode
5240                            + " better than installed " + ps.versionCode);
5241
5242                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5243                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5244                    synchronized (mInstallLock) {
5245                        args.cleanUpResourcesLI();
5246                    }
5247                    synchronized (mPackages) {
5248                        mSettings.enableSystemPackageLPw(ps.name);
5249                    }
5250                    updatedPkgBetter = true;
5251                }
5252            }
5253        }
5254
5255        if (updatedPkg != null) {
5256            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5257            // initially
5258            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5259
5260            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5261            // flag set initially
5262            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5263                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5264            }
5265        }
5266
5267        // Verify certificates against what was last scanned
5268        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5269
5270        /*
5271         * A new system app appeared, but we already had a non-system one of the
5272         * same name installed earlier.
5273         */
5274        boolean shouldHideSystemApp = false;
5275        if (updatedPkg == null && ps != null
5276                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5277            /*
5278             * Check to make sure the signatures match first. If they don't,
5279             * wipe the installed application and its data.
5280             */
5281            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5282                    != PackageManager.SIGNATURE_MATCH) {
5283                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5284                        + " signatures don't match existing userdata copy; removing");
5285                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5286                ps = null;
5287            } else {
5288                /*
5289                 * If the newly-added system app is an older version than the
5290                 * already installed version, hide it. It will be scanned later
5291                 * and re-added like an update.
5292                 */
5293                if (pkg.mVersionCode <= ps.versionCode) {
5294                    shouldHideSystemApp = true;
5295                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5296                            + " but new version " + pkg.mVersionCode + " better than installed "
5297                            + ps.versionCode + "; hiding system");
5298                } else {
5299                    /*
5300                     * The newly found system app is a newer version that the
5301                     * one previously installed. Simply remove the
5302                     * already-installed application and replace it with our own
5303                     * while keeping the application data.
5304                     */
5305                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5306                            + " reverting from " + ps.codePathString + ": new version "
5307                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5308                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5309                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5310                    synchronized (mInstallLock) {
5311                        args.cleanUpResourcesLI();
5312                    }
5313                }
5314            }
5315        }
5316
5317        // The apk is forward locked (not public) if its code and resources
5318        // are kept in different files. (except for app in either system or
5319        // vendor path).
5320        // TODO grab this value from PackageSettings
5321        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5322            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5323                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5324            }
5325        }
5326
5327        // TODO: extend to support forward-locked splits
5328        String resourcePath = null;
5329        String baseResourcePath = null;
5330        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5331            if (ps != null && ps.resourcePathString != null) {
5332                resourcePath = ps.resourcePathString;
5333                baseResourcePath = ps.resourcePathString;
5334            } else {
5335                // Should not happen at all. Just log an error.
5336                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5337            }
5338        } else {
5339            resourcePath = pkg.codePath;
5340            baseResourcePath = pkg.baseCodePath;
5341        }
5342
5343        // Set application objects path explicitly.
5344        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5345        pkg.applicationInfo.setCodePath(pkg.codePath);
5346        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5347        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5348        pkg.applicationInfo.setResourcePath(resourcePath);
5349        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5350        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5351
5352        // Note that we invoke the following method only if we are about to unpack an application
5353        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5354                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5355
5356        /*
5357         * If the system app should be overridden by a previously installed
5358         * data, hide the system app now and let the /data/app scan pick it up
5359         * again.
5360         */
5361        if (shouldHideSystemApp) {
5362            synchronized (mPackages) {
5363                /*
5364                 * We have to grant systems permissions before we hide, because
5365                 * grantPermissions will assume the package update is trying to
5366                 * expand its permissions.
5367                 */
5368                grantPermissionsLPw(pkg, true, pkg.packageName);
5369                mSettings.disableSystemPackageLPw(pkg.packageName);
5370            }
5371        }
5372
5373        return scannedPkg;
5374    }
5375
5376    private static String fixProcessName(String defProcessName,
5377            String processName, int uid) {
5378        if (processName == null) {
5379            return defProcessName;
5380        }
5381        return processName;
5382    }
5383
5384    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5385            throws PackageManagerException {
5386        if (pkgSetting.signatures.mSignatures != null) {
5387            // Already existing package. Make sure signatures match
5388            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5389                    == PackageManager.SIGNATURE_MATCH;
5390            if (!match) {
5391                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5392                        == PackageManager.SIGNATURE_MATCH;
5393            }
5394            if (!match) {
5395                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5396                        == PackageManager.SIGNATURE_MATCH;
5397            }
5398            if (!match) {
5399                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5400                        + pkg.packageName + " signatures do not match the "
5401                        + "previously installed version; ignoring!");
5402            }
5403        }
5404
5405        // Check for shared user signatures
5406        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5407            // Already existing package. Make sure signatures match
5408            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5409                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5410            if (!match) {
5411                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5412                        == PackageManager.SIGNATURE_MATCH;
5413            }
5414            if (!match) {
5415                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5416                        == PackageManager.SIGNATURE_MATCH;
5417            }
5418            if (!match) {
5419                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5420                        "Package " + pkg.packageName
5421                        + " has no signatures that match those in shared user "
5422                        + pkgSetting.sharedUser.name + "; ignoring!");
5423            }
5424        }
5425    }
5426
5427    /**
5428     * Enforces that only the system UID or root's UID can call a method exposed
5429     * via Binder.
5430     *
5431     * @param message used as message if SecurityException is thrown
5432     * @throws SecurityException if the caller is not system or root
5433     */
5434    private static final void enforceSystemOrRoot(String message) {
5435        final int uid = Binder.getCallingUid();
5436        if (uid != Process.SYSTEM_UID && uid != 0) {
5437            throw new SecurityException(message);
5438        }
5439    }
5440
5441    @Override
5442    public void performBootDexOpt() {
5443        enforceSystemOrRoot("Only the system can request dexopt be performed");
5444
5445        // Before everything else, see whether we need to fstrim.
5446        try {
5447            IMountService ms = PackageHelper.getMountService();
5448            if (ms != null) {
5449                final boolean isUpgrade = isUpgrade();
5450                boolean doTrim = isUpgrade;
5451                if (doTrim) {
5452                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5453                } else {
5454                    final long interval = android.provider.Settings.Global.getLong(
5455                            mContext.getContentResolver(),
5456                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5457                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5458                    if (interval > 0) {
5459                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5460                        if (timeSinceLast > interval) {
5461                            doTrim = true;
5462                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5463                                    + "; running immediately");
5464                        }
5465                    }
5466                }
5467                if (doTrim) {
5468                    if (!isFirstBoot()) {
5469                        try {
5470                            ActivityManagerNative.getDefault().showBootMessage(
5471                                    mContext.getResources().getString(
5472                                            R.string.android_upgrading_fstrim), true);
5473                        } catch (RemoteException e) {
5474                        }
5475                    }
5476                    ms.runMaintenance();
5477                }
5478            } else {
5479                Slog.e(TAG, "Mount service unavailable!");
5480            }
5481        } catch (RemoteException e) {
5482            // Can't happen; MountService is local
5483        }
5484
5485        final ArraySet<PackageParser.Package> pkgs;
5486        synchronized (mPackages) {
5487            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5488        }
5489
5490        if (pkgs != null) {
5491            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5492            // in case the device runs out of space.
5493            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5494            // Give priority to core apps.
5495            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5496                PackageParser.Package pkg = it.next();
5497                if (pkg.coreApp) {
5498                    if (DEBUG_DEXOPT) {
5499                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5500                    }
5501                    sortedPkgs.add(pkg);
5502                    it.remove();
5503                }
5504            }
5505            // Give priority to system apps that listen for pre boot complete.
5506            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5507            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
5508            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5509                PackageParser.Package pkg = it.next();
5510                if (pkgNames.contains(pkg.packageName)) {
5511                    if (DEBUG_DEXOPT) {
5512                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
5513                    }
5514                    sortedPkgs.add(pkg);
5515                    it.remove();
5516                }
5517            }
5518            // Give priority to system apps.
5519            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5520                PackageParser.Package pkg = it.next();
5521                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
5522                    if (DEBUG_DEXOPT) {
5523                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
5524                    }
5525                    sortedPkgs.add(pkg);
5526                    it.remove();
5527                }
5528            }
5529            // Give priority to updated system apps.
5530            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5531                PackageParser.Package pkg = it.next();
5532                if (pkg.isUpdatedSystemApp()) {
5533                    if (DEBUG_DEXOPT) {
5534                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
5535                    }
5536                    sortedPkgs.add(pkg);
5537                    it.remove();
5538                }
5539            }
5540            // Give priority to apps that listen for boot complete.
5541            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
5542            pkgNames = getPackageNamesForIntent(intent);
5543            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5544                PackageParser.Package pkg = it.next();
5545                if (pkgNames.contains(pkg.packageName)) {
5546                    if (DEBUG_DEXOPT) {
5547                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
5548                    }
5549                    sortedPkgs.add(pkg);
5550                    it.remove();
5551                }
5552            }
5553            // Filter out packages that aren't recently used.
5554            filterRecentlyUsedApps(pkgs);
5555            // Add all remaining apps.
5556            for (PackageParser.Package pkg : pkgs) {
5557                if (DEBUG_DEXOPT) {
5558                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
5559                }
5560                sortedPkgs.add(pkg);
5561            }
5562
5563            // If we want to be lazy, filter everything that wasn't recently used.
5564            if (mLazyDexOpt) {
5565                filterRecentlyUsedApps(sortedPkgs);
5566            }
5567
5568            int i = 0;
5569            int total = sortedPkgs.size();
5570            File dataDir = Environment.getDataDirectory();
5571            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
5572            if (lowThreshold == 0) {
5573                throw new IllegalStateException("Invalid low memory threshold");
5574            }
5575            for (PackageParser.Package pkg : sortedPkgs) {
5576                long usableSpace = dataDir.getUsableSpace();
5577                if (usableSpace < lowThreshold) {
5578                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
5579                    break;
5580                }
5581                performBootDexOpt(pkg, ++i, total);
5582            }
5583        }
5584    }
5585
5586    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
5587        // Filter out packages that aren't recently used.
5588        //
5589        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
5590        // should do a full dexopt.
5591        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
5592            int total = pkgs.size();
5593            int skipped = 0;
5594            long now = System.currentTimeMillis();
5595            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
5596                PackageParser.Package pkg = i.next();
5597                long then = pkg.mLastPackageUsageTimeInMills;
5598                if (then + mDexOptLRUThresholdInMills < now) {
5599                    if (DEBUG_DEXOPT) {
5600                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
5601                              ((then == 0) ? "never" : new Date(then)));
5602                    }
5603                    i.remove();
5604                    skipped++;
5605                }
5606            }
5607            if (DEBUG_DEXOPT) {
5608                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
5609            }
5610        }
5611    }
5612
5613    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
5614        List<ResolveInfo> ris = null;
5615        try {
5616            ris = AppGlobals.getPackageManager().queryIntentReceivers(
5617                    intent, null, 0, UserHandle.USER_OWNER);
5618        } catch (RemoteException e) {
5619        }
5620        ArraySet<String> pkgNames = new ArraySet<String>();
5621        if (ris != null) {
5622            for (ResolveInfo ri : ris) {
5623                pkgNames.add(ri.activityInfo.packageName);
5624            }
5625        }
5626        return pkgNames;
5627    }
5628
5629    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
5630        if (DEBUG_DEXOPT) {
5631            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
5632        }
5633        if (!isFirstBoot()) {
5634            try {
5635                ActivityManagerNative.getDefault().showBootMessage(
5636                        mContext.getResources().getString(R.string.android_upgrading_apk,
5637                                curr, total), true);
5638            } catch (RemoteException e) {
5639            }
5640        }
5641        PackageParser.Package p = pkg;
5642        synchronized (mInstallLock) {
5643            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
5644                    false /* force dex */, false /* defer */, true /* include dependencies */);
5645        }
5646    }
5647
5648    @Override
5649    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
5650        return performDexOpt(packageName, instructionSet, false);
5651    }
5652
5653    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
5654        boolean dexopt = mLazyDexOpt || backgroundDexopt;
5655        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
5656        if (!dexopt && !updateUsage) {
5657            // We aren't going to dexopt or update usage, so bail early.
5658            return false;
5659        }
5660        PackageParser.Package p;
5661        final String targetInstructionSet;
5662        synchronized (mPackages) {
5663            p = mPackages.get(packageName);
5664            if (p == null) {
5665                return false;
5666            }
5667            if (updateUsage) {
5668                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
5669            }
5670            mPackageUsage.write(false);
5671            if (!dexopt) {
5672                // We aren't going to dexopt, so bail early.
5673                return false;
5674            }
5675
5676            targetInstructionSet = instructionSet != null ? instructionSet :
5677                    getPrimaryInstructionSet(p.applicationInfo);
5678            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
5679                return false;
5680            }
5681        }
5682
5683        synchronized (mInstallLock) {
5684            final String[] instructionSets = new String[] { targetInstructionSet };
5685            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
5686                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
5687            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
5688        }
5689    }
5690
5691    public ArraySet<String> getPackagesThatNeedDexOpt() {
5692        ArraySet<String> pkgs = null;
5693        synchronized (mPackages) {
5694            for (PackageParser.Package p : mPackages.values()) {
5695                if (DEBUG_DEXOPT) {
5696                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
5697                }
5698                if (!p.mDexOptPerformed.isEmpty()) {
5699                    continue;
5700                }
5701                if (pkgs == null) {
5702                    pkgs = new ArraySet<String>();
5703                }
5704                pkgs.add(p.packageName);
5705            }
5706        }
5707        return pkgs;
5708    }
5709
5710    public void shutdown() {
5711        mPackageUsage.write(true);
5712    }
5713
5714    @Override
5715    public void forceDexOpt(String packageName) {
5716        enforceSystemOrRoot("forceDexOpt");
5717
5718        PackageParser.Package pkg;
5719        synchronized (mPackages) {
5720            pkg = mPackages.get(packageName);
5721            if (pkg == null) {
5722                throw new IllegalArgumentException("Missing package: " + packageName);
5723            }
5724        }
5725
5726        synchronized (mInstallLock) {
5727            final String[] instructionSets = new String[] {
5728                    getPrimaryInstructionSet(pkg.applicationInfo) };
5729            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
5730                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
5731            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
5732                throw new IllegalStateException("Failed to dexopt: " + res);
5733            }
5734        }
5735    }
5736
5737    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
5738        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
5739            Slog.w(TAG, "Unable to update from " + oldPkg.name
5740                    + " to " + newPkg.packageName
5741                    + ": old package not in system partition");
5742            return false;
5743        } else if (mPackages.get(oldPkg.name) != null) {
5744            Slog.w(TAG, "Unable to update from " + oldPkg.name
5745                    + " to " + newPkg.packageName
5746                    + ": old package still exists");
5747            return false;
5748        }
5749        return true;
5750    }
5751
5752    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
5753        int[] users = sUserManager.getUserIds();
5754        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
5755        if (res < 0) {
5756            return res;
5757        }
5758        for (int user : users) {
5759            if (user != 0) {
5760                res = mInstaller.createUserData(volumeUuid, packageName,
5761                        UserHandle.getUid(user, uid), user, seinfo);
5762                if (res < 0) {
5763                    return res;
5764                }
5765            }
5766        }
5767        return res;
5768    }
5769
5770    private int removeDataDirsLI(String volumeUuid, String packageName) {
5771        int[] users = sUserManager.getUserIds();
5772        int res = 0;
5773        for (int user : users) {
5774            int resInner = mInstaller.remove(volumeUuid, packageName, user);
5775            if (resInner < 0) {
5776                res = resInner;
5777            }
5778        }
5779
5780        return res;
5781    }
5782
5783    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
5784        int[] users = sUserManager.getUserIds();
5785        int res = 0;
5786        for (int user : users) {
5787            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
5788            if (resInner < 0) {
5789                res = resInner;
5790            }
5791        }
5792        return res;
5793    }
5794
5795    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
5796            PackageParser.Package changingLib) {
5797        if (file.path != null) {
5798            usesLibraryFiles.add(file.path);
5799            return;
5800        }
5801        PackageParser.Package p = mPackages.get(file.apk);
5802        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
5803            // If we are doing this while in the middle of updating a library apk,
5804            // then we need to make sure to use that new apk for determining the
5805            // dependencies here.  (We haven't yet finished committing the new apk
5806            // to the package manager state.)
5807            if (p == null || p.packageName.equals(changingLib.packageName)) {
5808                p = changingLib;
5809            }
5810        }
5811        if (p != null) {
5812            usesLibraryFiles.addAll(p.getAllCodePaths());
5813        }
5814    }
5815
5816    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
5817            PackageParser.Package changingLib) throws PackageManagerException {
5818        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
5819            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
5820            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
5821            for (int i=0; i<N; i++) {
5822                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
5823                if (file == null) {
5824                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
5825                            "Package " + pkg.packageName + " requires unavailable shared library "
5826                            + pkg.usesLibraries.get(i) + "; failing!");
5827                }
5828                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5829            }
5830            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
5831            for (int i=0; i<N; i++) {
5832                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
5833                if (file == null) {
5834                    Slog.w(TAG, "Package " + pkg.packageName
5835                            + " desires unavailable shared library "
5836                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
5837                } else {
5838                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5839                }
5840            }
5841            N = usesLibraryFiles.size();
5842            if (N > 0) {
5843                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
5844            } else {
5845                pkg.usesLibraryFiles = null;
5846            }
5847        }
5848    }
5849
5850    private static boolean hasString(List<String> list, List<String> which) {
5851        if (list == null) {
5852            return false;
5853        }
5854        for (int i=list.size()-1; i>=0; i--) {
5855            for (int j=which.size()-1; j>=0; j--) {
5856                if (which.get(j).equals(list.get(i))) {
5857                    return true;
5858                }
5859            }
5860        }
5861        return false;
5862    }
5863
5864    private void updateAllSharedLibrariesLPw() {
5865        for (PackageParser.Package pkg : mPackages.values()) {
5866            try {
5867                updateSharedLibrariesLPw(pkg, null);
5868            } catch (PackageManagerException e) {
5869                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5870            }
5871        }
5872    }
5873
5874    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
5875            PackageParser.Package changingPkg) {
5876        ArrayList<PackageParser.Package> res = null;
5877        for (PackageParser.Package pkg : mPackages.values()) {
5878            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
5879                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
5880                if (res == null) {
5881                    res = new ArrayList<PackageParser.Package>();
5882                }
5883                res.add(pkg);
5884                try {
5885                    updateSharedLibrariesLPw(pkg, changingPkg);
5886                } catch (PackageManagerException e) {
5887                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5888                }
5889            }
5890        }
5891        return res;
5892    }
5893
5894    /**
5895     * Derive the value of the {@code cpuAbiOverride} based on the provided
5896     * value and an optional stored value from the package settings.
5897     */
5898    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
5899        String cpuAbiOverride = null;
5900
5901        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
5902            cpuAbiOverride = null;
5903        } else if (abiOverride != null) {
5904            cpuAbiOverride = abiOverride;
5905        } else if (settings != null) {
5906            cpuAbiOverride = settings.cpuAbiOverrideString;
5907        }
5908
5909        return cpuAbiOverride;
5910    }
5911
5912    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
5913            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5914        boolean success = false;
5915        try {
5916            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
5917                    currentTime, user);
5918            success = true;
5919            return res;
5920        } finally {
5921            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5922                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
5923            }
5924        }
5925    }
5926
5927    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
5928            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5929        final File scanFile = new File(pkg.codePath);
5930        if (pkg.applicationInfo.getCodePath() == null ||
5931                pkg.applicationInfo.getResourcePath() == null) {
5932            // Bail out. The resource and code paths haven't been set.
5933            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
5934                    "Code and resource paths haven't been set correctly");
5935        }
5936
5937        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5938            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
5939        } else {
5940            // Only allow system apps to be flagged as core apps.
5941            pkg.coreApp = false;
5942        }
5943
5944        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5945            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5946        }
5947
5948        if (mCustomResolverComponentName != null &&
5949                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5950            setUpCustomResolverActivity(pkg);
5951        }
5952
5953        if (pkg.packageName.equals("android")) {
5954            synchronized (mPackages) {
5955                if (mAndroidApplication != null) {
5956                    Slog.w(TAG, "*************************************************");
5957                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5958                    Slog.w(TAG, " file=" + scanFile);
5959                    Slog.w(TAG, "*************************************************");
5960                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5961                            "Core android package being redefined.  Skipping.");
5962                }
5963
5964                // Set up information for our fall-back user intent resolution activity.
5965                mPlatformPackage = pkg;
5966                pkg.mVersionCode = mSdkVersion;
5967                mAndroidApplication = pkg.applicationInfo;
5968
5969                if (!mResolverReplaced) {
5970                    mResolveActivity.applicationInfo = mAndroidApplication;
5971                    mResolveActivity.name = ResolverActivity.class.getName();
5972                    mResolveActivity.packageName = mAndroidApplication.packageName;
5973                    mResolveActivity.processName = "system:ui";
5974                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5975                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5976                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5977                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5978                    mResolveActivity.exported = true;
5979                    mResolveActivity.enabled = true;
5980                    mResolveInfo.activityInfo = mResolveActivity;
5981                    mResolveInfo.priority = 0;
5982                    mResolveInfo.preferredOrder = 0;
5983                    mResolveInfo.match = 0;
5984                    mResolveComponentName = new ComponentName(
5985                            mAndroidApplication.packageName, mResolveActivity.name);
5986                }
5987            }
5988        }
5989
5990        if (DEBUG_PACKAGE_SCANNING) {
5991            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5992                Log.d(TAG, "Scanning package " + pkg.packageName);
5993        }
5994
5995        if (mPackages.containsKey(pkg.packageName)
5996                || mSharedLibraries.containsKey(pkg.packageName)) {
5997            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5998                    "Application package " + pkg.packageName
5999                    + " already installed.  Skipping duplicate.");
6000        }
6001
6002        // If we're only installing presumed-existing packages, require that the
6003        // scanned APK is both already known and at the path previously established
6004        // for it.  Previously unknown packages we pick up normally, but if we have an
6005        // a priori expectation about this package's install presence, enforce it.
6006        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6007            PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6008            if (known != null) {
6009                if (DEBUG_PACKAGE_SCANNING) {
6010                    Log.d(TAG, "Examining " + pkg.codePath
6011                            + " and requiring known paths " + known.codePathString
6012                            + " & " + known.resourcePathString);
6013                }
6014                if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6015                        || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6016                    throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6017                            "Application package " + pkg.packageName
6018                            + " found at " + pkg.applicationInfo.getCodePath()
6019                            + " but expected at " + known.codePathString + "; ignoring.");
6020                }
6021            }
6022        }
6023
6024        // Initialize package source and resource directories
6025        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6026        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6027
6028        SharedUserSetting suid = null;
6029        PackageSetting pkgSetting = null;
6030
6031        if (!isSystemApp(pkg)) {
6032            // Only system apps can use these features.
6033            pkg.mOriginalPackages = null;
6034            pkg.mRealPackage = null;
6035            pkg.mAdoptPermissions = null;
6036        }
6037
6038        // writer
6039        synchronized (mPackages) {
6040            if (pkg.mSharedUserId != null) {
6041                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6042                if (suid == null) {
6043                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6044                            "Creating application package " + pkg.packageName
6045                            + " for shared user failed");
6046                }
6047                if (DEBUG_PACKAGE_SCANNING) {
6048                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6049                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6050                                + "): packages=" + suid.packages);
6051                }
6052            }
6053
6054            // Check if we are renaming from an original package name.
6055            PackageSetting origPackage = null;
6056            String realName = null;
6057            if (pkg.mOriginalPackages != null) {
6058                // This package may need to be renamed to a previously
6059                // installed name.  Let's check on that...
6060                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6061                if (pkg.mOriginalPackages.contains(renamed)) {
6062                    // This package had originally been installed as the
6063                    // original name, and we have already taken care of
6064                    // transitioning to the new one.  Just update the new
6065                    // one to continue using the old name.
6066                    realName = pkg.mRealPackage;
6067                    if (!pkg.packageName.equals(renamed)) {
6068                        // Callers into this function may have already taken
6069                        // care of renaming the package; only do it here if
6070                        // it is not already done.
6071                        pkg.setPackageName(renamed);
6072                    }
6073
6074                } else {
6075                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6076                        if ((origPackage = mSettings.peekPackageLPr(
6077                                pkg.mOriginalPackages.get(i))) != null) {
6078                            // We do have the package already installed under its
6079                            // original name...  should we use it?
6080                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6081                                // New package is not compatible with original.
6082                                origPackage = null;
6083                                continue;
6084                            } else if (origPackage.sharedUser != null) {
6085                                // Make sure uid is compatible between packages.
6086                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6087                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6088                                            + " to " + pkg.packageName + ": old uid "
6089                                            + origPackage.sharedUser.name
6090                                            + " differs from " + pkg.mSharedUserId);
6091                                    origPackage = null;
6092                                    continue;
6093                                }
6094                            } else {
6095                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6096                                        + pkg.packageName + " to old name " + origPackage.name);
6097                            }
6098                            break;
6099                        }
6100                    }
6101                }
6102            }
6103
6104            if (mTransferedPackages.contains(pkg.packageName)) {
6105                Slog.w(TAG, "Package " + pkg.packageName
6106                        + " was transferred to another, but its .apk remains");
6107            }
6108
6109            // Just create the setting, don't add it yet. For already existing packages
6110            // the PkgSetting exists already and doesn't have to be created.
6111            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6112                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6113                    pkg.applicationInfo.primaryCpuAbi,
6114                    pkg.applicationInfo.secondaryCpuAbi,
6115                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6116                    user, false);
6117            if (pkgSetting == null) {
6118                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6119                        "Creating application package " + pkg.packageName + " failed");
6120            }
6121
6122            if (pkgSetting.origPackage != null) {
6123                // If we are first transitioning from an original package,
6124                // fix up the new package's name now.  We need to do this after
6125                // looking up the package under its new name, so getPackageLP
6126                // can take care of fiddling things correctly.
6127                pkg.setPackageName(origPackage.name);
6128
6129                // File a report about this.
6130                String msg = "New package " + pkgSetting.realName
6131                        + " renamed to replace old package " + pkgSetting.name;
6132                reportSettingsProblem(Log.WARN, msg);
6133
6134                // Make a note of it.
6135                mTransferedPackages.add(origPackage.name);
6136
6137                // No longer need to retain this.
6138                pkgSetting.origPackage = null;
6139            }
6140
6141            if (realName != null) {
6142                // Make a note of it.
6143                mTransferedPackages.add(pkg.packageName);
6144            }
6145
6146            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6147                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6148            }
6149
6150            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6151                // Check all shared libraries and map to their actual file path.
6152                // We only do this here for apps not on a system dir, because those
6153                // are the only ones that can fail an install due to this.  We
6154                // will take care of the system apps by updating all of their
6155                // library paths after the scan is done.
6156                updateSharedLibrariesLPw(pkg, null);
6157            }
6158
6159            if (mFoundPolicyFile) {
6160                SELinuxMMAC.assignSeinfoValue(pkg);
6161            }
6162
6163            pkg.applicationInfo.uid = pkgSetting.appId;
6164            pkg.mExtras = pkgSetting;
6165            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6166                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6167                    // We just determined the app is signed correctly, so bring
6168                    // over the latest parsed certs.
6169                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6170                } else {
6171                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6172                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6173                                "Package " + pkg.packageName + " upgrade keys do not match the "
6174                                + "previously installed version");
6175                    } else {
6176                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6177                        String msg = "System package " + pkg.packageName
6178                            + " signature changed; retaining data.";
6179                        reportSettingsProblem(Log.WARN, msg);
6180                    }
6181                }
6182            } else {
6183                try {
6184                    verifySignaturesLP(pkgSetting, pkg);
6185                    // We just determined the app is signed correctly, so bring
6186                    // over the latest parsed certs.
6187                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6188                } catch (PackageManagerException e) {
6189                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6190                        throw e;
6191                    }
6192                    // The signature has changed, but this package is in the system
6193                    // image...  let's recover!
6194                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6195                    // However...  if this package is part of a shared user, but it
6196                    // doesn't match the signature of the shared user, let's fail.
6197                    // What this means is that you can't change the signatures
6198                    // associated with an overall shared user, which doesn't seem all
6199                    // that unreasonable.
6200                    if (pkgSetting.sharedUser != null) {
6201                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6202                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6203                            throw new PackageManagerException(
6204                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6205                                            "Signature mismatch for shared user : "
6206                                            + pkgSetting.sharedUser);
6207                        }
6208                    }
6209                    // File a report about this.
6210                    String msg = "System package " + pkg.packageName
6211                        + " signature changed; retaining data.";
6212                    reportSettingsProblem(Log.WARN, msg);
6213                }
6214            }
6215            // Verify that this new package doesn't have any content providers
6216            // that conflict with existing packages.  Only do this if the
6217            // package isn't already installed, since we don't want to break
6218            // things that are installed.
6219            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6220                final int N = pkg.providers.size();
6221                int i;
6222                for (i=0; i<N; i++) {
6223                    PackageParser.Provider p = pkg.providers.get(i);
6224                    if (p.info.authority != null) {
6225                        String names[] = p.info.authority.split(";");
6226                        for (int j = 0; j < names.length; j++) {
6227                            if (mProvidersByAuthority.containsKey(names[j])) {
6228                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6229                                final String otherPackageName =
6230                                        ((other != null && other.getComponentName() != null) ?
6231                                                other.getComponentName().getPackageName() : "?");
6232                                throw new PackageManagerException(
6233                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6234                                                "Can't install because provider name " + names[j]
6235                                                + " (in package " + pkg.applicationInfo.packageName
6236                                                + ") is already used by " + otherPackageName);
6237                            }
6238                        }
6239                    }
6240                }
6241            }
6242
6243            if (pkg.mAdoptPermissions != null) {
6244                // This package wants to adopt ownership of permissions from
6245                // another package.
6246                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6247                    final String origName = pkg.mAdoptPermissions.get(i);
6248                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6249                    if (orig != null) {
6250                        if (verifyPackageUpdateLPr(orig, pkg)) {
6251                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6252                                    + pkg.packageName);
6253                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6254                        }
6255                    }
6256                }
6257            }
6258        }
6259
6260        final String pkgName = pkg.packageName;
6261
6262        final long scanFileTime = scanFile.lastModified();
6263        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6264        pkg.applicationInfo.processName = fixProcessName(
6265                pkg.applicationInfo.packageName,
6266                pkg.applicationInfo.processName,
6267                pkg.applicationInfo.uid);
6268
6269        File dataPath;
6270        if (mPlatformPackage == pkg) {
6271            // The system package is special.
6272            dataPath = new File(Environment.getDataDirectory(), "system");
6273
6274            pkg.applicationInfo.dataDir = dataPath.getPath();
6275
6276        } else {
6277            // This is a normal package, need to make its data directory.
6278            dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName,
6279                    UserHandle.USER_OWNER);
6280
6281            boolean uidError = false;
6282            if (dataPath.exists()) {
6283                int currentUid = 0;
6284                try {
6285                    StructStat stat = Os.stat(dataPath.getPath());
6286                    currentUid = stat.st_uid;
6287                } catch (ErrnoException e) {
6288                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6289                }
6290
6291                // If we have mismatched owners for the data path, we have a problem.
6292                if (currentUid != pkg.applicationInfo.uid) {
6293                    boolean recovered = false;
6294                    if (currentUid == 0) {
6295                        // The directory somehow became owned by root.  Wow.
6296                        // This is probably because the system was stopped while
6297                        // installd was in the middle of messing with its libs
6298                        // directory.  Ask installd to fix that.
6299                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6300                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6301                        if (ret >= 0) {
6302                            recovered = true;
6303                            String msg = "Package " + pkg.packageName
6304                                    + " unexpectedly changed to uid 0; recovered to " +
6305                                    + pkg.applicationInfo.uid;
6306                            reportSettingsProblem(Log.WARN, msg);
6307                        }
6308                    }
6309                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6310                            || (scanFlags&SCAN_BOOTING) != 0)) {
6311                        // If this is a system app, we can at least delete its
6312                        // current data so the application will still work.
6313                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6314                        if (ret >= 0) {
6315                            // TODO: Kill the processes first
6316                            // Old data gone!
6317                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6318                                    ? "System package " : "Third party package ";
6319                            String msg = prefix + pkg.packageName
6320                                    + " has changed from uid: "
6321                                    + currentUid + " to "
6322                                    + pkg.applicationInfo.uid + "; old data erased";
6323                            reportSettingsProblem(Log.WARN, msg);
6324                            recovered = true;
6325
6326                            // And now re-install the app.
6327                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6328                                    pkg.applicationInfo.seinfo);
6329                            if (ret == -1) {
6330                                // Ack should not happen!
6331                                msg = prefix + pkg.packageName
6332                                        + " could not have data directory re-created after delete.";
6333                                reportSettingsProblem(Log.WARN, msg);
6334                                throw new PackageManagerException(
6335                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6336                            }
6337                        }
6338                        if (!recovered) {
6339                            mHasSystemUidErrors = true;
6340                        }
6341                    } else if (!recovered) {
6342                        // If we allow this install to proceed, we will be broken.
6343                        // Abort, abort!
6344                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6345                                "scanPackageLI");
6346                    }
6347                    if (!recovered) {
6348                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6349                            + pkg.applicationInfo.uid + "/fs_"
6350                            + currentUid;
6351                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6352                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6353                        String msg = "Package " + pkg.packageName
6354                                + " has mismatched uid: "
6355                                + currentUid + " on disk, "
6356                                + pkg.applicationInfo.uid + " in settings";
6357                        // writer
6358                        synchronized (mPackages) {
6359                            mSettings.mReadMessages.append(msg);
6360                            mSettings.mReadMessages.append('\n');
6361                            uidError = true;
6362                            if (!pkgSetting.uidError) {
6363                                reportSettingsProblem(Log.ERROR, msg);
6364                            }
6365                        }
6366                    }
6367                }
6368                pkg.applicationInfo.dataDir = dataPath.getPath();
6369                if (mShouldRestoreconData) {
6370                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6371                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6372                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6373                }
6374            } else {
6375                if (DEBUG_PACKAGE_SCANNING) {
6376                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6377                        Log.v(TAG, "Want this data dir: " + dataPath);
6378                }
6379                //invoke installer to do the actual installation
6380                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6381                        pkg.applicationInfo.seinfo);
6382                if (ret < 0) {
6383                    // Error from installer
6384                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6385                            "Unable to create data dirs [errorCode=" + ret + "]");
6386                }
6387
6388                if (dataPath.exists()) {
6389                    pkg.applicationInfo.dataDir = dataPath.getPath();
6390                } else {
6391                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6392                    pkg.applicationInfo.dataDir = null;
6393                }
6394            }
6395
6396            pkgSetting.uidError = uidError;
6397        }
6398
6399        final String path = scanFile.getPath();
6400        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6401
6402        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6403            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6404
6405            // Some system apps still use directory structure for native libraries
6406            // in which case we might end up not detecting abi solely based on apk
6407            // structure. Try to detect abi based on directory structure.
6408            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6409                    pkg.applicationInfo.primaryCpuAbi == null) {
6410                setBundledAppAbisAndRoots(pkg, pkgSetting);
6411                setNativeLibraryPaths(pkg);
6412            }
6413
6414        } else {
6415            if ((scanFlags & SCAN_MOVE) != 0) {
6416                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6417                // but we already have this packages package info in the PackageSetting. We just
6418                // use that and derive the native library path based on the new codepath.
6419                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6420                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6421            }
6422
6423            // Set native library paths again. For moves, the path will be updated based on the
6424            // ABIs we've determined above. For non-moves, the path will be updated based on the
6425            // ABIs we determined during compilation, but the path will depend on the final
6426            // package path (after the rename away from the stage path).
6427            setNativeLibraryPaths(pkg);
6428        }
6429
6430        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6431        final int[] userIds = sUserManager.getUserIds();
6432        synchronized (mInstallLock) {
6433            // Create a native library symlink only if we have native libraries
6434            // and if the native libraries are 32 bit libraries. We do not provide
6435            // this symlink for 64 bit libraries.
6436            if (pkg.applicationInfo.primaryCpuAbi != null &&
6437                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6438                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6439                for (int userId : userIds) {
6440                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6441                            nativeLibPath, userId) < 0) {
6442                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6443                                "Failed linking native library dir (user=" + userId + ")");
6444                    }
6445                }
6446            }
6447        }
6448
6449        // This is a special case for the "system" package, where the ABI is
6450        // dictated by the zygote configuration (and init.rc). We should keep track
6451        // of this ABI so that we can deal with "normal" applications that run under
6452        // the same UID correctly.
6453        if (mPlatformPackage == pkg) {
6454            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6455                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6456        }
6457
6458        // If there's a mismatch between the abi-override in the package setting
6459        // and the abiOverride specified for the install. Warn about this because we
6460        // would've already compiled the app without taking the package setting into
6461        // account.
6462        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
6463            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
6464                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
6465                        " for package: " + pkg.packageName);
6466            }
6467        }
6468
6469        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6470        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6471        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6472
6473        // Copy the derived override back to the parsed package, so that we can
6474        // update the package settings accordingly.
6475        pkg.cpuAbiOverride = cpuAbiOverride;
6476
6477        if (DEBUG_ABI_SELECTION) {
6478            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6479                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6480                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6481        }
6482
6483        // Push the derived path down into PackageSettings so we know what to
6484        // clean up at uninstall time.
6485        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6486
6487        if (DEBUG_ABI_SELECTION) {
6488            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6489                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6490                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6491        }
6492
6493        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6494            // We don't do this here during boot because we can do it all
6495            // at once after scanning all existing packages.
6496            //
6497            // We also do this *before* we perform dexopt on this package, so that
6498            // we can avoid redundant dexopts, and also to make sure we've got the
6499            // code and package path correct.
6500            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
6501                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
6502        }
6503
6504        if ((scanFlags & SCAN_NO_DEX) == 0) {
6505            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
6506                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
6507            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6508                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
6509            }
6510        }
6511        if (mFactoryTest && pkg.requestedPermissions.contains(
6512                android.Manifest.permission.FACTORY_TEST)) {
6513            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
6514        }
6515
6516        ArrayList<PackageParser.Package> clientLibPkgs = null;
6517
6518        // writer
6519        synchronized (mPackages) {
6520            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6521                // Only system apps can add new shared libraries.
6522                if (pkg.libraryNames != null) {
6523                    for (int i=0; i<pkg.libraryNames.size(); i++) {
6524                        String name = pkg.libraryNames.get(i);
6525                        boolean allowed = false;
6526                        if (pkg.isUpdatedSystemApp()) {
6527                            // New library entries can only be added through the
6528                            // system image.  This is important to get rid of a lot
6529                            // of nasty edge cases: for example if we allowed a non-
6530                            // system update of the app to add a library, then uninstalling
6531                            // the update would make the library go away, and assumptions
6532                            // we made such as through app install filtering would now
6533                            // have allowed apps on the device which aren't compatible
6534                            // with it.  Better to just have the restriction here, be
6535                            // conservative, and create many fewer cases that can negatively
6536                            // impact the user experience.
6537                            final PackageSetting sysPs = mSettings
6538                                    .getDisabledSystemPkgLPr(pkg.packageName);
6539                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
6540                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
6541                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
6542                                        allowed = true;
6543                                        allowed = true;
6544                                        break;
6545                                    }
6546                                }
6547                            }
6548                        } else {
6549                            allowed = true;
6550                        }
6551                        if (allowed) {
6552                            if (!mSharedLibraries.containsKey(name)) {
6553                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
6554                            } else if (!name.equals(pkg.packageName)) {
6555                                Slog.w(TAG, "Package " + pkg.packageName + " library "
6556                                        + name + " already exists; skipping");
6557                            }
6558                        } else {
6559                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
6560                                    + name + " that is not declared on system image; skipping");
6561                        }
6562                    }
6563                    if ((scanFlags&SCAN_BOOTING) == 0) {
6564                        // If we are not booting, we need to update any applications
6565                        // that are clients of our shared library.  If we are booting,
6566                        // this will all be done once the scan is complete.
6567                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
6568                    }
6569                }
6570            }
6571        }
6572
6573        // We also need to dexopt any apps that are dependent on this library.  Note that
6574        // if these fail, we should abort the install since installing the library will
6575        // result in some apps being broken.
6576        if (clientLibPkgs != null) {
6577            if ((scanFlags & SCAN_NO_DEX) == 0) {
6578                for (int i = 0; i < clientLibPkgs.size(); i++) {
6579                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
6580                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
6581                            null /* instruction sets */, forceDex,
6582                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
6583                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6584                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
6585                                "scanPackageLI failed to dexopt clientLibPkgs");
6586                    }
6587                }
6588            }
6589        }
6590
6591        // Also need to kill any apps that are dependent on the library.
6592        if (clientLibPkgs != null) {
6593            for (int i=0; i<clientLibPkgs.size(); i++) {
6594                PackageParser.Package clientPkg = clientLibPkgs.get(i);
6595                killApplication(clientPkg.applicationInfo.packageName,
6596                        clientPkg.applicationInfo.uid, "update lib");
6597            }
6598        }
6599
6600        // Make sure we're not adding any bogus keyset info
6601        KeySetManagerService ksms = mSettings.mKeySetManagerService;
6602        ksms.assertScannedPackageValid(pkg);
6603
6604        // writer
6605        synchronized (mPackages) {
6606            // We don't expect installation to fail beyond this point
6607
6608            // Add the new setting to mSettings
6609            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
6610            // Add the new setting to mPackages
6611            mPackages.put(pkg.applicationInfo.packageName, pkg);
6612            // Make sure we don't accidentally delete its data.
6613            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
6614            while (iter.hasNext()) {
6615                PackageCleanItem item = iter.next();
6616                if (pkgName.equals(item.packageName)) {
6617                    iter.remove();
6618                }
6619            }
6620
6621            // Take care of first install / last update times.
6622            if (currentTime != 0) {
6623                if (pkgSetting.firstInstallTime == 0) {
6624                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
6625                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
6626                    pkgSetting.lastUpdateTime = currentTime;
6627                }
6628            } else if (pkgSetting.firstInstallTime == 0) {
6629                // We need *something*.  Take time time stamp of the file.
6630                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
6631            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
6632                if (scanFileTime != pkgSetting.timeStamp) {
6633                    // A package on the system image has changed; consider this
6634                    // to be an update.
6635                    pkgSetting.lastUpdateTime = scanFileTime;
6636                }
6637            }
6638
6639            // Add the package's KeySets to the global KeySetManagerService
6640            ksms.addScannedPackageLPw(pkg);
6641
6642            int N = pkg.providers.size();
6643            StringBuilder r = null;
6644            int i;
6645            for (i=0; i<N; i++) {
6646                PackageParser.Provider p = pkg.providers.get(i);
6647                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
6648                        p.info.processName, pkg.applicationInfo.uid);
6649                mProviders.addProvider(p);
6650                p.syncable = p.info.isSyncable;
6651                if (p.info.authority != null) {
6652                    String names[] = p.info.authority.split(";");
6653                    p.info.authority = null;
6654                    for (int j = 0; j < names.length; j++) {
6655                        if (j == 1 && p.syncable) {
6656                            // We only want the first authority for a provider to possibly be
6657                            // syncable, so if we already added this provider using a different
6658                            // authority clear the syncable flag. We copy the provider before
6659                            // changing it because the mProviders object contains a reference
6660                            // to a provider that we don't want to change.
6661                            // Only do this for the second authority since the resulting provider
6662                            // object can be the same for all future authorities for this provider.
6663                            p = new PackageParser.Provider(p);
6664                            p.syncable = false;
6665                        }
6666                        if (!mProvidersByAuthority.containsKey(names[j])) {
6667                            mProvidersByAuthority.put(names[j], p);
6668                            if (p.info.authority == null) {
6669                                p.info.authority = names[j];
6670                            } else {
6671                                p.info.authority = p.info.authority + ";" + names[j];
6672                            }
6673                            if (DEBUG_PACKAGE_SCANNING) {
6674                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6675                                    Log.d(TAG, "Registered content provider: " + names[j]
6676                                            + ", className = " + p.info.name + ", isSyncable = "
6677                                            + p.info.isSyncable);
6678                            }
6679                        } else {
6680                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6681                            Slog.w(TAG, "Skipping provider name " + names[j] +
6682                                    " (in package " + pkg.applicationInfo.packageName +
6683                                    "): name already used by "
6684                                    + ((other != null && other.getComponentName() != null)
6685                                            ? other.getComponentName().getPackageName() : "?"));
6686                        }
6687                    }
6688                }
6689                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6690                    if (r == null) {
6691                        r = new StringBuilder(256);
6692                    } else {
6693                        r.append(' ');
6694                    }
6695                    r.append(p.info.name);
6696                }
6697            }
6698            if (r != null) {
6699                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
6700            }
6701
6702            N = pkg.services.size();
6703            r = null;
6704            for (i=0; i<N; i++) {
6705                PackageParser.Service s = pkg.services.get(i);
6706                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
6707                        s.info.processName, pkg.applicationInfo.uid);
6708                mServices.addService(s);
6709                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6710                    if (r == null) {
6711                        r = new StringBuilder(256);
6712                    } else {
6713                        r.append(' ');
6714                    }
6715                    r.append(s.info.name);
6716                }
6717            }
6718            if (r != null) {
6719                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
6720            }
6721
6722            N = pkg.receivers.size();
6723            r = null;
6724            for (i=0; i<N; i++) {
6725                PackageParser.Activity a = pkg.receivers.get(i);
6726                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6727                        a.info.processName, pkg.applicationInfo.uid);
6728                mReceivers.addActivity(a, "receiver");
6729                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6730                    if (r == null) {
6731                        r = new StringBuilder(256);
6732                    } else {
6733                        r.append(' ');
6734                    }
6735                    r.append(a.info.name);
6736                }
6737            }
6738            if (r != null) {
6739                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
6740            }
6741
6742            N = pkg.activities.size();
6743            r = null;
6744            for (i=0; i<N; i++) {
6745                PackageParser.Activity a = pkg.activities.get(i);
6746                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6747                        a.info.processName, pkg.applicationInfo.uid);
6748                mActivities.addActivity(a, "activity");
6749                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6750                    if (r == null) {
6751                        r = new StringBuilder(256);
6752                    } else {
6753                        r.append(' ');
6754                    }
6755                    r.append(a.info.name);
6756                }
6757            }
6758            if (r != null) {
6759                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
6760            }
6761
6762            N = pkg.permissionGroups.size();
6763            r = null;
6764            for (i=0; i<N; i++) {
6765                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
6766                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
6767                if (cur == null) {
6768                    mPermissionGroups.put(pg.info.name, pg);
6769                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6770                        if (r == null) {
6771                            r = new StringBuilder(256);
6772                        } else {
6773                            r.append(' ');
6774                        }
6775                        r.append(pg.info.name);
6776                    }
6777                } else {
6778                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
6779                            + pg.info.packageName + " ignored: original from "
6780                            + cur.info.packageName);
6781                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6782                        if (r == null) {
6783                            r = new StringBuilder(256);
6784                        } else {
6785                            r.append(' ');
6786                        }
6787                        r.append("DUP:");
6788                        r.append(pg.info.name);
6789                    }
6790                }
6791            }
6792            if (r != null) {
6793                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6794            }
6795
6796            N = pkg.permissions.size();
6797            r = null;
6798            for (i=0; i<N; i++) {
6799                PackageParser.Permission p = pkg.permissions.get(i);
6800
6801                // Now that permission groups have a special meaning, we ignore permission
6802                // groups for legacy apps to prevent unexpected behavior. In particular,
6803                // permissions for one app being granted to someone just becuase they happen
6804                // to be in a group defined by another app (before this had no implications).
6805                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
6806                    p.group = mPermissionGroups.get(p.info.group);
6807                    // Warn for a permission in an unknown group.
6808                    if (p.info.group != null && p.group == null) {
6809                        Slog.w(TAG, "Permission " + p.info.name + " from package "
6810                                + p.info.packageName + " in an unknown group " + p.info.group);
6811                    }
6812                }
6813
6814                ArrayMap<String, BasePermission> permissionMap =
6815                        p.tree ? mSettings.mPermissionTrees
6816                                : mSettings.mPermissions;
6817                BasePermission bp = permissionMap.get(p.info.name);
6818
6819                // Allow system apps to redefine non-system permissions
6820                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
6821                    final boolean currentOwnerIsSystem = (bp.perm != null
6822                            && isSystemApp(bp.perm.owner));
6823                    if (isSystemApp(p.owner)) {
6824                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
6825                            // It's a built-in permission and no owner, take ownership now
6826                            bp.packageSetting = pkgSetting;
6827                            bp.perm = p;
6828                            bp.uid = pkg.applicationInfo.uid;
6829                            bp.sourcePackage = p.info.packageName;
6830                        } else if (!currentOwnerIsSystem) {
6831                            String msg = "New decl " + p.owner + " of permission  "
6832                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
6833                            reportSettingsProblem(Log.WARN, msg);
6834                            bp = null;
6835                        }
6836                    }
6837                }
6838
6839                if (bp == null) {
6840                    bp = new BasePermission(p.info.name, p.info.packageName,
6841                            BasePermission.TYPE_NORMAL);
6842                    permissionMap.put(p.info.name, bp);
6843                }
6844
6845                if (bp.perm == null) {
6846                    if (bp.sourcePackage == null
6847                            || bp.sourcePackage.equals(p.info.packageName)) {
6848                        BasePermission tree = findPermissionTreeLP(p.info.name);
6849                        if (tree == null
6850                                || tree.sourcePackage.equals(p.info.packageName)) {
6851                            bp.packageSetting = pkgSetting;
6852                            bp.perm = p;
6853                            bp.uid = pkg.applicationInfo.uid;
6854                            bp.sourcePackage = p.info.packageName;
6855                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6856                                if (r == null) {
6857                                    r = new StringBuilder(256);
6858                                } else {
6859                                    r.append(' ');
6860                                }
6861                                r.append(p.info.name);
6862                            }
6863                        } else {
6864                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6865                                    + p.info.packageName + " ignored: base tree "
6866                                    + tree.name + " is from package "
6867                                    + tree.sourcePackage);
6868                        }
6869                    } else {
6870                        Slog.w(TAG, "Permission " + p.info.name + " from package "
6871                                + p.info.packageName + " ignored: original from "
6872                                + bp.sourcePackage);
6873                    }
6874                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6875                    if (r == null) {
6876                        r = new StringBuilder(256);
6877                    } else {
6878                        r.append(' ');
6879                    }
6880                    r.append("DUP:");
6881                    r.append(p.info.name);
6882                }
6883                if (bp.perm == p) {
6884                    bp.protectionLevel = p.info.protectionLevel;
6885                }
6886            }
6887
6888            if (r != null) {
6889                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6890            }
6891
6892            N = pkg.instrumentation.size();
6893            r = null;
6894            for (i=0; i<N; i++) {
6895                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6896                a.info.packageName = pkg.applicationInfo.packageName;
6897                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6898                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6899                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6900                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6901                a.info.dataDir = pkg.applicationInfo.dataDir;
6902
6903                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6904                // need other information about the application, like the ABI and what not ?
6905                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6906                mInstrumentation.put(a.getComponentName(), a);
6907                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6908                    if (r == null) {
6909                        r = new StringBuilder(256);
6910                    } else {
6911                        r.append(' ');
6912                    }
6913                    r.append(a.info.name);
6914                }
6915            }
6916            if (r != null) {
6917                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6918            }
6919
6920            if (pkg.protectedBroadcasts != null) {
6921                N = pkg.protectedBroadcasts.size();
6922                for (i=0; i<N; i++) {
6923                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6924                }
6925            }
6926
6927            pkgSetting.setTimeStamp(scanFileTime);
6928
6929            // Create idmap files for pairs of (packages, overlay packages).
6930            // Note: "android", ie framework-res.apk, is handled by native layers.
6931            if (pkg.mOverlayTarget != null) {
6932                // This is an overlay package.
6933                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6934                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6935                        mOverlays.put(pkg.mOverlayTarget,
6936                                new ArrayMap<String, PackageParser.Package>());
6937                    }
6938                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6939                    map.put(pkg.packageName, pkg);
6940                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6941                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6942                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6943                                "scanPackageLI failed to createIdmap");
6944                    }
6945                }
6946            } else if (mOverlays.containsKey(pkg.packageName) &&
6947                    !pkg.packageName.equals("android")) {
6948                // This is a regular package, with one or more known overlay packages.
6949                createIdmapsForPackageLI(pkg);
6950            }
6951        }
6952
6953        return pkg;
6954    }
6955
6956    /**
6957     * Derive the ABI of a non-system package located at {@code scanFile}. This information
6958     * is derived purely on the basis of the contents of {@code scanFile} and
6959     * {@code cpuAbiOverride}.
6960     *
6961     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
6962     */
6963    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
6964                                 String cpuAbiOverride, boolean extractLibs)
6965            throws PackageManagerException {
6966        // TODO: We can probably be smarter about this stuff. For installed apps,
6967        // we can calculate this information at install time once and for all. For
6968        // system apps, we can probably assume that this information doesn't change
6969        // after the first boot scan. As things stand, we do lots of unnecessary work.
6970
6971        // Give ourselves some initial paths; we'll come back for another
6972        // pass once we've determined ABI below.
6973        setNativeLibraryPaths(pkg);
6974
6975        // We would never need to extract libs for forward-locked and external packages,
6976        // since the container service will do it for us. We shouldn't attempt to
6977        // extract libs from system app when it was not updated.
6978        if (pkg.isForwardLocked() || isExternal(pkg) ||
6979            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
6980            extractLibs = false;
6981        }
6982
6983        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
6984        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
6985
6986        NativeLibraryHelper.Handle handle = null;
6987        try {
6988            handle = NativeLibraryHelper.Handle.create(scanFile);
6989            // TODO(multiArch): This can be null for apps that didn't go through the
6990            // usual installation process. We can calculate it again, like we
6991            // do during install time.
6992            //
6993            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
6994            // unnecessary.
6995            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
6996
6997            // Null out the abis so that they can be recalculated.
6998            pkg.applicationInfo.primaryCpuAbi = null;
6999            pkg.applicationInfo.secondaryCpuAbi = null;
7000            if (isMultiArch(pkg.applicationInfo)) {
7001                // Warn if we've set an abiOverride for multi-lib packages..
7002                // By definition, we need to copy both 32 and 64 bit libraries for
7003                // such packages.
7004                if (pkg.cpuAbiOverride != null
7005                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7006                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7007                }
7008
7009                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7010                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7011                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7012                    if (extractLibs) {
7013                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7014                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7015                                useIsaSpecificSubdirs);
7016                    } else {
7017                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7018                    }
7019                }
7020
7021                maybeThrowExceptionForMultiArchCopy(
7022                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7023
7024                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7025                    if (extractLibs) {
7026                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7027                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7028                                useIsaSpecificSubdirs);
7029                    } else {
7030                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7031                    }
7032                }
7033
7034                maybeThrowExceptionForMultiArchCopy(
7035                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7036
7037                if (abi64 >= 0) {
7038                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7039                }
7040
7041                if (abi32 >= 0) {
7042                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7043                    if (abi64 >= 0) {
7044                        pkg.applicationInfo.secondaryCpuAbi = abi;
7045                    } else {
7046                        pkg.applicationInfo.primaryCpuAbi = abi;
7047                    }
7048                }
7049            } else {
7050                String[] abiList = (cpuAbiOverride != null) ?
7051                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7052
7053                // Enable gross and lame hacks for apps that are built with old
7054                // SDK tools. We must scan their APKs for renderscript bitcode and
7055                // not launch them if it's present. Don't bother checking on devices
7056                // that don't have 64 bit support.
7057                boolean needsRenderScriptOverride = false;
7058                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7059                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7060                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7061                    needsRenderScriptOverride = true;
7062                }
7063
7064                final int copyRet;
7065                if (extractLibs) {
7066                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7067                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7068                } else {
7069                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7070                }
7071
7072                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7073                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7074                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7075                }
7076
7077                if (copyRet >= 0) {
7078                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7079                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7080                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7081                } else if (needsRenderScriptOverride) {
7082                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7083                }
7084            }
7085        } catch (IOException ioe) {
7086            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7087        } finally {
7088            IoUtils.closeQuietly(handle);
7089        }
7090
7091        // Now that we've calculated the ABIs and determined if it's an internal app,
7092        // we will go ahead and populate the nativeLibraryPath.
7093        setNativeLibraryPaths(pkg);
7094    }
7095
7096    /**
7097     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7098     * i.e, so that all packages can be run inside a single process if required.
7099     *
7100     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7101     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7102     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7103     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7104     * updating a package that belongs to a shared user.
7105     *
7106     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7107     * adds unnecessary complexity.
7108     */
7109    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7110            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7111        String requiredInstructionSet = null;
7112        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7113            requiredInstructionSet = VMRuntime.getInstructionSet(
7114                     scannedPackage.applicationInfo.primaryCpuAbi);
7115        }
7116
7117        PackageSetting requirer = null;
7118        for (PackageSetting ps : packagesForUser) {
7119            // If packagesForUser contains scannedPackage, we skip it. This will happen
7120            // when scannedPackage is an update of an existing package. Without this check,
7121            // we will never be able to change the ABI of any package belonging to a shared
7122            // user, even if it's compatible with other packages.
7123            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7124                if (ps.primaryCpuAbiString == null) {
7125                    continue;
7126                }
7127
7128                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7129                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7130                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7131                    // this but there's not much we can do.
7132                    String errorMessage = "Instruction set mismatch, "
7133                            + ((requirer == null) ? "[caller]" : requirer)
7134                            + " requires " + requiredInstructionSet + " whereas " + ps
7135                            + " requires " + instructionSet;
7136                    Slog.w(TAG, errorMessage);
7137                }
7138
7139                if (requiredInstructionSet == null) {
7140                    requiredInstructionSet = instructionSet;
7141                    requirer = ps;
7142                }
7143            }
7144        }
7145
7146        if (requiredInstructionSet != null) {
7147            String adjustedAbi;
7148            if (requirer != null) {
7149                // requirer != null implies that either scannedPackage was null or that scannedPackage
7150                // did not require an ABI, in which case we have to adjust scannedPackage to match
7151                // the ABI of the set (which is the same as requirer's ABI)
7152                adjustedAbi = requirer.primaryCpuAbiString;
7153                if (scannedPackage != null) {
7154                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7155                }
7156            } else {
7157                // requirer == null implies that we're updating all ABIs in the set to
7158                // match scannedPackage.
7159                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7160            }
7161
7162            for (PackageSetting ps : packagesForUser) {
7163                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7164                    if (ps.primaryCpuAbiString != null) {
7165                        continue;
7166                    }
7167
7168                    ps.primaryCpuAbiString = adjustedAbi;
7169                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7170                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7171                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7172
7173                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7174                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7175                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7176                            ps.primaryCpuAbiString = null;
7177                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7178                            return;
7179                        } else {
7180                            mInstaller.rmdex(ps.codePathString,
7181                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7182                        }
7183                    }
7184                }
7185            }
7186        }
7187    }
7188
7189    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7190        synchronized (mPackages) {
7191            mResolverReplaced = true;
7192            // Set up information for custom user intent resolution activity.
7193            mResolveActivity.applicationInfo = pkg.applicationInfo;
7194            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7195            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7196            mResolveActivity.processName = pkg.applicationInfo.packageName;
7197            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7198            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7199                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7200            mResolveActivity.theme = 0;
7201            mResolveActivity.exported = true;
7202            mResolveActivity.enabled = true;
7203            mResolveInfo.activityInfo = mResolveActivity;
7204            mResolveInfo.priority = 0;
7205            mResolveInfo.preferredOrder = 0;
7206            mResolveInfo.match = 0;
7207            mResolveComponentName = mCustomResolverComponentName;
7208            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7209                    mResolveComponentName);
7210        }
7211    }
7212
7213    private static String calculateBundledApkRoot(final String codePathString) {
7214        final File codePath = new File(codePathString);
7215        final File codeRoot;
7216        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7217            codeRoot = Environment.getRootDirectory();
7218        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7219            codeRoot = Environment.getOemDirectory();
7220        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7221            codeRoot = Environment.getVendorDirectory();
7222        } else {
7223            // Unrecognized code path; take its top real segment as the apk root:
7224            // e.g. /something/app/blah.apk => /something
7225            try {
7226                File f = codePath.getCanonicalFile();
7227                File parent = f.getParentFile();    // non-null because codePath is a file
7228                File tmp;
7229                while ((tmp = parent.getParentFile()) != null) {
7230                    f = parent;
7231                    parent = tmp;
7232                }
7233                codeRoot = f;
7234                Slog.w(TAG, "Unrecognized code path "
7235                        + codePath + " - using " + codeRoot);
7236            } catch (IOException e) {
7237                // Can't canonicalize the code path -- shenanigans?
7238                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7239                return Environment.getRootDirectory().getPath();
7240            }
7241        }
7242        return codeRoot.getPath();
7243    }
7244
7245    /**
7246     * Derive and set the location of native libraries for the given package,
7247     * which varies depending on where and how the package was installed.
7248     */
7249    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7250        final ApplicationInfo info = pkg.applicationInfo;
7251        final String codePath = pkg.codePath;
7252        final File codeFile = new File(codePath);
7253        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7254        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7255
7256        info.nativeLibraryRootDir = null;
7257        info.nativeLibraryRootRequiresIsa = false;
7258        info.nativeLibraryDir = null;
7259        info.secondaryNativeLibraryDir = null;
7260
7261        if (isApkFile(codeFile)) {
7262            // Monolithic install
7263            if (bundledApp) {
7264                // If "/system/lib64/apkname" exists, assume that is the per-package
7265                // native library directory to use; otherwise use "/system/lib/apkname".
7266                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7267                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7268                        getPrimaryInstructionSet(info));
7269
7270                // This is a bundled system app so choose the path based on the ABI.
7271                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7272                // is just the default path.
7273                final String apkName = deriveCodePathName(codePath);
7274                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7275                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7276                        apkName).getAbsolutePath();
7277
7278                if (info.secondaryCpuAbi != null) {
7279                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7280                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7281                            secondaryLibDir, apkName).getAbsolutePath();
7282                }
7283            } else if (asecApp) {
7284                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7285                        .getAbsolutePath();
7286            } else {
7287                final String apkName = deriveCodePathName(codePath);
7288                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7289                        .getAbsolutePath();
7290            }
7291
7292            info.nativeLibraryRootRequiresIsa = false;
7293            info.nativeLibraryDir = info.nativeLibraryRootDir;
7294        } else {
7295            // Cluster install
7296            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7297            info.nativeLibraryRootRequiresIsa = true;
7298
7299            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7300                    getPrimaryInstructionSet(info)).getAbsolutePath();
7301
7302            if (info.secondaryCpuAbi != null) {
7303                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7304                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7305            }
7306        }
7307    }
7308
7309    /**
7310     * Calculate the abis and roots for a bundled app. These can uniquely
7311     * be determined from the contents of the system partition, i.e whether
7312     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7313     * of this information, and instead assume that the system was built
7314     * sensibly.
7315     */
7316    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7317                                           PackageSetting pkgSetting) {
7318        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7319
7320        // If "/system/lib64/apkname" exists, assume that is the per-package
7321        // native library directory to use; otherwise use "/system/lib/apkname".
7322        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7323        setBundledAppAbi(pkg, apkRoot, apkName);
7324        // pkgSetting might be null during rescan following uninstall of updates
7325        // to a bundled app, so accommodate that possibility.  The settings in
7326        // that case will be established later from the parsed package.
7327        //
7328        // If the settings aren't null, sync them up with what we've just derived.
7329        // note that apkRoot isn't stored in the package settings.
7330        if (pkgSetting != null) {
7331            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7332            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7333        }
7334    }
7335
7336    /**
7337     * Deduces the ABI of a bundled app and sets the relevant fields on the
7338     * parsed pkg object.
7339     *
7340     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7341     *        under which system libraries are installed.
7342     * @param apkName the name of the installed package.
7343     */
7344    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7345        final File codeFile = new File(pkg.codePath);
7346
7347        final boolean has64BitLibs;
7348        final boolean has32BitLibs;
7349        if (isApkFile(codeFile)) {
7350            // Monolithic install
7351            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7352            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7353        } else {
7354            // Cluster install
7355            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7356            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7357                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7358                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7359                has64BitLibs = (new File(rootDir, isa)).exists();
7360            } else {
7361                has64BitLibs = false;
7362            }
7363            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7364                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7365                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7366                has32BitLibs = (new File(rootDir, isa)).exists();
7367            } else {
7368                has32BitLibs = false;
7369            }
7370        }
7371
7372        if (has64BitLibs && !has32BitLibs) {
7373            // The package has 64 bit libs, but not 32 bit libs. Its primary
7374            // ABI should be 64 bit. We can safely assume here that the bundled
7375            // native libraries correspond to the most preferred ABI in the list.
7376
7377            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7378            pkg.applicationInfo.secondaryCpuAbi = null;
7379        } else if (has32BitLibs && !has64BitLibs) {
7380            // The package has 32 bit libs but not 64 bit libs. Its primary
7381            // ABI should be 32 bit.
7382
7383            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7384            pkg.applicationInfo.secondaryCpuAbi = null;
7385        } else if (has32BitLibs && has64BitLibs) {
7386            // The application has both 64 and 32 bit bundled libraries. We check
7387            // here that the app declares multiArch support, and warn if it doesn't.
7388            //
7389            // We will be lenient here and record both ABIs. The primary will be the
7390            // ABI that's higher on the list, i.e, a device that's configured to prefer
7391            // 64 bit apps will see a 64 bit primary ABI,
7392
7393            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7394                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7395            }
7396
7397            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7398                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7399                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7400            } else {
7401                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7402                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7403            }
7404        } else {
7405            pkg.applicationInfo.primaryCpuAbi = null;
7406            pkg.applicationInfo.secondaryCpuAbi = null;
7407        }
7408    }
7409
7410    private void killApplication(String pkgName, int appId, String reason) {
7411        // Request the ActivityManager to kill the process(only for existing packages)
7412        // so that we do not end up in a confused state while the user is still using the older
7413        // version of the application while the new one gets installed.
7414        IActivityManager am = ActivityManagerNative.getDefault();
7415        if (am != null) {
7416            try {
7417                am.killApplicationWithAppId(pkgName, appId, reason);
7418            } catch (RemoteException e) {
7419            }
7420        }
7421    }
7422
7423    void removePackageLI(PackageSetting ps, boolean chatty) {
7424        if (DEBUG_INSTALL) {
7425            if (chatty)
7426                Log.d(TAG, "Removing package " + ps.name);
7427        }
7428
7429        // writer
7430        synchronized (mPackages) {
7431            mPackages.remove(ps.name);
7432            final PackageParser.Package pkg = ps.pkg;
7433            if (pkg != null) {
7434                cleanPackageDataStructuresLILPw(pkg, chatty);
7435            }
7436        }
7437    }
7438
7439    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7440        if (DEBUG_INSTALL) {
7441            if (chatty)
7442                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7443        }
7444
7445        // writer
7446        synchronized (mPackages) {
7447            mPackages.remove(pkg.applicationInfo.packageName);
7448            cleanPackageDataStructuresLILPw(pkg, chatty);
7449        }
7450    }
7451
7452    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7453        int N = pkg.providers.size();
7454        StringBuilder r = null;
7455        int i;
7456        for (i=0; i<N; i++) {
7457            PackageParser.Provider p = pkg.providers.get(i);
7458            mProviders.removeProvider(p);
7459            if (p.info.authority == null) {
7460
7461                /* There was another ContentProvider with this authority when
7462                 * this app was installed so this authority is null,
7463                 * Ignore it as we don't have to unregister the provider.
7464                 */
7465                continue;
7466            }
7467            String names[] = p.info.authority.split(";");
7468            for (int j = 0; j < names.length; j++) {
7469                if (mProvidersByAuthority.get(names[j]) == p) {
7470                    mProvidersByAuthority.remove(names[j]);
7471                    if (DEBUG_REMOVE) {
7472                        if (chatty)
7473                            Log.d(TAG, "Unregistered content provider: " + names[j]
7474                                    + ", className = " + p.info.name + ", isSyncable = "
7475                                    + p.info.isSyncable);
7476                    }
7477                }
7478            }
7479            if (DEBUG_REMOVE && chatty) {
7480                if (r == null) {
7481                    r = new StringBuilder(256);
7482                } else {
7483                    r.append(' ');
7484                }
7485                r.append(p.info.name);
7486            }
7487        }
7488        if (r != null) {
7489            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7490        }
7491
7492        N = pkg.services.size();
7493        r = null;
7494        for (i=0; i<N; i++) {
7495            PackageParser.Service s = pkg.services.get(i);
7496            mServices.removeService(s);
7497            if (chatty) {
7498                if (r == null) {
7499                    r = new StringBuilder(256);
7500                } else {
7501                    r.append(' ');
7502                }
7503                r.append(s.info.name);
7504            }
7505        }
7506        if (r != null) {
7507            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
7508        }
7509
7510        N = pkg.receivers.size();
7511        r = null;
7512        for (i=0; i<N; i++) {
7513            PackageParser.Activity a = pkg.receivers.get(i);
7514            mReceivers.removeActivity(a, "receiver");
7515            if (DEBUG_REMOVE && chatty) {
7516                if (r == null) {
7517                    r = new StringBuilder(256);
7518                } else {
7519                    r.append(' ');
7520                }
7521                r.append(a.info.name);
7522            }
7523        }
7524        if (r != null) {
7525            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
7526        }
7527
7528        N = pkg.activities.size();
7529        r = null;
7530        for (i=0; i<N; i++) {
7531            PackageParser.Activity a = pkg.activities.get(i);
7532            mActivities.removeActivity(a, "activity");
7533            if (DEBUG_REMOVE && chatty) {
7534                if (r == null) {
7535                    r = new StringBuilder(256);
7536                } else {
7537                    r.append(' ');
7538                }
7539                r.append(a.info.name);
7540            }
7541        }
7542        if (r != null) {
7543            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
7544        }
7545
7546        N = pkg.permissions.size();
7547        r = null;
7548        for (i=0; i<N; i++) {
7549            PackageParser.Permission p = pkg.permissions.get(i);
7550            BasePermission bp = mSettings.mPermissions.get(p.info.name);
7551            if (bp == null) {
7552                bp = mSettings.mPermissionTrees.get(p.info.name);
7553            }
7554            if (bp != null && bp.perm == p) {
7555                bp.perm = null;
7556                if (DEBUG_REMOVE && chatty) {
7557                    if (r == null) {
7558                        r = new StringBuilder(256);
7559                    } else {
7560                        r.append(' ');
7561                    }
7562                    r.append(p.info.name);
7563                }
7564            }
7565            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7566                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
7567                if (appOpPerms != null) {
7568                    appOpPerms.remove(pkg.packageName);
7569                }
7570            }
7571        }
7572        if (r != null) {
7573            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7574        }
7575
7576        N = pkg.requestedPermissions.size();
7577        r = null;
7578        for (i=0; i<N; i++) {
7579            String perm = pkg.requestedPermissions.get(i);
7580            BasePermission bp = mSettings.mPermissions.get(perm);
7581            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7582                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
7583                if (appOpPerms != null) {
7584                    appOpPerms.remove(pkg.packageName);
7585                    if (appOpPerms.isEmpty()) {
7586                        mAppOpPermissionPackages.remove(perm);
7587                    }
7588                }
7589            }
7590        }
7591        if (r != null) {
7592            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7593        }
7594
7595        N = pkg.instrumentation.size();
7596        r = null;
7597        for (i=0; i<N; i++) {
7598            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7599            mInstrumentation.remove(a.getComponentName());
7600            if (DEBUG_REMOVE && chatty) {
7601                if (r == null) {
7602                    r = new StringBuilder(256);
7603                } else {
7604                    r.append(' ');
7605                }
7606                r.append(a.info.name);
7607            }
7608        }
7609        if (r != null) {
7610            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
7611        }
7612
7613        r = null;
7614        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7615            // Only system apps can hold shared libraries.
7616            if (pkg.libraryNames != null) {
7617                for (i=0; i<pkg.libraryNames.size(); i++) {
7618                    String name = pkg.libraryNames.get(i);
7619                    SharedLibraryEntry cur = mSharedLibraries.get(name);
7620                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
7621                        mSharedLibraries.remove(name);
7622                        if (DEBUG_REMOVE && chatty) {
7623                            if (r == null) {
7624                                r = new StringBuilder(256);
7625                            } else {
7626                                r.append(' ');
7627                            }
7628                            r.append(name);
7629                        }
7630                    }
7631                }
7632            }
7633        }
7634        if (r != null) {
7635            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
7636        }
7637    }
7638
7639    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
7640        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
7641            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
7642                return true;
7643            }
7644        }
7645        return false;
7646    }
7647
7648    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
7649    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
7650    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
7651
7652    private void updatePermissionsLPw(String changingPkg,
7653            PackageParser.Package pkgInfo, int flags) {
7654        // Make sure there are no dangling permission trees.
7655        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
7656        while (it.hasNext()) {
7657            final BasePermission bp = it.next();
7658            if (bp.packageSetting == null) {
7659                // We may not yet have parsed the package, so just see if
7660                // we still know about its settings.
7661                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7662            }
7663            if (bp.packageSetting == null) {
7664                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
7665                        + " from package " + bp.sourcePackage);
7666                it.remove();
7667            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7668                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7669                    Slog.i(TAG, "Removing old permission tree: " + bp.name
7670                            + " from package " + bp.sourcePackage);
7671                    flags |= UPDATE_PERMISSIONS_ALL;
7672                    it.remove();
7673                }
7674            }
7675        }
7676
7677        // Make sure all dynamic permissions have been assigned to a package,
7678        // and make sure there are no dangling permissions.
7679        it = mSettings.mPermissions.values().iterator();
7680        while (it.hasNext()) {
7681            final BasePermission bp = it.next();
7682            if (bp.type == BasePermission.TYPE_DYNAMIC) {
7683                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
7684                        + bp.name + " pkg=" + bp.sourcePackage
7685                        + " info=" + bp.pendingInfo);
7686                if (bp.packageSetting == null && bp.pendingInfo != null) {
7687                    final BasePermission tree = findPermissionTreeLP(bp.name);
7688                    if (tree != null && tree.perm != null) {
7689                        bp.packageSetting = tree.packageSetting;
7690                        bp.perm = new PackageParser.Permission(tree.perm.owner,
7691                                new PermissionInfo(bp.pendingInfo));
7692                        bp.perm.info.packageName = tree.perm.info.packageName;
7693                        bp.perm.info.name = bp.name;
7694                        bp.uid = tree.uid;
7695                    }
7696                }
7697            }
7698            if (bp.packageSetting == null) {
7699                // We may not yet have parsed the package, so just see if
7700                // we still know about its settings.
7701                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7702            }
7703            if (bp.packageSetting == null) {
7704                Slog.w(TAG, "Removing dangling permission: " + bp.name
7705                        + " from package " + bp.sourcePackage);
7706                it.remove();
7707            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7708                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7709                    Slog.i(TAG, "Removing old permission: " + bp.name
7710                            + " from package " + bp.sourcePackage);
7711                    flags |= UPDATE_PERMISSIONS_ALL;
7712                    it.remove();
7713                }
7714            }
7715        }
7716
7717        // Now update the permissions for all packages, in particular
7718        // replace the granted permissions of the system packages.
7719        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
7720            for (PackageParser.Package pkg : mPackages.values()) {
7721                if (pkg != pkgInfo) {
7722                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
7723                            changingPkg);
7724                }
7725            }
7726        }
7727
7728        if (pkgInfo != null) {
7729            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
7730        }
7731    }
7732
7733    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
7734            String packageOfInterest) {
7735        // IMPORTANT: There are two types of permissions: install and runtime.
7736        // Install time permissions are granted when the app is installed to
7737        // all device users and users added in the future. Runtime permissions
7738        // are granted at runtime explicitly to specific users. Normal and signature
7739        // protected permissions are install time permissions. Dangerous permissions
7740        // are install permissions if the app's target SDK is Lollipop MR1 or older,
7741        // otherwise they are runtime permissions. This function does not manage
7742        // runtime permissions except for the case an app targeting Lollipop MR1
7743        // being upgraded to target a newer SDK, in which case dangerous permissions
7744        // are transformed from install time to runtime ones.
7745
7746        final PackageSetting ps = (PackageSetting) pkg.mExtras;
7747        if (ps == null) {
7748            return;
7749        }
7750
7751        PermissionsState permissionsState = ps.getPermissionsState();
7752        PermissionsState origPermissions = permissionsState;
7753
7754        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
7755
7756        int[] upgradeUserIds = EMPTY_INT_ARRAY;
7757        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
7758
7759        boolean changedInstallPermission = false;
7760
7761        if (replace) {
7762            ps.installPermissionsFixed = false;
7763            if (!ps.isSharedUser()) {
7764                origPermissions = new PermissionsState(permissionsState);
7765                permissionsState.reset();
7766            }
7767        }
7768
7769        permissionsState.setGlobalGids(mGlobalGids);
7770
7771        final int N = pkg.requestedPermissions.size();
7772        for (int i=0; i<N; i++) {
7773            final String name = pkg.requestedPermissions.get(i);
7774            final BasePermission bp = mSettings.mPermissions.get(name);
7775
7776            if (DEBUG_INSTALL) {
7777                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
7778            }
7779
7780            if (bp == null || bp.packageSetting == null) {
7781                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7782                    Slog.w(TAG, "Unknown permission " + name
7783                            + " in package " + pkg.packageName);
7784                }
7785                continue;
7786            }
7787
7788            final String perm = bp.name;
7789            boolean allowedSig = false;
7790            int grant = GRANT_DENIED;
7791
7792            // Keep track of app op permissions.
7793            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7794                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
7795                if (pkgs == null) {
7796                    pkgs = new ArraySet<>();
7797                    mAppOpPermissionPackages.put(bp.name, pkgs);
7798                }
7799                pkgs.add(pkg.packageName);
7800            }
7801
7802            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
7803            switch (level) {
7804                case PermissionInfo.PROTECTION_NORMAL: {
7805                    // For all apps normal permissions are install time ones.
7806                    grant = GRANT_INSTALL;
7807                } break;
7808
7809                case PermissionInfo.PROTECTION_DANGEROUS: {
7810                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
7811                        // For legacy apps dangerous permissions are install time ones.
7812                        grant = GRANT_INSTALL_LEGACY;
7813                    } else if (ps.isSystem()) {
7814                        final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds();
7815                        if (origPermissions.hasInstallPermission(bp.name)) {
7816                            // If a system app had an install permission, then the app was
7817                            // upgraded and we grant the permissions as runtime to all users.
7818                            grant = GRANT_UPGRADE;
7819                            upgradeUserIds = currentUserIds;
7820                        } else if (!Arrays.equals(updatedUserIds, currentUserIds)) {
7821                            // If users changed since the last permissions update for a
7822                            // system app, we grant the permission as runtime to the new users.
7823                            grant = GRANT_UPGRADE;
7824                            upgradeUserIds = currentUserIds;
7825                            for (int userId : updatedUserIds) {
7826                                upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId);
7827                            }
7828                        } else {
7829                            // Otherwise, we grant the permission as runtime if the app
7830                            // already had it, i.e. we preserve runtime permissions.
7831                            grant = GRANT_RUNTIME;
7832                        }
7833                    } else if (origPermissions.hasInstallPermission(bp.name)) {
7834                        // For legacy apps that became modern, install becomes runtime.
7835                        grant = GRANT_UPGRADE;
7836                        upgradeUserIds = currentUserIds;
7837                    } else if (replace) {
7838                        // For upgraded modern apps keep runtime permissions unchanged.
7839                        grant = GRANT_RUNTIME;
7840                    }
7841                } break;
7842
7843                case PermissionInfo.PROTECTION_SIGNATURE: {
7844                    // For all apps signature permissions are install time ones.
7845                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
7846                    if (allowedSig) {
7847                        grant = GRANT_INSTALL;
7848                    }
7849                } break;
7850            }
7851
7852            if (DEBUG_INSTALL) {
7853                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
7854            }
7855
7856            if (grant != GRANT_DENIED) {
7857                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
7858                    // If this is an existing, non-system package, then
7859                    // we can't add any new permissions to it.
7860                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
7861                        // Except...  if this is a permission that was added
7862                        // to the platform (note: need to only do this when
7863                        // updating the platform).
7864                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
7865                            grant = GRANT_DENIED;
7866                        }
7867                    }
7868                }
7869
7870                switch (grant) {
7871                    case GRANT_INSTALL: {
7872                        // Revoke this as runtime permission to handle the case of
7873                        // a runtime permssion being downgraded to an install one.
7874                        for (int userId : UserManagerService.getInstance().getUserIds()) {
7875                            if (origPermissions.getRuntimePermissionState(
7876                                    bp.name, userId) != null) {
7877                                // Revoke the runtime permission and clear the flags.
7878                                origPermissions.revokeRuntimePermission(bp, userId);
7879                                origPermissions.updatePermissionFlags(bp, userId,
7880                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
7881                                // If we revoked a permission permission, we have to write.
7882                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7883                                        changedRuntimePermissionUserIds, userId);
7884                            }
7885                        }
7886                        // Grant an install permission.
7887                        if (permissionsState.grantInstallPermission(bp) !=
7888                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
7889                            changedInstallPermission = true;
7890                        }
7891                    } break;
7892
7893                    case GRANT_INSTALL_LEGACY: {
7894                        // Grant an install permission.
7895                        if (permissionsState.grantInstallPermission(bp) !=
7896                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
7897                            changedInstallPermission = true;
7898                        }
7899                    } break;
7900
7901                    case GRANT_RUNTIME: {
7902                        // Grant previously granted runtime permissions.
7903                        for (int userId : UserManagerService.getInstance().getUserIds()) {
7904                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
7905                                PermissionState permissionState = origPermissions
7906                                        .getRuntimePermissionState(bp.name, userId);
7907                                final int flags = permissionState.getFlags();
7908                                if (permissionsState.grantRuntimePermission(bp, userId) ==
7909                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7910                                    // If we cannot put the permission as it was, we have to write.
7911                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7912                                            changedRuntimePermissionUserIds, userId);
7913                                } else {
7914                                    // System components not only get the permissions but
7915                                    // they are also fixed, so nothing can change that.
7916                                    final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg)
7917                                            ? flags
7918                                            : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
7919                                    // Propagate the permission flags.
7920                                    permissionsState.updatePermissionFlags(bp, userId,
7921                                            newFlags, newFlags);
7922                                }
7923                            }
7924                        }
7925                    } break;
7926
7927                    case GRANT_UPGRADE: {
7928                        // Grant runtime permissions for a previously held install permission.
7929                        PermissionState permissionState = origPermissions
7930                                .getInstallPermissionState(bp.name);
7931                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
7932
7933                        origPermissions.revokeInstallPermission(bp);
7934                        // We will be transferring the permission flags, so clear them.
7935                        origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
7936                                PackageManager.MASK_PERMISSION_FLAGS, 0);
7937
7938                        // If the permission is not to be promoted to runtime we ignore it and
7939                        // also its other flags as they are not applicable to install permissions.
7940                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
7941                            for (int userId : upgradeUserIds) {
7942                                if (permissionsState.grantRuntimePermission(bp, userId) !=
7943                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7944                                    // System components not only get the permissions but
7945                                    // they are also fixed so nothing can change that.
7946                                    final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg)
7947                                            ? flags
7948                                            : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
7949                                    // Transfer the permission flags.
7950                                    permissionsState.updatePermissionFlags(bp, userId,
7951                                            newFlags, newFlags);
7952                                    // If we granted the permission, we have to write.
7953                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7954                                            changedRuntimePermissionUserIds, userId);
7955                                }
7956                            }
7957                        }
7958                    } break;
7959
7960                    default: {
7961                        if (packageOfInterest == null
7962                                || packageOfInterest.equals(pkg.packageName)) {
7963                            Slog.w(TAG, "Not granting permission " + perm
7964                                    + " to package " + pkg.packageName
7965                                    + " because it was previously installed without");
7966                        }
7967                    } break;
7968                }
7969            } else {
7970                if (permissionsState.revokeInstallPermission(bp) !=
7971                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7972                    // Also drop the permission flags.
7973                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
7974                            PackageManager.MASK_PERMISSION_FLAGS, 0);
7975                    changedInstallPermission = true;
7976                    Slog.i(TAG, "Un-granting permission " + perm
7977                            + " from package " + pkg.packageName
7978                            + " (protectionLevel=" + bp.protectionLevel
7979                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7980                            + ")");
7981                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
7982                    // Don't print warning for app op permissions, since it is fine for them
7983                    // not to be granted, there is a UI for the user to decide.
7984                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7985                        Slog.w(TAG, "Not granting permission " + perm
7986                                + " to package " + pkg.packageName
7987                                + " (protectionLevel=" + bp.protectionLevel
7988                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7989                                + ")");
7990                    }
7991                }
7992            }
7993        }
7994
7995        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
7996                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
7997            // This is the first that we have heard about this package, so the
7998            // permissions we have now selected are fixed until explicitly
7999            // changed.
8000            ps.installPermissionsFixed = true;
8001        }
8002
8003        ps.setPermissionsUpdatedForUserIds(currentUserIds);
8004
8005        // Persist the runtime permissions state for users with changes.
8006        for (int userId : changedRuntimePermissionUserIds) {
8007            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8008        }
8009    }
8010
8011    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8012        boolean allowed = false;
8013        final int NP = PackageParser.NEW_PERMISSIONS.length;
8014        for (int ip=0; ip<NP; ip++) {
8015            final PackageParser.NewPermissionInfo npi
8016                    = PackageParser.NEW_PERMISSIONS[ip];
8017            if (npi.name.equals(perm)
8018                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8019                allowed = true;
8020                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8021                        + pkg.packageName);
8022                break;
8023            }
8024        }
8025        return allowed;
8026    }
8027
8028    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8029            BasePermission bp, PermissionsState origPermissions) {
8030        boolean allowed;
8031        allowed = (compareSignatures(
8032                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8033                        == PackageManager.SIGNATURE_MATCH)
8034                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8035                        == PackageManager.SIGNATURE_MATCH);
8036        if (!allowed && (bp.protectionLevel
8037                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
8038            if (isSystemApp(pkg)) {
8039                // For updated system applications, a system permission
8040                // is granted only if it had been defined by the original application.
8041                if (pkg.isUpdatedSystemApp()) {
8042                    final PackageSetting sysPs = mSettings
8043                            .getDisabledSystemPkgLPr(pkg.packageName);
8044                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8045                        // If the original was granted this permission, we take
8046                        // that grant decision as read and propagate it to the
8047                        // update.
8048                        if (sysPs.isPrivileged()) {
8049                            allowed = true;
8050                        }
8051                    } else {
8052                        // The system apk may have been updated with an older
8053                        // version of the one on the data partition, but which
8054                        // granted a new system permission that it didn't have
8055                        // before.  In this case we do want to allow the app to
8056                        // now get the new permission if the ancestral apk is
8057                        // privileged to get it.
8058                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8059                            for (int j=0;
8060                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8061                                if (perm.equals(
8062                                        sysPs.pkg.requestedPermissions.get(j))) {
8063                                    allowed = true;
8064                                    break;
8065                                }
8066                            }
8067                        }
8068                    }
8069                } else {
8070                    allowed = isPrivilegedApp(pkg);
8071                }
8072            }
8073        }
8074        if (!allowed && (bp.protectionLevel
8075                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8076            // For development permissions, a development permission
8077            // is granted only if it was already granted.
8078            allowed = origPermissions.hasInstallPermission(perm);
8079        }
8080        return allowed;
8081    }
8082
8083    final class ActivityIntentResolver
8084            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8085        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8086                boolean defaultOnly, int userId) {
8087            if (!sUserManager.exists(userId)) return null;
8088            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8089            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8090        }
8091
8092        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8093                int userId) {
8094            if (!sUserManager.exists(userId)) return null;
8095            mFlags = flags;
8096            return super.queryIntent(intent, resolvedType,
8097                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8098        }
8099
8100        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8101                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8102            if (!sUserManager.exists(userId)) return null;
8103            if (packageActivities == null) {
8104                return null;
8105            }
8106            mFlags = flags;
8107            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8108            final int N = packageActivities.size();
8109            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8110                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8111
8112            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8113            for (int i = 0; i < N; ++i) {
8114                intentFilters = packageActivities.get(i).intents;
8115                if (intentFilters != null && intentFilters.size() > 0) {
8116                    PackageParser.ActivityIntentInfo[] array =
8117                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8118                    intentFilters.toArray(array);
8119                    listCut.add(array);
8120                }
8121            }
8122            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8123        }
8124
8125        public final void addActivity(PackageParser.Activity a, String type) {
8126            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8127            mActivities.put(a.getComponentName(), a);
8128            if (DEBUG_SHOW_INFO)
8129                Log.v(
8130                TAG, "  " + type + " " +
8131                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8132            if (DEBUG_SHOW_INFO)
8133                Log.v(TAG, "    Class=" + a.info.name);
8134            final int NI = a.intents.size();
8135            for (int j=0; j<NI; j++) {
8136                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8137                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8138                    intent.setPriority(0);
8139                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8140                            + a.className + " with priority > 0, forcing to 0");
8141                }
8142                if (DEBUG_SHOW_INFO) {
8143                    Log.v(TAG, "    IntentFilter:");
8144                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8145                }
8146                if (!intent.debugCheck()) {
8147                    Log.w(TAG, "==> For Activity " + a.info.name);
8148                }
8149                addFilter(intent);
8150            }
8151        }
8152
8153        public final void removeActivity(PackageParser.Activity a, String type) {
8154            mActivities.remove(a.getComponentName());
8155            if (DEBUG_SHOW_INFO) {
8156                Log.v(TAG, "  " + type + " "
8157                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8158                                : a.info.name) + ":");
8159                Log.v(TAG, "    Class=" + a.info.name);
8160            }
8161            final int NI = a.intents.size();
8162            for (int j=0; j<NI; j++) {
8163                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8164                if (DEBUG_SHOW_INFO) {
8165                    Log.v(TAG, "    IntentFilter:");
8166                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8167                }
8168                removeFilter(intent);
8169            }
8170        }
8171
8172        @Override
8173        protected boolean allowFilterResult(
8174                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8175            ActivityInfo filterAi = filter.activity.info;
8176            for (int i=dest.size()-1; i>=0; i--) {
8177                ActivityInfo destAi = dest.get(i).activityInfo;
8178                if (destAi.name == filterAi.name
8179                        && destAi.packageName == filterAi.packageName) {
8180                    return false;
8181                }
8182            }
8183            return true;
8184        }
8185
8186        @Override
8187        protected ActivityIntentInfo[] newArray(int size) {
8188            return new ActivityIntentInfo[size];
8189        }
8190
8191        @Override
8192        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8193            if (!sUserManager.exists(userId)) return true;
8194            PackageParser.Package p = filter.activity.owner;
8195            if (p != null) {
8196                PackageSetting ps = (PackageSetting)p.mExtras;
8197                if (ps != null) {
8198                    // System apps are never considered stopped for purposes of
8199                    // filtering, because there may be no way for the user to
8200                    // actually re-launch them.
8201                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8202                            && ps.getStopped(userId);
8203                }
8204            }
8205            return false;
8206        }
8207
8208        @Override
8209        protected boolean isPackageForFilter(String packageName,
8210                PackageParser.ActivityIntentInfo info) {
8211            return packageName.equals(info.activity.owner.packageName);
8212        }
8213
8214        @Override
8215        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8216                int match, int userId) {
8217            if (!sUserManager.exists(userId)) return null;
8218            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8219                return null;
8220            }
8221            final PackageParser.Activity activity = info.activity;
8222            if (mSafeMode && (activity.info.applicationInfo.flags
8223                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8224                return null;
8225            }
8226            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8227            if (ps == null) {
8228                return null;
8229            }
8230            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8231                    ps.readUserState(userId), userId);
8232            if (ai == null) {
8233                return null;
8234            }
8235            final ResolveInfo res = new ResolveInfo();
8236            res.activityInfo = ai;
8237            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8238                res.filter = info;
8239            }
8240            if (info != null) {
8241                res.handleAllWebDataURI = info.handleAllWebDataURI();
8242            }
8243            res.priority = info.getPriority();
8244            res.preferredOrder = activity.owner.mPreferredOrder;
8245            //System.out.println("Result: " + res.activityInfo.className +
8246            //                   " = " + res.priority);
8247            res.match = match;
8248            res.isDefault = info.hasDefault;
8249            res.labelRes = info.labelRes;
8250            res.nonLocalizedLabel = info.nonLocalizedLabel;
8251            if (userNeedsBadging(userId)) {
8252                res.noResourceId = true;
8253            } else {
8254                res.icon = info.icon;
8255            }
8256            res.system = res.activityInfo.applicationInfo.isSystemApp();
8257            return res;
8258        }
8259
8260        @Override
8261        protected void sortResults(List<ResolveInfo> results) {
8262            Collections.sort(results, mResolvePrioritySorter);
8263        }
8264
8265        @Override
8266        protected void dumpFilter(PrintWriter out, String prefix,
8267                PackageParser.ActivityIntentInfo filter) {
8268            out.print(prefix); out.print(
8269                    Integer.toHexString(System.identityHashCode(filter.activity)));
8270                    out.print(' ');
8271                    filter.activity.printComponentShortName(out);
8272                    out.print(" filter ");
8273                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8274        }
8275
8276        @Override
8277        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8278            return filter.activity;
8279        }
8280
8281        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8282            PackageParser.Activity activity = (PackageParser.Activity)label;
8283            out.print(prefix); out.print(
8284                    Integer.toHexString(System.identityHashCode(activity)));
8285                    out.print(' ');
8286                    activity.printComponentShortName(out);
8287            if (count > 1) {
8288                out.print(" ("); out.print(count); out.print(" filters)");
8289            }
8290            out.println();
8291        }
8292
8293//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8294//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8295//            final List<ResolveInfo> retList = Lists.newArrayList();
8296//            while (i.hasNext()) {
8297//                final ResolveInfo resolveInfo = i.next();
8298//                if (isEnabledLP(resolveInfo.activityInfo)) {
8299//                    retList.add(resolveInfo);
8300//                }
8301//            }
8302//            return retList;
8303//        }
8304
8305        // Keys are String (activity class name), values are Activity.
8306        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8307                = new ArrayMap<ComponentName, PackageParser.Activity>();
8308        private int mFlags;
8309    }
8310
8311    private final class ServiceIntentResolver
8312            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8313        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8314                boolean defaultOnly, int userId) {
8315            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8316            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8317        }
8318
8319        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8320                int userId) {
8321            if (!sUserManager.exists(userId)) return null;
8322            mFlags = flags;
8323            return super.queryIntent(intent, resolvedType,
8324                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8325        }
8326
8327        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8328                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8329            if (!sUserManager.exists(userId)) return null;
8330            if (packageServices == null) {
8331                return null;
8332            }
8333            mFlags = flags;
8334            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8335            final int N = packageServices.size();
8336            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8337                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8338
8339            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8340            for (int i = 0; i < N; ++i) {
8341                intentFilters = packageServices.get(i).intents;
8342                if (intentFilters != null && intentFilters.size() > 0) {
8343                    PackageParser.ServiceIntentInfo[] array =
8344                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8345                    intentFilters.toArray(array);
8346                    listCut.add(array);
8347                }
8348            }
8349            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8350        }
8351
8352        public final void addService(PackageParser.Service s) {
8353            mServices.put(s.getComponentName(), s);
8354            if (DEBUG_SHOW_INFO) {
8355                Log.v(TAG, "  "
8356                        + (s.info.nonLocalizedLabel != null
8357                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8358                Log.v(TAG, "    Class=" + s.info.name);
8359            }
8360            final int NI = s.intents.size();
8361            int j;
8362            for (j=0; j<NI; j++) {
8363                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8364                if (DEBUG_SHOW_INFO) {
8365                    Log.v(TAG, "    IntentFilter:");
8366                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8367                }
8368                if (!intent.debugCheck()) {
8369                    Log.w(TAG, "==> For Service " + s.info.name);
8370                }
8371                addFilter(intent);
8372            }
8373        }
8374
8375        public final void removeService(PackageParser.Service s) {
8376            mServices.remove(s.getComponentName());
8377            if (DEBUG_SHOW_INFO) {
8378                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8379                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8380                Log.v(TAG, "    Class=" + s.info.name);
8381            }
8382            final int NI = s.intents.size();
8383            int j;
8384            for (j=0; j<NI; j++) {
8385                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8386                if (DEBUG_SHOW_INFO) {
8387                    Log.v(TAG, "    IntentFilter:");
8388                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8389                }
8390                removeFilter(intent);
8391            }
8392        }
8393
8394        @Override
8395        protected boolean allowFilterResult(
8396                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8397            ServiceInfo filterSi = filter.service.info;
8398            for (int i=dest.size()-1; i>=0; i--) {
8399                ServiceInfo destAi = dest.get(i).serviceInfo;
8400                if (destAi.name == filterSi.name
8401                        && destAi.packageName == filterSi.packageName) {
8402                    return false;
8403                }
8404            }
8405            return true;
8406        }
8407
8408        @Override
8409        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8410            return new PackageParser.ServiceIntentInfo[size];
8411        }
8412
8413        @Override
8414        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8415            if (!sUserManager.exists(userId)) return true;
8416            PackageParser.Package p = filter.service.owner;
8417            if (p != null) {
8418                PackageSetting ps = (PackageSetting)p.mExtras;
8419                if (ps != null) {
8420                    // System apps are never considered stopped for purposes of
8421                    // filtering, because there may be no way for the user to
8422                    // actually re-launch them.
8423                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8424                            && ps.getStopped(userId);
8425                }
8426            }
8427            return false;
8428        }
8429
8430        @Override
8431        protected boolean isPackageForFilter(String packageName,
8432                PackageParser.ServiceIntentInfo info) {
8433            return packageName.equals(info.service.owner.packageName);
8434        }
8435
8436        @Override
8437        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8438                int match, int userId) {
8439            if (!sUserManager.exists(userId)) return null;
8440            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8441            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8442                return null;
8443            }
8444            final PackageParser.Service service = info.service;
8445            if (mSafeMode && (service.info.applicationInfo.flags
8446                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8447                return null;
8448            }
8449            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8450            if (ps == null) {
8451                return null;
8452            }
8453            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8454                    ps.readUserState(userId), userId);
8455            if (si == null) {
8456                return null;
8457            }
8458            final ResolveInfo res = new ResolveInfo();
8459            res.serviceInfo = si;
8460            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8461                res.filter = filter;
8462            }
8463            res.priority = info.getPriority();
8464            res.preferredOrder = service.owner.mPreferredOrder;
8465            res.match = match;
8466            res.isDefault = info.hasDefault;
8467            res.labelRes = info.labelRes;
8468            res.nonLocalizedLabel = info.nonLocalizedLabel;
8469            res.icon = info.icon;
8470            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8471            return res;
8472        }
8473
8474        @Override
8475        protected void sortResults(List<ResolveInfo> results) {
8476            Collections.sort(results, mResolvePrioritySorter);
8477        }
8478
8479        @Override
8480        protected void dumpFilter(PrintWriter out, String prefix,
8481                PackageParser.ServiceIntentInfo filter) {
8482            out.print(prefix); out.print(
8483                    Integer.toHexString(System.identityHashCode(filter.service)));
8484                    out.print(' ');
8485                    filter.service.printComponentShortName(out);
8486                    out.print(" filter ");
8487                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8488        }
8489
8490        @Override
8491        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8492            return filter.service;
8493        }
8494
8495        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8496            PackageParser.Service service = (PackageParser.Service)label;
8497            out.print(prefix); out.print(
8498                    Integer.toHexString(System.identityHashCode(service)));
8499                    out.print(' ');
8500                    service.printComponentShortName(out);
8501            if (count > 1) {
8502                out.print(" ("); out.print(count); out.print(" filters)");
8503            }
8504            out.println();
8505        }
8506
8507//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8508//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8509//            final List<ResolveInfo> retList = Lists.newArrayList();
8510//            while (i.hasNext()) {
8511//                final ResolveInfo resolveInfo = (ResolveInfo) i;
8512//                if (isEnabledLP(resolveInfo.serviceInfo)) {
8513//                    retList.add(resolveInfo);
8514//                }
8515//            }
8516//            return retList;
8517//        }
8518
8519        // Keys are String (activity class name), values are Activity.
8520        private final ArrayMap<ComponentName, PackageParser.Service> mServices
8521                = new ArrayMap<ComponentName, PackageParser.Service>();
8522        private int mFlags;
8523    };
8524
8525    private final class ProviderIntentResolver
8526            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
8527        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8528                boolean defaultOnly, int userId) {
8529            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8530            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8531        }
8532
8533        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8534                int userId) {
8535            if (!sUserManager.exists(userId))
8536                return null;
8537            mFlags = flags;
8538            return super.queryIntent(intent, resolvedType,
8539                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8540        }
8541
8542        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8543                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
8544            if (!sUserManager.exists(userId))
8545                return null;
8546            if (packageProviders == null) {
8547                return null;
8548            }
8549            mFlags = flags;
8550            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
8551            final int N = packageProviders.size();
8552            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
8553                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
8554
8555            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
8556            for (int i = 0; i < N; ++i) {
8557                intentFilters = packageProviders.get(i).intents;
8558                if (intentFilters != null && intentFilters.size() > 0) {
8559                    PackageParser.ProviderIntentInfo[] array =
8560                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
8561                    intentFilters.toArray(array);
8562                    listCut.add(array);
8563                }
8564            }
8565            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8566        }
8567
8568        public final void addProvider(PackageParser.Provider p) {
8569            if (mProviders.containsKey(p.getComponentName())) {
8570                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
8571                return;
8572            }
8573
8574            mProviders.put(p.getComponentName(), p);
8575            if (DEBUG_SHOW_INFO) {
8576                Log.v(TAG, "  "
8577                        + (p.info.nonLocalizedLabel != null
8578                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
8579                Log.v(TAG, "    Class=" + p.info.name);
8580            }
8581            final int NI = p.intents.size();
8582            int j;
8583            for (j = 0; j < NI; j++) {
8584                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8585                if (DEBUG_SHOW_INFO) {
8586                    Log.v(TAG, "    IntentFilter:");
8587                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8588                }
8589                if (!intent.debugCheck()) {
8590                    Log.w(TAG, "==> For Provider " + p.info.name);
8591                }
8592                addFilter(intent);
8593            }
8594        }
8595
8596        public final void removeProvider(PackageParser.Provider p) {
8597            mProviders.remove(p.getComponentName());
8598            if (DEBUG_SHOW_INFO) {
8599                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
8600                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
8601                Log.v(TAG, "    Class=" + p.info.name);
8602            }
8603            final int NI = p.intents.size();
8604            int j;
8605            for (j = 0; j < NI; j++) {
8606                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8607                if (DEBUG_SHOW_INFO) {
8608                    Log.v(TAG, "    IntentFilter:");
8609                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8610                }
8611                removeFilter(intent);
8612            }
8613        }
8614
8615        @Override
8616        protected boolean allowFilterResult(
8617                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
8618            ProviderInfo filterPi = filter.provider.info;
8619            for (int i = dest.size() - 1; i >= 0; i--) {
8620                ProviderInfo destPi = dest.get(i).providerInfo;
8621                if (destPi.name == filterPi.name
8622                        && destPi.packageName == filterPi.packageName) {
8623                    return false;
8624                }
8625            }
8626            return true;
8627        }
8628
8629        @Override
8630        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
8631            return new PackageParser.ProviderIntentInfo[size];
8632        }
8633
8634        @Override
8635        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
8636            if (!sUserManager.exists(userId))
8637                return true;
8638            PackageParser.Package p = filter.provider.owner;
8639            if (p != null) {
8640                PackageSetting ps = (PackageSetting) p.mExtras;
8641                if (ps != null) {
8642                    // System apps are never considered stopped for purposes of
8643                    // filtering, because there may be no way for the user to
8644                    // actually re-launch them.
8645                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8646                            && ps.getStopped(userId);
8647                }
8648            }
8649            return false;
8650        }
8651
8652        @Override
8653        protected boolean isPackageForFilter(String packageName,
8654                PackageParser.ProviderIntentInfo info) {
8655            return packageName.equals(info.provider.owner.packageName);
8656        }
8657
8658        @Override
8659        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
8660                int match, int userId) {
8661            if (!sUserManager.exists(userId))
8662                return null;
8663            final PackageParser.ProviderIntentInfo info = filter;
8664            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
8665                return null;
8666            }
8667            final PackageParser.Provider provider = info.provider;
8668            if (mSafeMode && (provider.info.applicationInfo.flags
8669                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
8670                return null;
8671            }
8672            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
8673            if (ps == null) {
8674                return null;
8675            }
8676            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
8677                    ps.readUserState(userId), userId);
8678            if (pi == null) {
8679                return null;
8680            }
8681            final ResolveInfo res = new ResolveInfo();
8682            res.providerInfo = pi;
8683            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
8684                res.filter = filter;
8685            }
8686            res.priority = info.getPriority();
8687            res.preferredOrder = provider.owner.mPreferredOrder;
8688            res.match = match;
8689            res.isDefault = info.hasDefault;
8690            res.labelRes = info.labelRes;
8691            res.nonLocalizedLabel = info.nonLocalizedLabel;
8692            res.icon = info.icon;
8693            res.system = res.providerInfo.applicationInfo.isSystemApp();
8694            return res;
8695        }
8696
8697        @Override
8698        protected void sortResults(List<ResolveInfo> results) {
8699            Collections.sort(results, mResolvePrioritySorter);
8700        }
8701
8702        @Override
8703        protected void dumpFilter(PrintWriter out, String prefix,
8704                PackageParser.ProviderIntentInfo filter) {
8705            out.print(prefix);
8706            out.print(
8707                    Integer.toHexString(System.identityHashCode(filter.provider)));
8708            out.print(' ');
8709            filter.provider.printComponentShortName(out);
8710            out.print(" filter ");
8711            out.println(Integer.toHexString(System.identityHashCode(filter)));
8712        }
8713
8714        @Override
8715        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
8716            return filter.provider;
8717        }
8718
8719        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8720            PackageParser.Provider provider = (PackageParser.Provider)label;
8721            out.print(prefix); out.print(
8722                    Integer.toHexString(System.identityHashCode(provider)));
8723                    out.print(' ');
8724                    provider.printComponentShortName(out);
8725            if (count > 1) {
8726                out.print(" ("); out.print(count); out.print(" filters)");
8727            }
8728            out.println();
8729        }
8730
8731        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
8732                = new ArrayMap<ComponentName, PackageParser.Provider>();
8733        private int mFlags;
8734    };
8735
8736    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
8737            new Comparator<ResolveInfo>() {
8738        public int compare(ResolveInfo r1, ResolveInfo r2) {
8739            int v1 = r1.priority;
8740            int v2 = r2.priority;
8741            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
8742            if (v1 != v2) {
8743                return (v1 > v2) ? -1 : 1;
8744            }
8745            v1 = r1.preferredOrder;
8746            v2 = r2.preferredOrder;
8747            if (v1 != v2) {
8748                return (v1 > v2) ? -1 : 1;
8749            }
8750            if (r1.isDefault != r2.isDefault) {
8751                return r1.isDefault ? -1 : 1;
8752            }
8753            v1 = r1.match;
8754            v2 = r2.match;
8755            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
8756            if (v1 != v2) {
8757                return (v1 > v2) ? -1 : 1;
8758            }
8759            if (r1.system != r2.system) {
8760                return r1.system ? -1 : 1;
8761            }
8762            return 0;
8763        }
8764    };
8765
8766    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
8767            new Comparator<ProviderInfo>() {
8768        public int compare(ProviderInfo p1, ProviderInfo p2) {
8769            final int v1 = p1.initOrder;
8770            final int v2 = p2.initOrder;
8771            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
8772        }
8773    };
8774
8775    final void sendPackageBroadcast(final String action, final String pkg,
8776            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
8777            final int[] userIds) {
8778        mHandler.post(new Runnable() {
8779            @Override
8780            public void run() {
8781                try {
8782                    final IActivityManager am = ActivityManagerNative.getDefault();
8783                    if (am == null) return;
8784                    final int[] resolvedUserIds;
8785                    if (userIds == null) {
8786                        resolvedUserIds = am.getRunningUserIds();
8787                    } else {
8788                        resolvedUserIds = userIds;
8789                    }
8790                    for (int id : resolvedUserIds) {
8791                        final Intent intent = new Intent(action,
8792                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
8793                        if (extras != null) {
8794                            intent.putExtras(extras);
8795                        }
8796                        if (targetPkg != null) {
8797                            intent.setPackage(targetPkg);
8798                        }
8799                        // Modify the UID when posting to other users
8800                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
8801                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
8802                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
8803                            intent.putExtra(Intent.EXTRA_UID, uid);
8804                        }
8805                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
8806                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
8807                        if (DEBUG_BROADCASTS) {
8808                            RuntimeException here = new RuntimeException("here");
8809                            here.fillInStackTrace();
8810                            Slog.d(TAG, "Sending to user " + id + ": "
8811                                    + intent.toShortString(false, true, false, false)
8812                                    + " " + intent.getExtras(), here);
8813                        }
8814                        am.broadcastIntent(null, intent, null, finishedReceiver,
8815                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
8816                                null, finishedReceiver != null, false, id);
8817                    }
8818                } catch (RemoteException ex) {
8819                }
8820            }
8821        });
8822    }
8823
8824    /**
8825     * Check if the external storage media is available. This is true if there
8826     * is a mounted external storage medium or if the external storage is
8827     * emulated.
8828     */
8829    private boolean isExternalMediaAvailable() {
8830        return mMediaMounted || Environment.isExternalStorageEmulated();
8831    }
8832
8833    @Override
8834    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
8835        // writer
8836        synchronized (mPackages) {
8837            if (!isExternalMediaAvailable()) {
8838                // If the external storage is no longer mounted at this point,
8839                // the caller may not have been able to delete all of this
8840                // packages files and can not delete any more.  Bail.
8841                return null;
8842            }
8843            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
8844            if (lastPackage != null) {
8845                pkgs.remove(lastPackage);
8846            }
8847            if (pkgs.size() > 0) {
8848                return pkgs.get(0);
8849            }
8850        }
8851        return null;
8852    }
8853
8854    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
8855        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
8856                userId, andCode ? 1 : 0, packageName);
8857        if (mSystemReady) {
8858            msg.sendToTarget();
8859        } else {
8860            if (mPostSystemReadyMessages == null) {
8861                mPostSystemReadyMessages = new ArrayList<>();
8862            }
8863            mPostSystemReadyMessages.add(msg);
8864        }
8865    }
8866
8867    void startCleaningPackages() {
8868        // reader
8869        synchronized (mPackages) {
8870            if (!isExternalMediaAvailable()) {
8871                return;
8872            }
8873            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
8874                return;
8875            }
8876        }
8877        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
8878        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
8879        IActivityManager am = ActivityManagerNative.getDefault();
8880        if (am != null) {
8881            try {
8882                am.startService(null, intent, null, UserHandle.USER_OWNER);
8883            } catch (RemoteException e) {
8884            }
8885        }
8886    }
8887
8888    @Override
8889    public void installPackage(String originPath, IPackageInstallObserver2 observer,
8890            int installFlags, String installerPackageName, VerificationParams verificationParams,
8891            String packageAbiOverride) {
8892        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
8893                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
8894    }
8895
8896    @Override
8897    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
8898            int installFlags, String installerPackageName, VerificationParams verificationParams,
8899            String packageAbiOverride, int userId) {
8900        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
8901
8902        final int callingUid = Binder.getCallingUid();
8903        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
8904
8905        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8906            try {
8907                if (observer != null) {
8908                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
8909                }
8910            } catch (RemoteException re) {
8911            }
8912            return;
8913        }
8914
8915        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
8916            installFlags |= PackageManager.INSTALL_FROM_ADB;
8917
8918        } else {
8919            // Caller holds INSTALL_PACKAGES permission, so we're less strict
8920            // about installerPackageName.
8921
8922            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
8923            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
8924        }
8925
8926        UserHandle user;
8927        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
8928            user = UserHandle.ALL;
8929        } else {
8930            user = new UserHandle(userId);
8931        }
8932
8933        // Only system components can circumvent runtime permissions when installing.
8934        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
8935                && mContext.checkCallingOrSelfPermission(Manifest.permission
8936                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
8937            throw new SecurityException("You need the "
8938                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
8939                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
8940        }
8941
8942        verificationParams.setInstallerUid(callingUid);
8943
8944        final File originFile = new File(originPath);
8945        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
8946
8947        final Message msg = mHandler.obtainMessage(INIT_COPY);
8948        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
8949                null, verificationParams, user, packageAbiOverride);
8950        mHandler.sendMessage(msg);
8951    }
8952
8953    void installStage(String packageName, File stagedDir, String stagedCid,
8954            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
8955            String installerPackageName, int installerUid, UserHandle user) {
8956        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
8957                params.referrerUri, installerUid, null);
8958
8959        final OriginInfo origin;
8960        if (stagedDir != null) {
8961            origin = OriginInfo.fromStagedFile(stagedDir);
8962        } else {
8963            origin = OriginInfo.fromStagedContainer(stagedCid);
8964        }
8965
8966        final Message msg = mHandler.obtainMessage(INIT_COPY);
8967        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
8968                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
8969        mHandler.sendMessage(msg);
8970    }
8971
8972    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
8973        Bundle extras = new Bundle(1);
8974        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
8975
8976        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
8977                packageName, extras, null, null, new int[] {userId});
8978        try {
8979            IActivityManager am = ActivityManagerNative.getDefault();
8980            final boolean isSystem =
8981                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
8982            if (isSystem && am.isUserRunning(userId, false)) {
8983                // The just-installed/enabled app is bundled on the system, so presumed
8984                // to be able to run automatically without needing an explicit launch.
8985                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
8986                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
8987                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
8988                        .setPackage(packageName);
8989                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
8990                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
8991            }
8992        } catch (RemoteException e) {
8993            // shouldn't happen
8994            Slog.w(TAG, "Unable to bootstrap installed package", e);
8995        }
8996    }
8997
8998    @Override
8999    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9000            int userId) {
9001        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9002        PackageSetting pkgSetting;
9003        final int uid = Binder.getCallingUid();
9004        enforceCrossUserPermission(uid, userId, true, true,
9005                "setApplicationHiddenSetting for user " + userId);
9006
9007        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9008            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9009            return false;
9010        }
9011
9012        long callingId = Binder.clearCallingIdentity();
9013        try {
9014            boolean sendAdded = false;
9015            boolean sendRemoved = false;
9016            // writer
9017            synchronized (mPackages) {
9018                pkgSetting = mSettings.mPackages.get(packageName);
9019                if (pkgSetting == null) {
9020                    return false;
9021                }
9022                if (pkgSetting.getHidden(userId) != hidden) {
9023                    pkgSetting.setHidden(hidden, userId);
9024                    mSettings.writePackageRestrictionsLPr(userId);
9025                    if (hidden) {
9026                        sendRemoved = true;
9027                    } else {
9028                        sendAdded = true;
9029                    }
9030                }
9031            }
9032            if (sendAdded) {
9033                sendPackageAddedForUser(packageName, pkgSetting, userId);
9034                return true;
9035            }
9036            if (sendRemoved) {
9037                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9038                        "hiding pkg");
9039                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9040            }
9041        } finally {
9042            Binder.restoreCallingIdentity(callingId);
9043        }
9044        return false;
9045    }
9046
9047    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9048            int userId) {
9049        final PackageRemovedInfo info = new PackageRemovedInfo();
9050        info.removedPackage = packageName;
9051        info.removedUsers = new int[] {userId};
9052        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9053        info.sendBroadcast(false, false, false);
9054    }
9055
9056    /**
9057     * Returns true if application is not found or there was an error. Otherwise it returns
9058     * the hidden state of the package for the given user.
9059     */
9060    @Override
9061    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9062        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9063        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9064                false, "getApplicationHidden for user " + userId);
9065        PackageSetting pkgSetting;
9066        long callingId = Binder.clearCallingIdentity();
9067        try {
9068            // writer
9069            synchronized (mPackages) {
9070                pkgSetting = mSettings.mPackages.get(packageName);
9071                if (pkgSetting == null) {
9072                    return true;
9073                }
9074                return pkgSetting.getHidden(userId);
9075            }
9076        } finally {
9077            Binder.restoreCallingIdentity(callingId);
9078        }
9079    }
9080
9081    /**
9082     * @hide
9083     */
9084    @Override
9085    public int installExistingPackageAsUser(String packageName, int userId) {
9086        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9087                null);
9088        PackageSetting pkgSetting;
9089        final int uid = Binder.getCallingUid();
9090        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9091                + userId);
9092        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9093            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9094        }
9095
9096        long callingId = Binder.clearCallingIdentity();
9097        try {
9098            boolean sendAdded = false;
9099
9100            // writer
9101            synchronized (mPackages) {
9102                pkgSetting = mSettings.mPackages.get(packageName);
9103                if (pkgSetting == null) {
9104                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9105                }
9106                if (!pkgSetting.getInstalled(userId)) {
9107                    pkgSetting.setInstalled(true, userId);
9108                    pkgSetting.setHidden(false, userId);
9109                    mSettings.writePackageRestrictionsLPr(userId);
9110                    sendAdded = true;
9111                }
9112            }
9113
9114            if (sendAdded) {
9115                sendPackageAddedForUser(packageName, pkgSetting, userId);
9116            }
9117        } finally {
9118            Binder.restoreCallingIdentity(callingId);
9119        }
9120
9121        return PackageManager.INSTALL_SUCCEEDED;
9122    }
9123
9124    boolean isUserRestricted(int userId, String restrictionKey) {
9125        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9126        if (restrictions.getBoolean(restrictionKey, false)) {
9127            Log.w(TAG, "User is restricted: " + restrictionKey);
9128            return true;
9129        }
9130        return false;
9131    }
9132
9133    @Override
9134    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9135        mContext.enforceCallingOrSelfPermission(
9136                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9137                "Only package verification agents can verify applications");
9138
9139        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9140        final PackageVerificationResponse response = new PackageVerificationResponse(
9141                verificationCode, Binder.getCallingUid());
9142        msg.arg1 = id;
9143        msg.obj = response;
9144        mHandler.sendMessage(msg);
9145    }
9146
9147    @Override
9148    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9149            long millisecondsToDelay) {
9150        mContext.enforceCallingOrSelfPermission(
9151                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9152                "Only package verification agents can extend verification timeouts");
9153
9154        final PackageVerificationState state = mPendingVerification.get(id);
9155        final PackageVerificationResponse response = new PackageVerificationResponse(
9156                verificationCodeAtTimeout, Binder.getCallingUid());
9157
9158        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9159            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9160        }
9161        if (millisecondsToDelay < 0) {
9162            millisecondsToDelay = 0;
9163        }
9164        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9165                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9166            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9167        }
9168
9169        if ((state != null) && !state.timeoutExtended()) {
9170            state.extendTimeout();
9171
9172            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9173            msg.arg1 = id;
9174            msg.obj = response;
9175            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9176        }
9177    }
9178
9179    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9180            int verificationCode, UserHandle user) {
9181        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9182        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9183        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9184        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9185        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9186
9187        mContext.sendBroadcastAsUser(intent, user,
9188                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9189    }
9190
9191    private ComponentName matchComponentForVerifier(String packageName,
9192            List<ResolveInfo> receivers) {
9193        ActivityInfo targetReceiver = null;
9194
9195        final int NR = receivers.size();
9196        for (int i = 0; i < NR; i++) {
9197            final ResolveInfo info = receivers.get(i);
9198            if (info.activityInfo == null) {
9199                continue;
9200            }
9201
9202            if (packageName.equals(info.activityInfo.packageName)) {
9203                targetReceiver = info.activityInfo;
9204                break;
9205            }
9206        }
9207
9208        if (targetReceiver == null) {
9209            return null;
9210        }
9211
9212        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9213    }
9214
9215    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9216            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9217        if (pkgInfo.verifiers.length == 0) {
9218            return null;
9219        }
9220
9221        final int N = pkgInfo.verifiers.length;
9222        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9223        for (int i = 0; i < N; i++) {
9224            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9225
9226            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9227                    receivers);
9228            if (comp == null) {
9229                continue;
9230            }
9231
9232            final int verifierUid = getUidForVerifier(verifierInfo);
9233            if (verifierUid == -1) {
9234                continue;
9235            }
9236
9237            if (DEBUG_VERIFY) {
9238                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9239                        + " with the correct signature");
9240            }
9241            sufficientVerifiers.add(comp);
9242            verificationState.addSufficientVerifier(verifierUid);
9243        }
9244
9245        return sufficientVerifiers;
9246    }
9247
9248    private int getUidForVerifier(VerifierInfo verifierInfo) {
9249        synchronized (mPackages) {
9250            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9251            if (pkg == null) {
9252                return -1;
9253            } else if (pkg.mSignatures.length != 1) {
9254                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9255                        + " has more than one signature; ignoring");
9256                return -1;
9257            }
9258
9259            /*
9260             * If the public key of the package's signature does not match
9261             * our expected public key, then this is a different package and
9262             * we should skip.
9263             */
9264
9265            final byte[] expectedPublicKey;
9266            try {
9267                final Signature verifierSig = pkg.mSignatures[0];
9268                final PublicKey publicKey = verifierSig.getPublicKey();
9269                expectedPublicKey = publicKey.getEncoded();
9270            } catch (CertificateException e) {
9271                return -1;
9272            }
9273
9274            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9275
9276            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9277                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9278                        + " does not have the expected public key; ignoring");
9279                return -1;
9280            }
9281
9282            return pkg.applicationInfo.uid;
9283        }
9284    }
9285
9286    @Override
9287    public void finishPackageInstall(int token) {
9288        enforceSystemOrRoot("Only the system is allowed to finish installs");
9289
9290        if (DEBUG_INSTALL) {
9291            Slog.v(TAG, "BM finishing package install for " + token);
9292        }
9293
9294        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9295        mHandler.sendMessage(msg);
9296    }
9297
9298    /**
9299     * Get the verification agent timeout.
9300     *
9301     * @return verification timeout in milliseconds
9302     */
9303    private long getVerificationTimeout() {
9304        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9305                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9306                DEFAULT_VERIFICATION_TIMEOUT);
9307    }
9308
9309    /**
9310     * Get the default verification agent response code.
9311     *
9312     * @return default verification response code
9313     */
9314    private int getDefaultVerificationResponse() {
9315        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9316                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9317                DEFAULT_VERIFICATION_RESPONSE);
9318    }
9319
9320    /**
9321     * Check whether or not package verification has been enabled.
9322     *
9323     * @return true if verification should be performed
9324     */
9325    private boolean isVerificationEnabled(int userId, int installFlags) {
9326        if (!DEFAULT_VERIFY_ENABLE) {
9327            return false;
9328        }
9329
9330        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9331
9332        // Check if installing from ADB
9333        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9334            // Do not run verification in a test harness environment
9335            if (ActivityManager.isRunningInTestHarness()) {
9336                return false;
9337            }
9338            if (ensureVerifyAppsEnabled) {
9339                return true;
9340            }
9341            // Check if the developer does not want package verification for ADB installs
9342            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9343                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9344                return false;
9345            }
9346        }
9347
9348        if (ensureVerifyAppsEnabled) {
9349            return true;
9350        }
9351
9352        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9353                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9354    }
9355
9356    @Override
9357    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9358            throws RemoteException {
9359        mContext.enforceCallingOrSelfPermission(
9360                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9361                "Only intentfilter verification agents can verify applications");
9362
9363        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9364        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9365                Binder.getCallingUid(), verificationCode, failedDomains);
9366        msg.arg1 = id;
9367        msg.obj = response;
9368        mHandler.sendMessage(msg);
9369    }
9370
9371    @Override
9372    public int getIntentVerificationStatus(String packageName, int userId) {
9373        synchronized (mPackages) {
9374            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9375        }
9376    }
9377
9378    @Override
9379    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9380        boolean result = false;
9381        synchronized (mPackages) {
9382            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9383        }
9384        if (result) {
9385            scheduleWritePackageRestrictionsLocked(userId);
9386        }
9387        return result;
9388    }
9389
9390    @Override
9391    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9392        synchronized (mPackages) {
9393            return mSettings.getIntentFilterVerificationsLPr(packageName);
9394        }
9395    }
9396
9397    @Override
9398    public List<IntentFilter> getAllIntentFilters(String packageName) {
9399        if (TextUtils.isEmpty(packageName)) {
9400            return Collections.<IntentFilter>emptyList();
9401        }
9402        synchronized (mPackages) {
9403            PackageParser.Package pkg = mPackages.get(packageName);
9404            if (pkg == null || pkg.activities == null) {
9405                return Collections.<IntentFilter>emptyList();
9406            }
9407            final int count = pkg.activities.size();
9408            ArrayList<IntentFilter> result = new ArrayList<>();
9409            for (int n=0; n<count; n++) {
9410                PackageParser.Activity activity = pkg.activities.get(n);
9411                if (activity.intents != null || activity.intents.size() > 0) {
9412                    result.addAll(activity.intents);
9413                }
9414            }
9415            return result;
9416        }
9417    }
9418
9419    @Override
9420    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9421        synchronized (mPackages) {
9422            boolean result = mSettings.setDefaultBrowserPackageNameLPr(packageName, userId);
9423            if (packageName != null) {
9424                result |= updateIntentVerificationStatus(packageName,
9425                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9426                        UserHandle.myUserId());
9427            }
9428            return result;
9429        }
9430    }
9431
9432    @Override
9433    public String getDefaultBrowserPackageName(int userId) {
9434        synchronized (mPackages) {
9435            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9436        }
9437    }
9438
9439    /**
9440     * Get the "allow unknown sources" setting.
9441     *
9442     * @return the current "allow unknown sources" setting
9443     */
9444    private int getUnknownSourcesSettings() {
9445        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9446                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9447                -1);
9448    }
9449
9450    @Override
9451    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9452        final int uid = Binder.getCallingUid();
9453        // writer
9454        synchronized (mPackages) {
9455            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9456            if (targetPackageSetting == null) {
9457                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9458            }
9459
9460            PackageSetting installerPackageSetting;
9461            if (installerPackageName != null) {
9462                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9463                if (installerPackageSetting == null) {
9464                    throw new IllegalArgumentException("Unknown installer package: "
9465                            + installerPackageName);
9466                }
9467            } else {
9468                installerPackageSetting = null;
9469            }
9470
9471            Signature[] callerSignature;
9472            Object obj = mSettings.getUserIdLPr(uid);
9473            if (obj != null) {
9474                if (obj instanceof SharedUserSetting) {
9475                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9476                } else if (obj instanceof PackageSetting) {
9477                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9478                } else {
9479                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9480                }
9481            } else {
9482                throw new SecurityException("Unknown calling uid " + uid);
9483            }
9484
9485            // Verify: can't set installerPackageName to a package that is
9486            // not signed with the same cert as the caller.
9487            if (installerPackageSetting != null) {
9488                if (compareSignatures(callerSignature,
9489                        installerPackageSetting.signatures.mSignatures)
9490                        != PackageManager.SIGNATURE_MATCH) {
9491                    throw new SecurityException(
9492                            "Caller does not have same cert as new installer package "
9493                            + installerPackageName);
9494                }
9495            }
9496
9497            // Verify: if target already has an installer package, it must
9498            // be signed with the same cert as the caller.
9499            if (targetPackageSetting.installerPackageName != null) {
9500                PackageSetting setting = mSettings.mPackages.get(
9501                        targetPackageSetting.installerPackageName);
9502                // If the currently set package isn't valid, then it's always
9503                // okay to change it.
9504                if (setting != null) {
9505                    if (compareSignatures(callerSignature,
9506                            setting.signatures.mSignatures)
9507                            != PackageManager.SIGNATURE_MATCH) {
9508                        throw new SecurityException(
9509                                "Caller does not have same cert as old installer package "
9510                                + targetPackageSetting.installerPackageName);
9511                    }
9512                }
9513            }
9514
9515            // Okay!
9516            targetPackageSetting.installerPackageName = installerPackageName;
9517            scheduleWriteSettingsLocked();
9518        }
9519    }
9520
9521    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
9522        // Queue up an async operation since the package installation may take a little while.
9523        mHandler.post(new Runnable() {
9524            public void run() {
9525                mHandler.removeCallbacks(this);
9526                 // Result object to be returned
9527                PackageInstalledInfo res = new PackageInstalledInfo();
9528                res.returnCode = currentStatus;
9529                res.uid = -1;
9530                res.pkg = null;
9531                res.removedInfo = new PackageRemovedInfo();
9532                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9533                    args.doPreInstall(res.returnCode);
9534                    synchronized (mInstallLock) {
9535                        installPackageLI(args, res);
9536                    }
9537                    args.doPostInstall(res.returnCode, res.uid);
9538                }
9539
9540                // A restore should be performed at this point if (a) the install
9541                // succeeded, (b) the operation is not an update, and (c) the new
9542                // package has not opted out of backup participation.
9543                final boolean update = res.removedInfo.removedPackage != null;
9544                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
9545                boolean doRestore = !update
9546                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
9547
9548                // Set up the post-install work request bookkeeping.  This will be used
9549                // and cleaned up by the post-install event handling regardless of whether
9550                // there's a restore pass performed.  Token values are >= 1.
9551                int token;
9552                if (mNextInstallToken < 0) mNextInstallToken = 1;
9553                token = mNextInstallToken++;
9554
9555                PostInstallData data = new PostInstallData(args, res);
9556                mRunningInstalls.put(token, data);
9557                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
9558
9559                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
9560                    // Pass responsibility to the Backup Manager.  It will perform a
9561                    // restore if appropriate, then pass responsibility back to the
9562                    // Package Manager to run the post-install observer callbacks
9563                    // and broadcasts.
9564                    IBackupManager bm = IBackupManager.Stub.asInterface(
9565                            ServiceManager.getService(Context.BACKUP_SERVICE));
9566                    if (bm != null) {
9567                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
9568                                + " to BM for possible restore");
9569                        try {
9570                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
9571                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
9572                            } else {
9573                                doRestore = false;
9574                            }
9575                        } catch (RemoteException e) {
9576                            // can't happen; the backup manager is local
9577                        } catch (Exception e) {
9578                            Slog.e(TAG, "Exception trying to enqueue restore", e);
9579                            doRestore = false;
9580                        }
9581                    } else {
9582                        Slog.e(TAG, "Backup Manager not found!");
9583                        doRestore = false;
9584                    }
9585                }
9586
9587                if (!doRestore) {
9588                    // No restore possible, or the Backup Manager was mysteriously not
9589                    // available -- just fire the post-install work request directly.
9590                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
9591                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9592                    mHandler.sendMessage(msg);
9593                }
9594            }
9595        });
9596    }
9597
9598    private abstract class HandlerParams {
9599        private static final int MAX_RETRIES = 4;
9600
9601        /**
9602         * Number of times startCopy() has been attempted and had a non-fatal
9603         * error.
9604         */
9605        private int mRetries = 0;
9606
9607        /** User handle for the user requesting the information or installation. */
9608        private final UserHandle mUser;
9609
9610        HandlerParams(UserHandle user) {
9611            mUser = user;
9612        }
9613
9614        UserHandle getUser() {
9615            return mUser;
9616        }
9617
9618        final boolean startCopy() {
9619            boolean res;
9620            try {
9621                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
9622
9623                if (++mRetries > MAX_RETRIES) {
9624                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
9625                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
9626                    handleServiceError();
9627                    return false;
9628                } else {
9629                    handleStartCopy();
9630                    res = true;
9631                }
9632            } catch (RemoteException e) {
9633                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
9634                mHandler.sendEmptyMessage(MCS_RECONNECT);
9635                res = false;
9636            }
9637            handleReturnCode();
9638            return res;
9639        }
9640
9641        final void serviceError() {
9642            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
9643            handleServiceError();
9644            handleReturnCode();
9645        }
9646
9647        abstract void handleStartCopy() throws RemoteException;
9648        abstract void handleServiceError();
9649        abstract void handleReturnCode();
9650    }
9651
9652    class MeasureParams extends HandlerParams {
9653        private final PackageStats mStats;
9654        private boolean mSuccess;
9655
9656        private final IPackageStatsObserver mObserver;
9657
9658        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
9659            super(new UserHandle(stats.userHandle));
9660            mObserver = observer;
9661            mStats = stats;
9662        }
9663
9664        @Override
9665        public String toString() {
9666            return "MeasureParams{"
9667                + Integer.toHexString(System.identityHashCode(this))
9668                + " " + mStats.packageName + "}";
9669        }
9670
9671        @Override
9672        void handleStartCopy() throws RemoteException {
9673            synchronized (mInstallLock) {
9674                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
9675            }
9676
9677            if (mSuccess) {
9678                final boolean mounted;
9679                if (Environment.isExternalStorageEmulated()) {
9680                    mounted = true;
9681                } else {
9682                    final String status = Environment.getExternalStorageState();
9683                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
9684                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
9685                }
9686
9687                if (mounted) {
9688                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
9689
9690                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
9691                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
9692
9693                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
9694                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
9695
9696                    // Always subtract cache size, since it's a subdirectory
9697                    mStats.externalDataSize -= mStats.externalCacheSize;
9698
9699                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
9700                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
9701
9702                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
9703                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
9704                }
9705            }
9706        }
9707
9708        @Override
9709        void handleReturnCode() {
9710            if (mObserver != null) {
9711                try {
9712                    mObserver.onGetStatsCompleted(mStats, mSuccess);
9713                } catch (RemoteException e) {
9714                    Slog.i(TAG, "Observer no longer exists.");
9715                }
9716            }
9717        }
9718
9719        @Override
9720        void handleServiceError() {
9721            Slog.e(TAG, "Could not measure application " + mStats.packageName
9722                            + " external storage");
9723        }
9724    }
9725
9726    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
9727            throws RemoteException {
9728        long result = 0;
9729        for (File path : paths) {
9730            result += mcs.calculateDirectorySize(path.getAbsolutePath());
9731        }
9732        return result;
9733    }
9734
9735    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
9736        for (File path : paths) {
9737            try {
9738                mcs.clearDirectory(path.getAbsolutePath());
9739            } catch (RemoteException e) {
9740            }
9741        }
9742    }
9743
9744    static class OriginInfo {
9745        /**
9746         * Location where install is coming from, before it has been
9747         * copied/renamed into place. This could be a single monolithic APK
9748         * file, or a cluster directory. This location may be untrusted.
9749         */
9750        final File file;
9751        final String cid;
9752
9753        /**
9754         * Flag indicating that {@link #file} or {@link #cid} has already been
9755         * staged, meaning downstream users don't need to defensively copy the
9756         * contents.
9757         */
9758        final boolean staged;
9759
9760        /**
9761         * Flag indicating that {@link #file} or {@link #cid} is an already
9762         * installed app that is being moved.
9763         */
9764        final boolean existing;
9765
9766        final String resolvedPath;
9767        final File resolvedFile;
9768
9769        static OriginInfo fromNothing() {
9770            return new OriginInfo(null, null, false, false);
9771        }
9772
9773        static OriginInfo fromUntrustedFile(File file) {
9774            return new OriginInfo(file, null, false, false);
9775        }
9776
9777        static OriginInfo fromExistingFile(File file) {
9778            return new OriginInfo(file, null, false, true);
9779        }
9780
9781        static OriginInfo fromStagedFile(File file) {
9782            return new OriginInfo(file, null, true, false);
9783        }
9784
9785        static OriginInfo fromStagedContainer(String cid) {
9786            return new OriginInfo(null, cid, true, false);
9787        }
9788
9789        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
9790            this.file = file;
9791            this.cid = cid;
9792            this.staged = staged;
9793            this.existing = existing;
9794
9795            if (cid != null) {
9796                resolvedPath = PackageHelper.getSdDir(cid);
9797                resolvedFile = new File(resolvedPath);
9798            } else if (file != null) {
9799                resolvedPath = file.getAbsolutePath();
9800                resolvedFile = file;
9801            } else {
9802                resolvedPath = null;
9803                resolvedFile = null;
9804            }
9805        }
9806    }
9807
9808    class MoveInfo {
9809        final int moveId;
9810        final String fromUuid;
9811        final String toUuid;
9812        final String packageName;
9813        final String dataAppName;
9814        final int appId;
9815        final String seinfo;
9816
9817        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
9818                String dataAppName, int appId, String seinfo) {
9819            this.moveId = moveId;
9820            this.fromUuid = fromUuid;
9821            this.toUuid = toUuid;
9822            this.packageName = packageName;
9823            this.dataAppName = dataAppName;
9824            this.appId = appId;
9825            this.seinfo = seinfo;
9826        }
9827    }
9828
9829    class InstallParams extends HandlerParams {
9830        final OriginInfo origin;
9831        final MoveInfo move;
9832        final IPackageInstallObserver2 observer;
9833        int installFlags;
9834        final String installerPackageName;
9835        final String volumeUuid;
9836        final VerificationParams verificationParams;
9837        private InstallArgs mArgs;
9838        private int mRet;
9839        final String packageAbiOverride;
9840
9841        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
9842                int installFlags, String installerPackageName, String volumeUuid,
9843                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
9844            super(user);
9845            this.origin = origin;
9846            this.move = move;
9847            this.observer = observer;
9848            this.installFlags = installFlags;
9849            this.installerPackageName = installerPackageName;
9850            this.volumeUuid = volumeUuid;
9851            this.verificationParams = verificationParams;
9852            this.packageAbiOverride = packageAbiOverride;
9853        }
9854
9855        @Override
9856        public String toString() {
9857            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
9858                    + " file=" + origin.file + " cid=" + origin.cid + "}";
9859        }
9860
9861        public ManifestDigest getManifestDigest() {
9862            if (verificationParams == null) {
9863                return null;
9864            }
9865            return verificationParams.getManifestDigest();
9866        }
9867
9868        private int installLocationPolicy(PackageInfoLite pkgLite) {
9869            String packageName = pkgLite.packageName;
9870            int installLocation = pkgLite.installLocation;
9871            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9872            // reader
9873            synchronized (mPackages) {
9874                PackageParser.Package pkg = mPackages.get(packageName);
9875                if (pkg != null) {
9876                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
9877                        // Check for downgrading.
9878                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
9879                            try {
9880                                checkDowngrade(pkg, pkgLite);
9881                            } catch (PackageManagerException e) {
9882                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
9883                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
9884                            }
9885                        }
9886                        // Check for updated system application.
9887                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9888                            if (onSd) {
9889                                Slog.w(TAG, "Cannot install update to system app on sdcard");
9890                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
9891                            }
9892                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9893                        } else {
9894                            if (onSd) {
9895                                // Install flag overrides everything.
9896                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9897                            }
9898                            // If current upgrade specifies particular preference
9899                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
9900                                // Application explicitly specified internal.
9901                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9902                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
9903                                // App explictly prefers external. Let policy decide
9904                            } else {
9905                                // Prefer previous location
9906                                if (isExternal(pkg)) {
9907                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9908                                }
9909                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9910                            }
9911                        }
9912                    } else {
9913                        // Invalid install. Return error code
9914                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
9915                    }
9916                }
9917            }
9918            // All the special cases have been taken care of.
9919            // Return result based on recommended install location.
9920            if (onSd) {
9921                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9922            }
9923            return pkgLite.recommendedInstallLocation;
9924        }
9925
9926        /*
9927         * Invoke remote method to get package information and install
9928         * location values. Override install location based on default
9929         * policy if needed and then create install arguments based
9930         * on the install location.
9931         */
9932        public void handleStartCopy() throws RemoteException {
9933            int ret = PackageManager.INSTALL_SUCCEEDED;
9934
9935            // If we're already staged, we've firmly committed to an install location
9936            if (origin.staged) {
9937                if (origin.file != null) {
9938                    installFlags |= PackageManager.INSTALL_INTERNAL;
9939                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
9940                } else if (origin.cid != null) {
9941                    installFlags |= PackageManager.INSTALL_EXTERNAL;
9942                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
9943                } else {
9944                    throw new IllegalStateException("Invalid stage location");
9945                }
9946            }
9947
9948            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9949            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
9950
9951            PackageInfoLite pkgLite = null;
9952
9953            if (onInt && onSd) {
9954                // Check if both bits are set.
9955                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
9956                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9957            } else {
9958                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
9959                        packageAbiOverride);
9960
9961                /*
9962                 * If we have too little free space, try to free cache
9963                 * before giving up.
9964                 */
9965                if (!origin.staged && pkgLite.recommendedInstallLocation
9966                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9967                    // TODO: focus freeing disk space on the target device
9968                    final StorageManager storage = StorageManager.from(mContext);
9969                    final long lowThreshold = storage.getStorageLowBytes(
9970                            Environment.getDataDirectory());
9971
9972                    final long sizeBytes = mContainerService.calculateInstalledSize(
9973                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
9974
9975                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
9976                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
9977                                installFlags, packageAbiOverride);
9978                    }
9979
9980                    /*
9981                     * The cache free must have deleted the file we
9982                     * downloaded to install.
9983                     *
9984                     * TODO: fix the "freeCache" call to not delete
9985                     *       the file we care about.
9986                     */
9987                    if (pkgLite.recommendedInstallLocation
9988                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9989                        pkgLite.recommendedInstallLocation
9990                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
9991                    }
9992                }
9993            }
9994
9995            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9996                int loc = pkgLite.recommendedInstallLocation;
9997                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
9998                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9999                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10000                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10001                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10002                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10003                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10004                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10005                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10006                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10007                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10008                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10009                } else {
10010                    // Override with defaults if needed.
10011                    loc = installLocationPolicy(pkgLite);
10012                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10013                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10014                    } else if (!onSd && !onInt) {
10015                        // Override install location with flags
10016                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10017                            // Set the flag to install on external media.
10018                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10019                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10020                        } else {
10021                            // Make sure the flag for installing on external
10022                            // media is unset
10023                            installFlags |= PackageManager.INSTALL_INTERNAL;
10024                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10025                        }
10026                    }
10027                }
10028            }
10029
10030            final InstallArgs args = createInstallArgs(this);
10031            mArgs = args;
10032
10033            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10034                 /*
10035                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10036                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10037                 */
10038                int userIdentifier = getUser().getIdentifier();
10039                if (userIdentifier == UserHandle.USER_ALL
10040                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10041                    userIdentifier = UserHandle.USER_OWNER;
10042                }
10043
10044                /*
10045                 * Determine if we have any installed package verifiers. If we
10046                 * do, then we'll defer to them to verify the packages.
10047                 */
10048                final int requiredUid = mRequiredVerifierPackage == null ? -1
10049                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10050                if (!origin.existing && requiredUid != -1
10051                        && isVerificationEnabled(userIdentifier, installFlags)) {
10052                    final Intent verification = new Intent(
10053                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10054                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10055                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10056                            PACKAGE_MIME_TYPE);
10057                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10058
10059                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10060                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10061                            0 /* TODO: Which userId? */);
10062
10063                    if (DEBUG_VERIFY) {
10064                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10065                                + verification.toString() + " with " + pkgLite.verifiers.length
10066                                + " optional verifiers");
10067                    }
10068
10069                    final int verificationId = mPendingVerificationToken++;
10070
10071                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10072
10073                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10074                            installerPackageName);
10075
10076                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10077                            installFlags);
10078
10079                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10080                            pkgLite.packageName);
10081
10082                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10083                            pkgLite.versionCode);
10084
10085                    if (verificationParams != null) {
10086                        if (verificationParams.getVerificationURI() != null) {
10087                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10088                                 verificationParams.getVerificationURI());
10089                        }
10090                        if (verificationParams.getOriginatingURI() != null) {
10091                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10092                                  verificationParams.getOriginatingURI());
10093                        }
10094                        if (verificationParams.getReferrer() != null) {
10095                            verification.putExtra(Intent.EXTRA_REFERRER,
10096                                  verificationParams.getReferrer());
10097                        }
10098                        if (verificationParams.getOriginatingUid() >= 0) {
10099                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10100                                  verificationParams.getOriginatingUid());
10101                        }
10102                        if (verificationParams.getInstallerUid() >= 0) {
10103                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10104                                  verificationParams.getInstallerUid());
10105                        }
10106                    }
10107
10108                    final PackageVerificationState verificationState = new PackageVerificationState(
10109                            requiredUid, args);
10110
10111                    mPendingVerification.append(verificationId, verificationState);
10112
10113                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10114                            receivers, verificationState);
10115
10116                    /*
10117                     * If any sufficient verifiers were listed in the package
10118                     * manifest, attempt to ask them.
10119                     */
10120                    if (sufficientVerifiers != null) {
10121                        final int N = sufficientVerifiers.size();
10122                        if (N == 0) {
10123                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10124                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10125                        } else {
10126                            for (int i = 0; i < N; i++) {
10127                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10128
10129                                final Intent sufficientIntent = new Intent(verification);
10130                                sufficientIntent.setComponent(verifierComponent);
10131
10132                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
10133                            }
10134                        }
10135                    }
10136
10137                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10138                            mRequiredVerifierPackage, receivers);
10139                    if (ret == PackageManager.INSTALL_SUCCEEDED
10140                            && mRequiredVerifierPackage != null) {
10141                        /*
10142                         * Send the intent to the required verification agent,
10143                         * but only start the verification timeout after the
10144                         * target BroadcastReceivers have run.
10145                         */
10146                        verification.setComponent(requiredVerifierComponent);
10147                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
10148                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10149                                new BroadcastReceiver() {
10150                                    @Override
10151                                    public void onReceive(Context context, Intent intent) {
10152                                        final Message msg = mHandler
10153                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10154                                        msg.arg1 = verificationId;
10155                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10156                                    }
10157                                }, null, 0, null, null);
10158
10159                        /*
10160                         * We don't want the copy to proceed until verification
10161                         * succeeds, so null out this field.
10162                         */
10163                        mArgs = null;
10164                    }
10165                } else {
10166                    /*
10167                     * No package verification is enabled, so immediately start
10168                     * the remote call to initiate copy using temporary file.
10169                     */
10170                    ret = args.copyApk(mContainerService, true);
10171                }
10172            }
10173
10174            mRet = ret;
10175        }
10176
10177        @Override
10178        void handleReturnCode() {
10179            // If mArgs is null, then MCS couldn't be reached. When it
10180            // reconnects, it will try again to install. At that point, this
10181            // will succeed.
10182            if (mArgs != null) {
10183                processPendingInstall(mArgs, mRet);
10184            }
10185        }
10186
10187        @Override
10188        void handleServiceError() {
10189            mArgs = createInstallArgs(this);
10190            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10191        }
10192
10193        public boolean isForwardLocked() {
10194            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10195        }
10196    }
10197
10198    /**
10199     * Used during creation of InstallArgs
10200     *
10201     * @param installFlags package installation flags
10202     * @return true if should be installed on external storage
10203     */
10204    private static boolean installOnExternalAsec(int installFlags) {
10205        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10206            return false;
10207        }
10208        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10209            return true;
10210        }
10211        return false;
10212    }
10213
10214    /**
10215     * Used during creation of InstallArgs
10216     *
10217     * @param installFlags package installation flags
10218     * @return true if should be installed as forward locked
10219     */
10220    private static boolean installForwardLocked(int installFlags) {
10221        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10222    }
10223
10224    private InstallArgs createInstallArgs(InstallParams params) {
10225        if (params.move != null) {
10226            return new MoveInstallArgs(params);
10227        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10228            return new AsecInstallArgs(params);
10229        } else {
10230            return new FileInstallArgs(params);
10231        }
10232    }
10233
10234    /**
10235     * Create args that describe an existing installed package. Typically used
10236     * when cleaning up old installs, or used as a move source.
10237     */
10238    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10239            String resourcePath, String[] instructionSets) {
10240        final boolean isInAsec;
10241        if (installOnExternalAsec(installFlags)) {
10242            /* Apps on SD card are always in ASEC containers. */
10243            isInAsec = true;
10244        } else if (installForwardLocked(installFlags)
10245                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10246            /*
10247             * Forward-locked apps are only in ASEC containers if they're the
10248             * new style
10249             */
10250            isInAsec = true;
10251        } else {
10252            isInAsec = false;
10253        }
10254
10255        if (isInAsec) {
10256            return new AsecInstallArgs(codePath, instructionSets,
10257                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10258        } else {
10259            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10260        }
10261    }
10262
10263    static abstract class InstallArgs {
10264        /** @see InstallParams#origin */
10265        final OriginInfo origin;
10266        /** @see InstallParams#move */
10267        final MoveInfo move;
10268
10269        final IPackageInstallObserver2 observer;
10270        // Always refers to PackageManager flags only
10271        final int installFlags;
10272        final String installerPackageName;
10273        final String volumeUuid;
10274        final ManifestDigest manifestDigest;
10275        final UserHandle user;
10276        final String abiOverride;
10277
10278        // The list of instruction sets supported by this app. This is currently
10279        // only used during the rmdex() phase to clean up resources. We can get rid of this
10280        // if we move dex files under the common app path.
10281        /* nullable */ String[] instructionSets;
10282
10283        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10284                int installFlags, String installerPackageName, String volumeUuid,
10285                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10286                String abiOverride) {
10287            this.origin = origin;
10288            this.move = move;
10289            this.installFlags = installFlags;
10290            this.observer = observer;
10291            this.installerPackageName = installerPackageName;
10292            this.volumeUuid = volumeUuid;
10293            this.manifestDigest = manifestDigest;
10294            this.user = user;
10295            this.instructionSets = instructionSets;
10296            this.abiOverride = abiOverride;
10297        }
10298
10299        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10300        abstract int doPreInstall(int status);
10301
10302        /**
10303         * Rename package into final resting place. All paths on the given
10304         * scanned package should be updated to reflect the rename.
10305         */
10306        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10307        abstract int doPostInstall(int status, int uid);
10308
10309        /** @see PackageSettingBase#codePathString */
10310        abstract String getCodePath();
10311        /** @see PackageSettingBase#resourcePathString */
10312        abstract String getResourcePath();
10313
10314        // Need installer lock especially for dex file removal.
10315        abstract void cleanUpResourcesLI();
10316        abstract boolean doPostDeleteLI(boolean delete);
10317
10318        /**
10319         * Called before the source arguments are copied. This is used mostly
10320         * for MoveParams when it needs to read the source file to put it in the
10321         * destination.
10322         */
10323        int doPreCopy() {
10324            return PackageManager.INSTALL_SUCCEEDED;
10325        }
10326
10327        /**
10328         * Called after the source arguments are copied. This is used mostly for
10329         * MoveParams when it needs to read the source file to put it in the
10330         * destination.
10331         *
10332         * @return
10333         */
10334        int doPostCopy(int uid) {
10335            return PackageManager.INSTALL_SUCCEEDED;
10336        }
10337
10338        protected boolean isFwdLocked() {
10339            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10340        }
10341
10342        protected boolean isExternalAsec() {
10343            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10344        }
10345
10346        UserHandle getUser() {
10347            return user;
10348        }
10349    }
10350
10351    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10352        if (!allCodePaths.isEmpty()) {
10353            if (instructionSets == null) {
10354                throw new IllegalStateException("instructionSet == null");
10355            }
10356            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10357            for (String codePath : allCodePaths) {
10358                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10359                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10360                    if (retCode < 0) {
10361                        Slog.w(TAG, "Couldn't remove dex file for package: "
10362                                + " at location " + codePath + ", retcode=" + retCode);
10363                        // we don't consider this to be a failure of the core package deletion
10364                    }
10365                }
10366            }
10367        }
10368    }
10369
10370    /**
10371     * Logic to handle installation of non-ASEC applications, including copying
10372     * and renaming logic.
10373     */
10374    class FileInstallArgs extends InstallArgs {
10375        private File codeFile;
10376        private File resourceFile;
10377
10378        // Example topology:
10379        // /data/app/com.example/base.apk
10380        // /data/app/com.example/split_foo.apk
10381        // /data/app/com.example/lib/arm/libfoo.so
10382        // /data/app/com.example/lib/arm64/libfoo.so
10383        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10384
10385        /** New install */
10386        FileInstallArgs(InstallParams params) {
10387            super(params.origin, params.move, params.observer, params.installFlags,
10388                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10389                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10390            if (isFwdLocked()) {
10391                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10392            }
10393        }
10394
10395        /** Existing install */
10396        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10397            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10398                    null);
10399            this.codeFile = (codePath != null) ? new File(codePath) : null;
10400            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10401        }
10402
10403        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10404            if (origin.staged) {
10405                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10406                codeFile = origin.file;
10407                resourceFile = origin.file;
10408                return PackageManager.INSTALL_SUCCEEDED;
10409            }
10410
10411            try {
10412                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10413                codeFile = tempDir;
10414                resourceFile = tempDir;
10415            } catch (IOException e) {
10416                Slog.w(TAG, "Failed to create copy file: " + e);
10417                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10418            }
10419
10420            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10421                @Override
10422                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10423                    if (!FileUtils.isValidExtFilename(name)) {
10424                        throw new IllegalArgumentException("Invalid filename: " + name);
10425                    }
10426                    try {
10427                        final File file = new File(codeFile, name);
10428                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10429                                O_RDWR | O_CREAT, 0644);
10430                        Os.chmod(file.getAbsolutePath(), 0644);
10431                        return new ParcelFileDescriptor(fd);
10432                    } catch (ErrnoException e) {
10433                        throw new RemoteException("Failed to open: " + e.getMessage());
10434                    }
10435                }
10436            };
10437
10438            int ret = PackageManager.INSTALL_SUCCEEDED;
10439            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10440            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10441                Slog.e(TAG, "Failed to copy package");
10442                return ret;
10443            }
10444
10445            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10446            NativeLibraryHelper.Handle handle = null;
10447            try {
10448                handle = NativeLibraryHelper.Handle.create(codeFile);
10449                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10450                        abiOverride);
10451            } catch (IOException e) {
10452                Slog.e(TAG, "Copying native libraries failed", e);
10453                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10454            } finally {
10455                IoUtils.closeQuietly(handle);
10456            }
10457
10458            return ret;
10459        }
10460
10461        int doPreInstall(int status) {
10462            if (status != PackageManager.INSTALL_SUCCEEDED) {
10463                cleanUp();
10464            }
10465            return status;
10466        }
10467
10468        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10469            if (status != PackageManager.INSTALL_SUCCEEDED) {
10470                cleanUp();
10471                return false;
10472            }
10473
10474            final File targetDir = codeFile.getParentFile();
10475            final File beforeCodeFile = codeFile;
10476            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10477
10478            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10479            try {
10480                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10481            } catch (ErrnoException e) {
10482                Slog.w(TAG, "Failed to rename", e);
10483                return false;
10484            }
10485
10486            if (!SELinux.restoreconRecursive(afterCodeFile)) {
10487                Slog.w(TAG, "Failed to restorecon");
10488                return false;
10489            }
10490
10491            // Reflect the rename internally
10492            codeFile = afterCodeFile;
10493            resourceFile = afterCodeFile;
10494
10495            // Reflect the rename in scanned details
10496            pkg.codePath = afterCodeFile.getAbsolutePath();
10497            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10498                    pkg.baseCodePath);
10499            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10500                    pkg.splitCodePaths);
10501
10502            // Reflect the rename in app info
10503            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10504            pkg.applicationInfo.setCodePath(pkg.codePath);
10505            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10506            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10507            pkg.applicationInfo.setResourcePath(pkg.codePath);
10508            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10509            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10510
10511            return true;
10512        }
10513
10514        int doPostInstall(int status, int uid) {
10515            if (status != PackageManager.INSTALL_SUCCEEDED) {
10516                cleanUp();
10517            }
10518            return status;
10519        }
10520
10521        @Override
10522        String getCodePath() {
10523            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10524        }
10525
10526        @Override
10527        String getResourcePath() {
10528            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10529        }
10530
10531        private boolean cleanUp() {
10532            if (codeFile == null || !codeFile.exists()) {
10533                return false;
10534            }
10535
10536            if (codeFile.isDirectory()) {
10537                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10538            } else {
10539                codeFile.delete();
10540            }
10541
10542            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10543                resourceFile.delete();
10544            }
10545
10546            return true;
10547        }
10548
10549        void cleanUpResourcesLI() {
10550            // Try enumerating all code paths before deleting
10551            List<String> allCodePaths = Collections.EMPTY_LIST;
10552            if (codeFile != null && codeFile.exists()) {
10553                try {
10554                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10555                    allCodePaths = pkg.getAllCodePaths();
10556                } catch (PackageParserException e) {
10557                    // Ignored; we tried our best
10558                }
10559            }
10560
10561            cleanUp();
10562            removeDexFiles(allCodePaths, instructionSets);
10563        }
10564
10565        boolean doPostDeleteLI(boolean delete) {
10566            // XXX err, shouldn't we respect the delete flag?
10567            cleanUpResourcesLI();
10568            return true;
10569        }
10570    }
10571
10572    private boolean isAsecExternal(String cid) {
10573        final String asecPath = PackageHelper.getSdFilesystem(cid);
10574        return !asecPath.startsWith(mAsecInternalPath);
10575    }
10576
10577    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
10578            PackageManagerException {
10579        if (copyRet < 0) {
10580            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
10581                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
10582                throw new PackageManagerException(copyRet, message);
10583            }
10584        }
10585    }
10586
10587    /**
10588     * Extract the MountService "container ID" from the full code path of an
10589     * .apk.
10590     */
10591    static String cidFromCodePath(String fullCodePath) {
10592        int eidx = fullCodePath.lastIndexOf("/");
10593        String subStr1 = fullCodePath.substring(0, eidx);
10594        int sidx = subStr1.lastIndexOf("/");
10595        return subStr1.substring(sidx+1, eidx);
10596    }
10597
10598    /**
10599     * Logic to handle installation of ASEC applications, including copying and
10600     * renaming logic.
10601     */
10602    class AsecInstallArgs extends InstallArgs {
10603        static final String RES_FILE_NAME = "pkg.apk";
10604        static final String PUBLIC_RES_FILE_NAME = "res.zip";
10605
10606        String cid;
10607        String packagePath;
10608        String resourcePath;
10609
10610        /** New install */
10611        AsecInstallArgs(InstallParams params) {
10612            super(params.origin, params.move, params.observer, params.installFlags,
10613                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10614                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10615        }
10616
10617        /** Existing install */
10618        AsecInstallArgs(String fullCodePath, String[] instructionSets,
10619                        boolean isExternal, boolean isForwardLocked) {
10620            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
10621                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10622                    instructionSets, null);
10623            // Hackily pretend we're still looking at a full code path
10624            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
10625                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
10626            }
10627
10628            // Extract cid from fullCodePath
10629            int eidx = fullCodePath.lastIndexOf("/");
10630            String subStr1 = fullCodePath.substring(0, eidx);
10631            int sidx = subStr1.lastIndexOf("/");
10632            cid = subStr1.substring(sidx+1, eidx);
10633            setMountPath(subStr1);
10634        }
10635
10636        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
10637            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
10638                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10639                    instructionSets, null);
10640            this.cid = cid;
10641            setMountPath(PackageHelper.getSdDir(cid));
10642        }
10643
10644        void createCopyFile() {
10645            cid = mInstallerService.allocateExternalStageCidLegacy();
10646        }
10647
10648        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10649            if (origin.staged) {
10650                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
10651                cid = origin.cid;
10652                setMountPath(PackageHelper.getSdDir(cid));
10653                return PackageManager.INSTALL_SUCCEEDED;
10654            }
10655
10656            if (temp) {
10657                createCopyFile();
10658            } else {
10659                /*
10660                 * Pre-emptively destroy the container since it's destroyed if
10661                 * copying fails due to it existing anyway.
10662                 */
10663                PackageHelper.destroySdDir(cid);
10664            }
10665
10666            final String newMountPath = imcs.copyPackageToContainer(
10667                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
10668                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
10669
10670            if (newMountPath != null) {
10671                setMountPath(newMountPath);
10672                return PackageManager.INSTALL_SUCCEEDED;
10673            } else {
10674                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10675            }
10676        }
10677
10678        @Override
10679        String getCodePath() {
10680            return packagePath;
10681        }
10682
10683        @Override
10684        String getResourcePath() {
10685            return resourcePath;
10686        }
10687
10688        int doPreInstall(int status) {
10689            if (status != PackageManager.INSTALL_SUCCEEDED) {
10690                // Destroy container
10691                PackageHelper.destroySdDir(cid);
10692            } else {
10693                boolean mounted = PackageHelper.isContainerMounted(cid);
10694                if (!mounted) {
10695                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
10696                            Process.SYSTEM_UID);
10697                    if (newMountPath != null) {
10698                        setMountPath(newMountPath);
10699                    } else {
10700                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10701                    }
10702                }
10703            }
10704            return status;
10705        }
10706
10707        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10708            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
10709            String newMountPath = null;
10710            if (PackageHelper.isContainerMounted(cid)) {
10711                // Unmount the container
10712                if (!PackageHelper.unMountSdDir(cid)) {
10713                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
10714                    return false;
10715                }
10716            }
10717            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10718                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
10719                        " which might be stale. Will try to clean up.");
10720                // Clean up the stale container and proceed to recreate.
10721                if (!PackageHelper.destroySdDir(newCacheId)) {
10722                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
10723                    return false;
10724                }
10725                // Successfully cleaned up stale container. Try to rename again.
10726                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10727                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
10728                            + " inspite of cleaning it up.");
10729                    return false;
10730                }
10731            }
10732            if (!PackageHelper.isContainerMounted(newCacheId)) {
10733                Slog.w(TAG, "Mounting container " + newCacheId);
10734                newMountPath = PackageHelper.mountSdDir(newCacheId,
10735                        getEncryptKey(), Process.SYSTEM_UID);
10736            } else {
10737                newMountPath = PackageHelper.getSdDir(newCacheId);
10738            }
10739            if (newMountPath == null) {
10740                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
10741                return false;
10742            }
10743            Log.i(TAG, "Succesfully renamed " + cid +
10744                    " to " + newCacheId +
10745                    " at new path: " + newMountPath);
10746            cid = newCacheId;
10747
10748            final File beforeCodeFile = new File(packagePath);
10749            setMountPath(newMountPath);
10750            final File afterCodeFile = new File(packagePath);
10751
10752            // Reflect the rename in scanned details
10753            pkg.codePath = afterCodeFile.getAbsolutePath();
10754            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10755                    pkg.baseCodePath);
10756            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10757                    pkg.splitCodePaths);
10758
10759            // Reflect the rename in app info
10760            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10761            pkg.applicationInfo.setCodePath(pkg.codePath);
10762            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10763            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10764            pkg.applicationInfo.setResourcePath(pkg.codePath);
10765            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10766            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10767
10768            return true;
10769        }
10770
10771        private void setMountPath(String mountPath) {
10772            final File mountFile = new File(mountPath);
10773
10774            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
10775            if (monolithicFile.exists()) {
10776                packagePath = monolithicFile.getAbsolutePath();
10777                if (isFwdLocked()) {
10778                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
10779                } else {
10780                    resourcePath = packagePath;
10781                }
10782            } else {
10783                packagePath = mountFile.getAbsolutePath();
10784                resourcePath = packagePath;
10785            }
10786        }
10787
10788        int doPostInstall(int status, int uid) {
10789            if (status != PackageManager.INSTALL_SUCCEEDED) {
10790                cleanUp();
10791            } else {
10792                final int groupOwner;
10793                final String protectedFile;
10794                if (isFwdLocked()) {
10795                    groupOwner = UserHandle.getSharedAppGid(uid);
10796                    protectedFile = RES_FILE_NAME;
10797                } else {
10798                    groupOwner = -1;
10799                    protectedFile = null;
10800                }
10801
10802                if (uid < Process.FIRST_APPLICATION_UID
10803                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
10804                    Slog.e(TAG, "Failed to finalize " + cid);
10805                    PackageHelper.destroySdDir(cid);
10806                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10807                }
10808
10809                boolean mounted = PackageHelper.isContainerMounted(cid);
10810                if (!mounted) {
10811                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
10812                }
10813            }
10814            return status;
10815        }
10816
10817        private void cleanUp() {
10818            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
10819
10820            // Destroy secure container
10821            PackageHelper.destroySdDir(cid);
10822        }
10823
10824        private List<String> getAllCodePaths() {
10825            final File codeFile = new File(getCodePath());
10826            if (codeFile != null && codeFile.exists()) {
10827                try {
10828                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10829                    return pkg.getAllCodePaths();
10830                } catch (PackageParserException e) {
10831                    // Ignored; we tried our best
10832                }
10833            }
10834            return Collections.EMPTY_LIST;
10835        }
10836
10837        void cleanUpResourcesLI() {
10838            // Enumerate all code paths before deleting
10839            cleanUpResourcesLI(getAllCodePaths());
10840        }
10841
10842        private void cleanUpResourcesLI(List<String> allCodePaths) {
10843            cleanUp();
10844            removeDexFiles(allCodePaths, instructionSets);
10845        }
10846
10847        String getPackageName() {
10848            return getAsecPackageName(cid);
10849        }
10850
10851        boolean doPostDeleteLI(boolean delete) {
10852            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
10853            final List<String> allCodePaths = getAllCodePaths();
10854            boolean mounted = PackageHelper.isContainerMounted(cid);
10855            if (mounted) {
10856                // Unmount first
10857                if (PackageHelper.unMountSdDir(cid)) {
10858                    mounted = false;
10859                }
10860            }
10861            if (!mounted && delete) {
10862                cleanUpResourcesLI(allCodePaths);
10863            }
10864            return !mounted;
10865        }
10866
10867        @Override
10868        int doPreCopy() {
10869            if (isFwdLocked()) {
10870                if (!PackageHelper.fixSdPermissions(cid,
10871                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
10872                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10873                }
10874            }
10875
10876            return PackageManager.INSTALL_SUCCEEDED;
10877        }
10878
10879        @Override
10880        int doPostCopy(int uid) {
10881            if (isFwdLocked()) {
10882                if (uid < Process.FIRST_APPLICATION_UID
10883                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
10884                                RES_FILE_NAME)) {
10885                    Slog.e(TAG, "Failed to finalize " + cid);
10886                    PackageHelper.destroySdDir(cid);
10887                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10888                }
10889            }
10890
10891            return PackageManager.INSTALL_SUCCEEDED;
10892        }
10893    }
10894
10895    /**
10896     * Logic to handle movement of existing installed applications.
10897     */
10898    class MoveInstallArgs extends InstallArgs {
10899        private File codeFile;
10900        private File resourceFile;
10901
10902        /** New install */
10903        MoveInstallArgs(InstallParams params) {
10904            super(params.origin, params.move, params.observer, params.installFlags,
10905                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10906                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10907        }
10908
10909        int copyApk(IMediaContainerService imcs, boolean temp) {
10910            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
10911                    + move.fromUuid + " to " + move.toUuid);
10912            synchronized (mInstaller) {
10913                if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
10914                        move.dataAppName, move.appId, move.seinfo) != 0) {
10915                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10916                }
10917            }
10918
10919            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
10920            resourceFile = codeFile;
10921            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
10922
10923            return PackageManager.INSTALL_SUCCEEDED;
10924        }
10925
10926        int doPreInstall(int status) {
10927            if (status != PackageManager.INSTALL_SUCCEEDED) {
10928                cleanUp();
10929            }
10930            return status;
10931        }
10932
10933        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10934            if (status != PackageManager.INSTALL_SUCCEEDED) {
10935                cleanUp();
10936                return false;
10937            }
10938
10939            // Reflect the move in app info
10940            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10941            pkg.applicationInfo.setCodePath(pkg.codePath);
10942            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10943            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10944            pkg.applicationInfo.setResourcePath(pkg.codePath);
10945            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10946            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10947
10948            return true;
10949        }
10950
10951        int doPostInstall(int status, int uid) {
10952            if (status != PackageManager.INSTALL_SUCCEEDED) {
10953                cleanUp();
10954            }
10955            return status;
10956        }
10957
10958        @Override
10959        String getCodePath() {
10960            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10961        }
10962
10963        @Override
10964        String getResourcePath() {
10965            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10966        }
10967
10968        private boolean cleanUp() {
10969            if (codeFile == null || !codeFile.exists()) {
10970                return false;
10971            }
10972
10973            if (codeFile.isDirectory()) {
10974                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10975            } else {
10976                codeFile.delete();
10977            }
10978
10979            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10980                resourceFile.delete();
10981            }
10982
10983            return true;
10984        }
10985
10986        void cleanUpResourcesLI() {
10987            cleanUp();
10988        }
10989
10990        boolean doPostDeleteLI(boolean delete) {
10991            // XXX err, shouldn't we respect the delete flag?
10992            cleanUpResourcesLI();
10993            return true;
10994        }
10995    }
10996
10997    static String getAsecPackageName(String packageCid) {
10998        int idx = packageCid.lastIndexOf("-");
10999        if (idx == -1) {
11000            return packageCid;
11001        }
11002        return packageCid.substring(0, idx);
11003    }
11004
11005    // Utility method used to create code paths based on package name and available index.
11006    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11007        String idxStr = "";
11008        int idx = 1;
11009        // Fall back to default value of idx=1 if prefix is not
11010        // part of oldCodePath
11011        if (oldCodePath != null) {
11012            String subStr = oldCodePath;
11013            // Drop the suffix right away
11014            if (suffix != null && subStr.endsWith(suffix)) {
11015                subStr = subStr.substring(0, subStr.length() - suffix.length());
11016            }
11017            // If oldCodePath already contains prefix find out the
11018            // ending index to either increment or decrement.
11019            int sidx = subStr.lastIndexOf(prefix);
11020            if (sidx != -1) {
11021                subStr = subStr.substring(sidx + prefix.length());
11022                if (subStr != null) {
11023                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11024                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11025                    }
11026                    try {
11027                        idx = Integer.parseInt(subStr);
11028                        if (idx <= 1) {
11029                            idx++;
11030                        } else {
11031                            idx--;
11032                        }
11033                    } catch(NumberFormatException e) {
11034                    }
11035                }
11036            }
11037        }
11038        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11039        return prefix + idxStr;
11040    }
11041
11042    private File getNextCodePath(File targetDir, String packageName) {
11043        int suffix = 1;
11044        File result;
11045        do {
11046            result = new File(targetDir, packageName + "-" + suffix);
11047            suffix++;
11048        } while (result.exists());
11049        return result;
11050    }
11051
11052    // Utility method that returns the relative package path with respect
11053    // to the installation directory. Like say for /data/data/com.test-1.apk
11054    // string com.test-1 is returned.
11055    static String deriveCodePathName(String codePath) {
11056        if (codePath == null) {
11057            return null;
11058        }
11059        final File codeFile = new File(codePath);
11060        final String name = codeFile.getName();
11061        if (codeFile.isDirectory()) {
11062            return name;
11063        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11064            final int lastDot = name.lastIndexOf('.');
11065            return name.substring(0, lastDot);
11066        } else {
11067            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11068            return null;
11069        }
11070    }
11071
11072    class PackageInstalledInfo {
11073        String name;
11074        int uid;
11075        // The set of users that originally had this package installed.
11076        int[] origUsers;
11077        // The set of users that now have this package installed.
11078        int[] newUsers;
11079        PackageParser.Package pkg;
11080        int returnCode;
11081        String returnMsg;
11082        PackageRemovedInfo removedInfo;
11083
11084        public void setError(int code, String msg) {
11085            returnCode = code;
11086            returnMsg = msg;
11087            Slog.w(TAG, msg);
11088        }
11089
11090        public void setError(String msg, PackageParserException e) {
11091            returnCode = e.error;
11092            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11093            Slog.w(TAG, msg, e);
11094        }
11095
11096        public void setError(String msg, PackageManagerException e) {
11097            returnCode = e.error;
11098            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11099            Slog.w(TAG, msg, e);
11100        }
11101
11102        // In some error cases we want to convey more info back to the observer
11103        String origPackage;
11104        String origPermission;
11105    }
11106
11107    /*
11108     * Install a non-existing package.
11109     */
11110    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11111            UserHandle user, String installerPackageName, String volumeUuid,
11112            PackageInstalledInfo res) {
11113        // Remember this for later, in case we need to rollback this install
11114        String pkgName = pkg.packageName;
11115
11116        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11117        final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName,
11118                UserHandle.USER_OWNER).exists();
11119        synchronized(mPackages) {
11120            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11121                // A package with the same name is already installed, though
11122                // it has been renamed to an older name.  The package we
11123                // are trying to install should be installed as an update to
11124                // the existing one, but that has not been requested, so bail.
11125                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11126                        + " without first uninstalling package running as "
11127                        + mSettings.mRenamedPackages.get(pkgName));
11128                return;
11129            }
11130            if (mPackages.containsKey(pkgName)) {
11131                // Don't allow installation over an existing package with the same name.
11132                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11133                        + " without first uninstalling.");
11134                return;
11135            }
11136        }
11137
11138        try {
11139            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11140                    System.currentTimeMillis(), user);
11141
11142            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11143            // delete the partially installed application. the data directory will have to be
11144            // restored if it was already existing
11145            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11146                // remove package from internal structures.  Note that we want deletePackageX to
11147                // delete the package data and cache directories that it created in
11148                // scanPackageLocked, unless those directories existed before we even tried to
11149                // install.
11150                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11151                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11152                                res.removedInfo, true);
11153            }
11154
11155        } catch (PackageManagerException e) {
11156            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11157        }
11158    }
11159
11160    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11161        // Can't rotate keys during boot or if sharedUser.
11162        if (oldPs == null || (scanFlags&SCAN_BOOTING) != 0 || oldPs.sharedUser != null
11163                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11164            return false;
11165        }
11166        // app is using upgradeKeySets; make sure all are valid
11167        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11168        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11169        for (int i = 0; i < upgradeKeySets.length; i++) {
11170            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11171                Slog.wtf(TAG, "Package "
11172                         + (oldPs.name != null ? oldPs.name : "<null>")
11173                         + " contains upgrade-key-set reference to unknown key-set: "
11174                         + upgradeKeySets[i]
11175                         + " reverting to signatures check.");
11176                return false;
11177            }
11178        }
11179        return true;
11180    }
11181
11182    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11183        // Upgrade keysets are being used.  Determine if new package has a superset of the
11184        // required keys.
11185        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11186        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11187        for (int i = 0; i < upgradeKeySets.length; i++) {
11188            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11189            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11190                return true;
11191            }
11192        }
11193        return false;
11194    }
11195
11196    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11197            UserHandle user, String installerPackageName, String volumeUuid,
11198            PackageInstalledInfo res) {
11199        final PackageParser.Package oldPackage;
11200        final String pkgName = pkg.packageName;
11201        final int[] allUsers;
11202        final boolean[] perUserInstalled;
11203        final boolean weFroze;
11204
11205        // First find the old package info and check signatures
11206        synchronized(mPackages) {
11207            oldPackage = mPackages.get(pkgName);
11208            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11209            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11210            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11211                if(!checkUpgradeKeySetLP(ps, pkg)) {
11212                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11213                            "New package not signed by keys specified by upgrade-keysets: "
11214                            + pkgName);
11215                    return;
11216                }
11217            } else {
11218                // default to original signature matching
11219                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11220                    != PackageManager.SIGNATURE_MATCH) {
11221                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11222                            "New package has a different signature: " + pkgName);
11223                    return;
11224                }
11225            }
11226
11227            // In case of rollback, remember per-user/profile install state
11228            allUsers = sUserManager.getUserIds();
11229            perUserInstalled = new boolean[allUsers.length];
11230            for (int i = 0; i < allUsers.length; i++) {
11231                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11232            }
11233
11234            // Mark the app as frozen to prevent launching during the upgrade
11235            // process, and then kill all running instances
11236            if (!ps.frozen) {
11237                ps.frozen = true;
11238                weFroze = true;
11239            } else {
11240                weFroze = false;
11241            }
11242        }
11243
11244        // Now that we're guarded by frozen state, kill app during upgrade
11245        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11246
11247        try {
11248            boolean sysPkg = (isSystemApp(oldPackage));
11249            if (sysPkg) {
11250                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11251                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11252            } else {
11253                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11254                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11255            }
11256        } finally {
11257            // Regardless of success or failure of upgrade steps above, always
11258            // unfreeze the package if we froze it
11259            if (weFroze) {
11260                unfreezePackage(pkgName);
11261            }
11262        }
11263    }
11264
11265    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11266            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11267            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11268            String volumeUuid, PackageInstalledInfo res) {
11269        String pkgName = deletedPackage.packageName;
11270        boolean deletedPkg = true;
11271        boolean updatedSettings = false;
11272
11273        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11274                + deletedPackage);
11275        long origUpdateTime;
11276        if (pkg.mExtras != null) {
11277            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11278        } else {
11279            origUpdateTime = 0;
11280        }
11281
11282        // First delete the existing package while retaining the data directory
11283        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11284                res.removedInfo, true)) {
11285            // If the existing package wasn't successfully deleted
11286            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11287            deletedPkg = false;
11288        } else {
11289            // Successfully deleted the old package; proceed with replace.
11290
11291            // If deleted package lived in a container, give users a chance to
11292            // relinquish resources before killing.
11293            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11294                if (DEBUG_INSTALL) {
11295                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11296                }
11297                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11298                final ArrayList<String> pkgList = new ArrayList<String>(1);
11299                pkgList.add(deletedPackage.applicationInfo.packageName);
11300                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11301            }
11302
11303            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11304            try {
11305                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11306                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11307                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11308                        perUserInstalled, res, user);
11309                updatedSettings = true;
11310            } catch (PackageManagerException e) {
11311                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11312            }
11313        }
11314
11315        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11316            // remove package from internal structures.  Note that we want deletePackageX to
11317            // delete the package data and cache directories that it created in
11318            // scanPackageLocked, unless those directories existed before we even tried to
11319            // install.
11320            if(updatedSettings) {
11321                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11322                deletePackageLI(
11323                        pkgName, null, true, allUsers, perUserInstalled,
11324                        PackageManager.DELETE_KEEP_DATA,
11325                                res.removedInfo, true);
11326            }
11327            // Since we failed to install the new package we need to restore the old
11328            // package that we deleted.
11329            if (deletedPkg) {
11330                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11331                File restoreFile = new File(deletedPackage.codePath);
11332                // Parse old package
11333                boolean oldExternal = isExternal(deletedPackage);
11334                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11335                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11336                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11337                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11338                try {
11339                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11340                } catch (PackageManagerException e) {
11341                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11342                            + e.getMessage());
11343                    return;
11344                }
11345                // Restore of old package succeeded. Update permissions.
11346                // writer
11347                synchronized (mPackages) {
11348                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11349                            UPDATE_PERMISSIONS_ALL);
11350                    // can downgrade to reader
11351                    mSettings.writeLPr();
11352                }
11353                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11354            }
11355        }
11356    }
11357
11358    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11359            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11360            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11361            String volumeUuid, PackageInstalledInfo res) {
11362        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11363                + ", old=" + deletedPackage);
11364        boolean disabledSystem = false;
11365        boolean updatedSettings = false;
11366        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11367        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11368                != 0) {
11369            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11370        }
11371        String packageName = deletedPackage.packageName;
11372        if (packageName == null) {
11373            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11374                    "Attempt to delete null packageName.");
11375            return;
11376        }
11377        PackageParser.Package oldPkg;
11378        PackageSetting oldPkgSetting;
11379        // reader
11380        synchronized (mPackages) {
11381            oldPkg = mPackages.get(packageName);
11382            oldPkgSetting = mSettings.mPackages.get(packageName);
11383            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11384                    (oldPkgSetting == null)) {
11385                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11386                        "Couldn't find package:" + packageName + " information");
11387                return;
11388            }
11389        }
11390
11391        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11392        res.removedInfo.removedPackage = packageName;
11393        // Remove existing system package
11394        removePackageLI(oldPkgSetting, true);
11395        // writer
11396        synchronized (mPackages) {
11397            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11398            if (!disabledSystem && deletedPackage != null) {
11399                // We didn't need to disable the .apk as a current system package,
11400                // which means we are replacing another update that is already
11401                // installed.  We need to make sure to delete the older one's .apk.
11402                res.removedInfo.args = createInstallArgsForExisting(0,
11403                        deletedPackage.applicationInfo.getCodePath(),
11404                        deletedPackage.applicationInfo.getResourcePath(),
11405                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11406            } else {
11407                res.removedInfo.args = null;
11408            }
11409        }
11410
11411        // Successfully disabled the old package. Now proceed with re-installation
11412        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11413
11414        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11415        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11416
11417        PackageParser.Package newPackage = null;
11418        try {
11419            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11420            if (newPackage.mExtras != null) {
11421                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11422                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11423                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11424
11425                // is the update attempting to change shared user? that isn't going to work...
11426                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11427                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11428                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11429                            + " to " + newPkgSetting.sharedUser);
11430                    updatedSettings = true;
11431                }
11432            }
11433
11434            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11435                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11436                        perUserInstalled, res, user);
11437                updatedSettings = true;
11438            }
11439
11440        } catch (PackageManagerException e) {
11441            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11442        }
11443
11444        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11445            // Re installation failed. Restore old information
11446            // Remove new pkg information
11447            if (newPackage != null) {
11448                removeInstalledPackageLI(newPackage, true);
11449            }
11450            // Add back the old system package
11451            try {
11452                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11453            } catch (PackageManagerException e) {
11454                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11455            }
11456            // Restore the old system information in Settings
11457            synchronized (mPackages) {
11458                if (disabledSystem) {
11459                    mSettings.enableSystemPackageLPw(packageName);
11460                }
11461                if (updatedSettings) {
11462                    mSettings.setInstallerPackageName(packageName,
11463                            oldPkgSetting.installerPackageName);
11464                }
11465                mSettings.writeLPr();
11466            }
11467        }
11468    }
11469
11470    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
11471            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
11472            UserHandle user) {
11473        String pkgName = newPackage.packageName;
11474        synchronized (mPackages) {
11475            //write settings. the installStatus will be incomplete at this stage.
11476            //note that the new package setting would have already been
11477            //added to mPackages. It hasn't been persisted yet.
11478            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11479            mSettings.writeLPr();
11480        }
11481
11482        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11483
11484        synchronized (mPackages) {
11485            updatePermissionsLPw(newPackage.packageName, newPackage,
11486                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11487                            ? UPDATE_PERMISSIONS_ALL : 0));
11488            // For system-bundled packages, we assume that installing an upgraded version
11489            // of the package implies that the user actually wants to run that new code,
11490            // so we enable the package.
11491            PackageSetting ps = mSettings.mPackages.get(pkgName);
11492            if (ps != null) {
11493                if (isSystemApp(newPackage)) {
11494                    // NB: implicit assumption that system package upgrades apply to all users
11495                    if (DEBUG_INSTALL) {
11496                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
11497                    }
11498                    if (res.origUsers != null) {
11499                        for (int userHandle : res.origUsers) {
11500                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
11501                                    userHandle, installerPackageName);
11502                        }
11503                    }
11504                    // Also convey the prior install/uninstall state
11505                    if (allUsers != null && perUserInstalled != null) {
11506                        for (int i = 0; i < allUsers.length; i++) {
11507                            if (DEBUG_INSTALL) {
11508                                Slog.d(TAG, "    user " + allUsers[i]
11509                                        + " => " + perUserInstalled[i]);
11510                            }
11511                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
11512                        }
11513                        // these install state changes will be persisted in the
11514                        // upcoming call to mSettings.writeLPr().
11515                    }
11516                }
11517                // It's implied that when a user requests installation, they want the app to be
11518                // installed and enabled.
11519                int userId = user.getIdentifier();
11520                if (userId != UserHandle.USER_ALL) {
11521                    ps.setInstalled(true, userId);
11522                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
11523                }
11524            }
11525            res.name = pkgName;
11526            res.uid = newPackage.applicationInfo.uid;
11527            res.pkg = newPackage;
11528            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
11529            mSettings.setInstallerPackageName(pkgName, installerPackageName);
11530            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11531            //to update install status
11532            mSettings.writeLPr();
11533        }
11534    }
11535
11536    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
11537        final int installFlags = args.installFlags;
11538        final String installerPackageName = args.installerPackageName;
11539        final String volumeUuid = args.volumeUuid;
11540        final File tmpPackageFile = new File(args.getCodePath());
11541        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
11542        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
11543                || (args.volumeUuid != null));
11544        boolean replace = false;
11545        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
11546        // Result object to be returned
11547        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11548
11549        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
11550        // Retrieve PackageSettings and parse package
11551        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
11552                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
11553                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11554        PackageParser pp = new PackageParser();
11555        pp.setSeparateProcesses(mSeparateProcesses);
11556        pp.setDisplayMetrics(mMetrics);
11557
11558        final PackageParser.Package pkg;
11559        try {
11560            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
11561        } catch (PackageParserException e) {
11562            res.setError("Failed parse during installPackageLI", e);
11563            return;
11564        }
11565
11566        // Mark that we have an install time CPU ABI override.
11567        pkg.cpuAbiOverride = args.abiOverride;
11568
11569        String pkgName = res.name = pkg.packageName;
11570        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
11571            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
11572                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
11573                return;
11574            }
11575        }
11576
11577        try {
11578            pp.collectCertificates(pkg, parseFlags);
11579            pp.collectManifestDigest(pkg);
11580        } catch (PackageParserException e) {
11581            res.setError("Failed collect during installPackageLI", e);
11582            return;
11583        }
11584
11585        /* If the installer passed in a manifest digest, compare it now. */
11586        if (args.manifestDigest != null) {
11587            if (DEBUG_INSTALL) {
11588                final String parsedManifest = pkg.manifestDigest == null ? "null"
11589                        : pkg.manifestDigest.toString();
11590                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
11591                        + parsedManifest);
11592            }
11593
11594            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
11595                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
11596                return;
11597            }
11598        } else if (DEBUG_INSTALL) {
11599            final String parsedManifest = pkg.manifestDigest == null
11600                    ? "null" : pkg.manifestDigest.toString();
11601            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
11602        }
11603
11604        // Get rid of all references to package scan path via parser.
11605        pp = null;
11606        String oldCodePath = null;
11607        boolean systemApp = false;
11608        synchronized (mPackages) {
11609            // Check if installing already existing package
11610            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11611                String oldName = mSettings.mRenamedPackages.get(pkgName);
11612                if (pkg.mOriginalPackages != null
11613                        && pkg.mOriginalPackages.contains(oldName)
11614                        && mPackages.containsKey(oldName)) {
11615                    // This package is derived from an original package,
11616                    // and this device has been updating from that original
11617                    // name.  We must continue using the original name, so
11618                    // rename the new package here.
11619                    pkg.setPackageName(oldName);
11620                    pkgName = pkg.packageName;
11621                    replace = true;
11622                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
11623                            + oldName + " pkgName=" + pkgName);
11624                } else if (mPackages.containsKey(pkgName)) {
11625                    // This package, under its official name, already exists
11626                    // on the device; we should replace it.
11627                    replace = true;
11628                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
11629                }
11630
11631                // Prevent apps opting out from runtime permissions
11632                if (replace) {
11633                    PackageParser.Package oldPackage = mPackages.get(pkgName);
11634                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
11635                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
11636                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
11637                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
11638                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
11639                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
11640                                        + " doesn't support runtime permissions but the old"
11641                                        + " target SDK " + oldTargetSdk + " does.");
11642                        return;
11643                    }
11644                }
11645            }
11646
11647            PackageSetting ps = mSettings.mPackages.get(pkgName);
11648            if (ps != null) {
11649                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
11650
11651                // Quick sanity check that we're signed correctly if updating;
11652                // we'll check this again later when scanning, but we want to
11653                // bail early here before tripping over redefined permissions.
11654                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11655                    if (!checkUpgradeKeySetLP(ps, pkg)) {
11656                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
11657                                + pkg.packageName + " upgrade keys do not match the "
11658                                + "previously installed version");
11659                        return;
11660                    }
11661                } else {
11662                    try {
11663                        verifySignaturesLP(ps, pkg);
11664                    } catch (PackageManagerException e) {
11665                        res.setError(e.error, e.getMessage());
11666                        return;
11667                    }
11668                }
11669
11670                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
11671                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
11672                    systemApp = (ps.pkg.applicationInfo.flags &
11673                            ApplicationInfo.FLAG_SYSTEM) != 0;
11674                }
11675                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11676            }
11677
11678            // Check whether the newly-scanned package wants to define an already-defined perm
11679            int N = pkg.permissions.size();
11680            for (int i = N-1; i >= 0; i--) {
11681                PackageParser.Permission perm = pkg.permissions.get(i);
11682                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
11683                if (bp != null) {
11684                    // If the defining package is signed with our cert, it's okay.  This
11685                    // also includes the "updating the same package" case, of course.
11686                    // "updating same package" could also involve key-rotation.
11687                    final boolean sigsOk;
11688                    if (bp.sourcePackage.equals(pkg.packageName)
11689                            && (bp.packageSetting instanceof PackageSetting)
11690                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
11691                                    scanFlags))) {
11692                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
11693                    } else {
11694                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
11695                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
11696                    }
11697                    if (!sigsOk) {
11698                        // If the owning package is the system itself, we log but allow
11699                        // install to proceed; we fail the install on all other permission
11700                        // redefinitions.
11701                        if (!bp.sourcePackage.equals("android")) {
11702                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
11703                                    + pkg.packageName + " attempting to redeclare permission "
11704                                    + perm.info.name + " already owned by " + bp.sourcePackage);
11705                            res.origPermission = perm.info.name;
11706                            res.origPackage = bp.sourcePackage;
11707                            return;
11708                        } else {
11709                            Slog.w(TAG, "Package " + pkg.packageName
11710                                    + " attempting to redeclare system permission "
11711                                    + perm.info.name + "; ignoring new declaration");
11712                            pkg.permissions.remove(i);
11713                        }
11714                    }
11715                }
11716            }
11717
11718        }
11719
11720        if (systemApp && onExternal) {
11721            // Disable updates to system apps on sdcard
11722            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11723                    "Cannot install updates to system apps on sdcard");
11724            return;
11725        }
11726
11727        if (args.move != null) {
11728            // We did an in-place move, so dex is ready to roll
11729            scanFlags |= SCAN_NO_DEX;
11730            scanFlags |= SCAN_MOVE;
11731        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
11732            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
11733            scanFlags |= SCAN_NO_DEX;
11734
11735            try {
11736                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
11737                        true /* extract libs */);
11738            } catch (PackageManagerException pme) {
11739                Slog.e(TAG, "Error deriving application ABI", pme);
11740                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
11741                return;
11742            }
11743
11744            // Run dexopt before old package gets removed, to minimize time when app is unavailable
11745            int result = mPackageDexOptimizer
11746                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
11747                            false /* defer */, false /* inclDependencies */);
11748            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
11749                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
11750                return;
11751            }
11752        }
11753
11754        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
11755            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
11756            return;
11757        }
11758
11759        startIntentFilterVerifications(args.user.getIdentifier(), pkg);
11760
11761        if (replace) {
11762            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
11763                    installerPackageName, volumeUuid, res);
11764        } else {
11765            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
11766                    args.user, installerPackageName, volumeUuid, res);
11767        }
11768        synchronized (mPackages) {
11769            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11770            if (ps != null) {
11771                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11772            }
11773        }
11774    }
11775
11776    private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) {
11777        if (mIntentFilterVerifierComponent == null) {
11778            Slog.w(TAG, "No IntentFilter verification will not be done as "
11779                    + "there is no IntentFilterVerifier available!");
11780            return;
11781        }
11782
11783        final int verifierUid = getPackageUid(
11784                mIntentFilterVerifierComponent.getPackageName(),
11785                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
11786
11787        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
11788        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
11789        msg.obj = pkg;
11790        msg.arg1 = userId;
11791        msg.arg2 = verifierUid;
11792
11793        mHandler.sendMessage(msg);
11794    }
11795
11796    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid,
11797            PackageParser.Package pkg) {
11798        int size = pkg.activities.size();
11799        if (size == 0) {
11800            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
11801                    "No activity, so no need to verify any IntentFilter!");
11802            return;
11803        }
11804
11805        final boolean hasDomainURLs = hasDomainURLs(pkg);
11806        if (!hasDomainURLs) {
11807            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
11808                    "No domain URLs, so no need to verify any IntentFilter!");
11809            return;
11810        }
11811
11812        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
11813                + " if any IntentFilter from the " + size
11814                + " Activities needs verification ...");
11815
11816        final int verificationId = mIntentFilterVerificationToken++;
11817        int count = 0;
11818        final String packageName = pkg.packageName;
11819        boolean needToVerify = false;
11820
11821        synchronized (mPackages) {
11822            // If any filters need to be verified, then all need to be.
11823            for (PackageParser.Activity a : pkg.activities) {
11824                for (ActivityIntentInfo filter : a.intents) {
11825                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
11826                        if (DEBUG_DOMAIN_VERIFICATION) {
11827                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
11828                        }
11829                        needToVerify = true;
11830                        break;
11831                    }
11832                }
11833            }
11834            if (needToVerify) {
11835                for (PackageParser.Activity a : pkg.activities) {
11836                    for (ActivityIntentInfo filter : a.intents) {
11837                        boolean needsFilterVerification = filter.hasWebDataURI();
11838                        if (needsFilterVerification && needsNetworkVerificationLPr(filter)) {
11839                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
11840                                    "Verification needed for IntentFilter:" + filter.toString());
11841                            mIntentFilterVerifier.addOneIntentFilterVerification(
11842                                    verifierUid, userId, verificationId, filter, packageName);
11843                            count++;
11844                        }
11845                    }
11846                }
11847            }
11848        }
11849
11850        if (count > 0) {
11851            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
11852                    + " IntentFilter verification" + (count > 1 ? "s" : "")
11853                    +  " for userId:" + userId);
11854            mIntentFilterVerifier.startVerifications(userId);
11855        } else {
11856            if (DEBUG_DOMAIN_VERIFICATION) {
11857                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
11858            }
11859        }
11860    }
11861
11862    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
11863        final ComponentName cn  = filter.activity.getComponentName();
11864        final String packageName = cn.getPackageName();
11865
11866        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
11867                packageName);
11868        if (ivi == null) {
11869            return true;
11870        }
11871        int status = ivi.getStatus();
11872        switch (status) {
11873            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
11874            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
11875                return true;
11876
11877            default:
11878                // Nothing to do
11879                return false;
11880        }
11881    }
11882
11883    private boolean isSystemComponentOrPersistentPrivApp(PackageParser.Package pkg) {
11884        return UserHandle.getAppId(pkg.applicationInfo.uid) < FIRST_APPLICATION_UID
11885                || ((pkg.applicationInfo.privateFlags
11886                        & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0
11887                && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0);
11888    }
11889
11890    private static boolean isMultiArch(PackageSetting ps) {
11891        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
11892    }
11893
11894    private static boolean isMultiArch(ApplicationInfo info) {
11895        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
11896    }
11897
11898    private static boolean isExternal(PackageParser.Package pkg) {
11899        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11900    }
11901
11902    private static boolean isExternal(PackageSetting ps) {
11903        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11904    }
11905
11906    private static boolean isExternal(ApplicationInfo info) {
11907        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11908    }
11909
11910    private static boolean isSystemApp(PackageParser.Package pkg) {
11911        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
11912    }
11913
11914    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
11915        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
11916    }
11917
11918    private static boolean hasDomainURLs(PackageParser.Package pkg) {
11919        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
11920    }
11921
11922    private static boolean isSystemApp(PackageSetting ps) {
11923        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
11924    }
11925
11926    private static boolean isUpdatedSystemApp(PackageSetting ps) {
11927        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
11928    }
11929
11930    private int packageFlagsToInstallFlags(PackageSetting ps) {
11931        int installFlags = 0;
11932        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
11933            // This existing package was an external ASEC install when we have
11934            // the external flag without a UUID
11935            installFlags |= PackageManager.INSTALL_EXTERNAL;
11936        }
11937        if (ps.isForwardLocked()) {
11938            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
11939        }
11940        return installFlags;
11941    }
11942
11943    private void deleteTempPackageFiles() {
11944        final FilenameFilter filter = new FilenameFilter() {
11945            public boolean accept(File dir, String name) {
11946                return name.startsWith("vmdl") && name.endsWith(".tmp");
11947            }
11948        };
11949        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
11950            file.delete();
11951        }
11952    }
11953
11954    @Override
11955    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
11956            int flags) {
11957        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
11958                flags);
11959    }
11960
11961    @Override
11962    public void deletePackage(final String packageName,
11963            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
11964        mContext.enforceCallingOrSelfPermission(
11965                android.Manifest.permission.DELETE_PACKAGES, null);
11966        final int uid = Binder.getCallingUid();
11967        if (UserHandle.getUserId(uid) != userId) {
11968            mContext.enforceCallingPermission(
11969                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
11970                    "deletePackage for user " + userId);
11971        }
11972        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
11973            try {
11974                observer.onPackageDeleted(packageName,
11975                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
11976            } catch (RemoteException re) {
11977            }
11978            return;
11979        }
11980
11981        boolean uninstallBlocked = false;
11982        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
11983            int[] users = sUserManager.getUserIds();
11984            for (int i = 0; i < users.length; ++i) {
11985                if (getBlockUninstallForUser(packageName, users[i])) {
11986                    uninstallBlocked = true;
11987                    break;
11988                }
11989            }
11990        } else {
11991            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
11992        }
11993        if (uninstallBlocked) {
11994            try {
11995                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
11996                        null);
11997            } catch (RemoteException re) {
11998            }
11999            return;
12000        }
12001
12002        if (DEBUG_REMOVE) {
12003            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12004        }
12005        // Queue up an async operation since the package deletion may take a little while.
12006        mHandler.post(new Runnable() {
12007            public void run() {
12008                mHandler.removeCallbacks(this);
12009                final int returnCode = deletePackageX(packageName, userId, flags);
12010                if (observer != null) {
12011                    try {
12012                        observer.onPackageDeleted(packageName, returnCode, null);
12013                    } catch (RemoteException e) {
12014                        Log.i(TAG, "Observer no longer exists.");
12015                    } //end catch
12016                } //end if
12017            } //end run
12018        });
12019    }
12020
12021    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12022        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12023                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12024        try {
12025            if (dpm != null) {
12026                if (dpm.isDeviceOwner(packageName)) {
12027                    return true;
12028                }
12029                int[] users;
12030                if (userId == UserHandle.USER_ALL) {
12031                    users = sUserManager.getUserIds();
12032                } else {
12033                    users = new int[]{userId};
12034                }
12035                for (int i = 0; i < users.length; ++i) {
12036                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12037                        return true;
12038                    }
12039                }
12040            }
12041        } catch (RemoteException e) {
12042        }
12043        return false;
12044    }
12045
12046    /**
12047     *  This method is an internal method that could be get invoked either
12048     *  to delete an installed package or to clean up a failed installation.
12049     *  After deleting an installed package, a broadcast is sent to notify any
12050     *  listeners that the package has been installed. For cleaning up a failed
12051     *  installation, the broadcast is not necessary since the package's
12052     *  installation wouldn't have sent the initial broadcast either
12053     *  The key steps in deleting a package are
12054     *  deleting the package information in internal structures like mPackages,
12055     *  deleting the packages base directories through installd
12056     *  updating mSettings to reflect current status
12057     *  persisting settings for later use
12058     *  sending a broadcast if necessary
12059     */
12060    private int deletePackageX(String packageName, int userId, int flags) {
12061        final PackageRemovedInfo info = new PackageRemovedInfo();
12062        final boolean res;
12063
12064        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12065                ? UserHandle.ALL : new UserHandle(userId);
12066
12067        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12068            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12069            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12070        }
12071
12072        boolean removedForAllUsers = false;
12073        boolean systemUpdate = false;
12074
12075        // for the uninstall-updates case and restricted profiles, remember the per-
12076        // userhandle installed state
12077        int[] allUsers;
12078        boolean[] perUserInstalled;
12079        synchronized (mPackages) {
12080            PackageSetting ps = mSettings.mPackages.get(packageName);
12081            allUsers = sUserManager.getUserIds();
12082            perUserInstalled = new boolean[allUsers.length];
12083            for (int i = 0; i < allUsers.length; i++) {
12084                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12085            }
12086        }
12087
12088        synchronized (mInstallLock) {
12089            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12090            res = deletePackageLI(packageName, removeForUser,
12091                    true, allUsers, perUserInstalled,
12092                    flags | REMOVE_CHATTY, info, true);
12093            systemUpdate = info.isRemovedPackageSystemUpdate;
12094            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12095                removedForAllUsers = true;
12096            }
12097            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12098                    + " removedForAllUsers=" + removedForAllUsers);
12099        }
12100
12101        if (res) {
12102            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12103
12104            // If the removed package was a system update, the old system package
12105            // was re-enabled; we need to broadcast this information
12106            if (systemUpdate) {
12107                Bundle extras = new Bundle(1);
12108                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12109                        ? info.removedAppId : info.uid);
12110                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12111
12112                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12113                        extras, null, null, null);
12114                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12115                        extras, null, null, null);
12116                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12117                        null, packageName, null, null);
12118            }
12119        }
12120        // Force a gc here.
12121        Runtime.getRuntime().gc();
12122        // Delete the resources here after sending the broadcast to let
12123        // other processes clean up before deleting resources.
12124        if (info.args != null) {
12125            synchronized (mInstallLock) {
12126                info.args.doPostDeleteLI(true);
12127            }
12128        }
12129
12130        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12131    }
12132
12133    class PackageRemovedInfo {
12134        String removedPackage;
12135        int uid = -1;
12136        int removedAppId = -1;
12137        int[] removedUsers = null;
12138        boolean isRemovedPackageSystemUpdate = false;
12139        // Clean up resources deleted packages.
12140        InstallArgs args = null;
12141
12142        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12143            Bundle extras = new Bundle(1);
12144            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12145            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12146            if (replacing) {
12147                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12148            }
12149            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12150            if (removedPackage != null) {
12151                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12152                        extras, null, null, removedUsers);
12153                if (fullRemove && !replacing) {
12154                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12155                            extras, null, null, removedUsers);
12156                }
12157            }
12158            if (removedAppId >= 0) {
12159                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12160                        removedUsers);
12161            }
12162        }
12163    }
12164
12165    /*
12166     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12167     * flag is not set, the data directory is removed as well.
12168     * make sure this flag is set for partially installed apps. If not its meaningless to
12169     * delete a partially installed application.
12170     */
12171    private void removePackageDataLI(PackageSetting ps,
12172            int[] allUserHandles, boolean[] perUserInstalled,
12173            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12174        String packageName = ps.name;
12175        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12176        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12177        // Retrieve object to delete permissions for shared user later on
12178        final PackageSetting deletedPs;
12179        // reader
12180        synchronized (mPackages) {
12181            deletedPs = mSettings.mPackages.get(packageName);
12182            if (outInfo != null) {
12183                outInfo.removedPackage = packageName;
12184                outInfo.removedUsers = deletedPs != null
12185                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12186                        : null;
12187            }
12188        }
12189        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12190            removeDataDirsLI(ps.volumeUuid, packageName);
12191            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12192        }
12193        // writer
12194        synchronized (mPackages) {
12195            if (deletedPs != null) {
12196                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12197                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12198                    clearDefaultBrowserIfNeeded(packageName);
12199                    if (outInfo != null) {
12200                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12201                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12202                    }
12203                    updatePermissionsLPw(deletedPs.name, null, 0);
12204                    if (deletedPs.sharedUser != null) {
12205                        // Remove permissions associated with package. Since runtime
12206                        // permissions are per user we have to kill the removed package
12207                        // or packages running under the shared user of the removed
12208                        // package if revoking the permissions requested only by the removed
12209                        // package is successful and this causes a change in gids.
12210                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12211                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12212                                    userId);
12213                            if (userIdToKill == UserHandle.USER_ALL
12214                                    || userIdToKill >= UserHandle.USER_OWNER) {
12215                                // If gids changed for this user, kill all affected packages.
12216                                mHandler.post(new Runnable() {
12217                                    @Override
12218                                    public void run() {
12219                                        // This has to happen with no lock held.
12220                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12221                                                KILL_APP_REASON_GIDS_CHANGED);
12222                                    }
12223                                });
12224                            break;
12225                            }
12226                        }
12227                    }
12228                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12229                }
12230                // make sure to preserve per-user disabled state if this removal was just
12231                // a downgrade of a system app to the factory package
12232                if (allUserHandles != null && perUserInstalled != null) {
12233                    if (DEBUG_REMOVE) {
12234                        Slog.d(TAG, "Propagating install state across downgrade");
12235                    }
12236                    for (int i = 0; i < allUserHandles.length; i++) {
12237                        if (DEBUG_REMOVE) {
12238                            Slog.d(TAG, "    user " + allUserHandles[i]
12239                                    + " => " + perUserInstalled[i]);
12240                        }
12241                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12242                    }
12243                }
12244            }
12245            // can downgrade to reader
12246            if (writeSettings) {
12247                // Save settings now
12248                mSettings.writeLPr();
12249            }
12250        }
12251        if (outInfo != null) {
12252            // A user ID was deleted here. Go through all users and remove it
12253            // from KeyStore.
12254            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12255        }
12256    }
12257
12258    static boolean locationIsPrivileged(File path) {
12259        try {
12260            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12261                    .getCanonicalPath();
12262            return path.getCanonicalPath().startsWith(privilegedAppDir);
12263        } catch (IOException e) {
12264            Slog.e(TAG, "Unable to access code path " + path);
12265        }
12266        return false;
12267    }
12268
12269    /*
12270     * Tries to delete system package.
12271     */
12272    private boolean deleteSystemPackageLI(PackageSetting newPs,
12273            int[] allUserHandles, boolean[] perUserInstalled,
12274            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12275        final boolean applyUserRestrictions
12276                = (allUserHandles != null) && (perUserInstalled != null);
12277        PackageSetting disabledPs = null;
12278        // Confirm if the system package has been updated
12279        // An updated system app can be deleted. This will also have to restore
12280        // the system pkg from system partition
12281        // reader
12282        synchronized (mPackages) {
12283            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12284        }
12285        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12286                + " disabledPs=" + disabledPs);
12287        if (disabledPs == null) {
12288            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12289            return false;
12290        } else if (DEBUG_REMOVE) {
12291            Slog.d(TAG, "Deleting system pkg from data partition");
12292        }
12293        if (DEBUG_REMOVE) {
12294            if (applyUserRestrictions) {
12295                Slog.d(TAG, "Remembering install states:");
12296                for (int i = 0; i < allUserHandles.length; i++) {
12297                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12298                }
12299            }
12300        }
12301        // Delete the updated package
12302        outInfo.isRemovedPackageSystemUpdate = true;
12303        if (disabledPs.versionCode < newPs.versionCode) {
12304            // Delete data for downgrades
12305            flags &= ~PackageManager.DELETE_KEEP_DATA;
12306        } else {
12307            // Preserve data by setting flag
12308            flags |= PackageManager.DELETE_KEEP_DATA;
12309        }
12310        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12311                allUserHandles, perUserInstalled, outInfo, writeSettings);
12312        if (!ret) {
12313            return false;
12314        }
12315        // writer
12316        synchronized (mPackages) {
12317            // Reinstate the old system package
12318            mSettings.enableSystemPackageLPw(newPs.name);
12319            // Remove any native libraries from the upgraded package.
12320            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12321        }
12322        // Install the system package
12323        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12324        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12325        if (locationIsPrivileged(disabledPs.codePath)) {
12326            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12327        }
12328
12329        final PackageParser.Package newPkg;
12330        try {
12331            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12332        } catch (PackageManagerException e) {
12333            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12334            return false;
12335        }
12336
12337        // writer
12338        synchronized (mPackages) {
12339            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12340            updatePermissionsLPw(newPkg.packageName, newPkg,
12341                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12342            if (applyUserRestrictions) {
12343                if (DEBUG_REMOVE) {
12344                    Slog.d(TAG, "Propagating install state across reinstall");
12345                }
12346                for (int i = 0; i < allUserHandles.length; i++) {
12347                    if (DEBUG_REMOVE) {
12348                        Slog.d(TAG, "    user " + allUserHandles[i]
12349                                + " => " + perUserInstalled[i]);
12350                    }
12351                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12352                }
12353                // Regardless of writeSettings we need to ensure that this restriction
12354                // state propagation is persisted
12355                mSettings.writeAllUsersPackageRestrictionsLPr();
12356            }
12357            // can downgrade to reader here
12358            if (writeSettings) {
12359                mSettings.writeLPr();
12360            }
12361        }
12362        return true;
12363    }
12364
12365    private boolean deleteInstalledPackageLI(PackageSetting ps,
12366            boolean deleteCodeAndResources, int flags,
12367            int[] allUserHandles, boolean[] perUserInstalled,
12368            PackageRemovedInfo outInfo, boolean writeSettings) {
12369        if (outInfo != null) {
12370            outInfo.uid = ps.appId;
12371        }
12372
12373        // Delete package data from internal structures and also remove data if flag is set
12374        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12375
12376        // Delete application code and resources
12377        if (deleteCodeAndResources && (outInfo != null)) {
12378            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12379                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12380            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12381        }
12382        return true;
12383    }
12384
12385    @Override
12386    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12387            int userId) {
12388        mContext.enforceCallingOrSelfPermission(
12389                android.Manifest.permission.DELETE_PACKAGES, null);
12390        synchronized (mPackages) {
12391            PackageSetting ps = mSettings.mPackages.get(packageName);
12392            if (ps == null) {
12393                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12394                return false;
12395            }
12396            if (!ps.getInstalled(userId)) {
12397                // Can't block uninstall for an app that is not installed or enabled.
12398                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12399                return false;
12400            }
12401            ps.setBlockUninstall(blockUninstall, userId);
12402            mSettings.writePackageRestrictionsLPr(userId);
12403        }
12404        return true;
12405    }
12406
12407    @Override
12408    public boolean getBlockUninstallForUser(String packageName, int userId) {
12409        synchronized (mPackages) {
12410            PackageSetting ps = mSettings.mPackages.get(packageName);
12411            if (ps == null) {
12412                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
12413                return false;
12414            }
12415            return ps.getBlockUninstall(userId);
12416        }
12417    }
12418
12419    /*
12420     * This method handles package deletion in general
12421     */
12422    private boolean deletePackageLI(String packageName, UserHandle user,
12423            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
12424            int flags, PackageRemovedInfo outInfo,
12425            boolean writeSettings) {
12426        if (packageName == null) {
12427            Slog.w(TAG, "Attempt to delete null packageName.");
12428            return false;
12429        }
12430        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
12431        PackageSetting ps;
12432        boolean dataOnly = false;
12433        int removeUser = -1;
12434        int appId = -1;
12435        synchronized (mPackages) {
12436            ps = mSettings.mPackages.get(packageName);
12437            if (ps == null) {
12438                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12439                return false;
12440            }
12441            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
12442                    && user.getIdentifier() != UserHandle.USER_ALL) {
12443                // The caller is asking that the package only be deleted for a single
12444                // user.  To do this, we just mark its uninstalled state and delete
12445                // its data.  If this is a system app, we only allow this to happen if
12446                // they have set the special DELETE_SYSTEM_APP which requests different
12447                // semantics than normal for uninstalling system apps.
12448                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
12449                ps.setUserState(user.getIdentifier(),
12450                        COMPONENT_ENABLED_STATE_DEFAULT,
12451                        false, //installed
12452                        true,  //stopped
12453                        true,  //notLaunched
12454                        false, //hidden
12455                        null, null, null,
12456                        false, // blockUninstall
12457                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
12458                if (!isSystemApp(ps)) {
12459                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
12460                        // Other user still have this package installed, so all
12461                        // we need to do is clear this user's data and save that
12462                        // it is uninstalled.
12463                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
12464                        removeUser = user.getIdentifier();
12465                        appId = ps.appId;
12466                        scheduleWritePackageRestrictionsLocked(removeUser);
12467                    } else {
12468                        // We need to set it back to 'installed' so the uninstall
12469                        // broadcasts will be sent correctly.
12470                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
12471                        ps.setInstalled(true, user.getIdentifier());
12472                    }
12473                } else {
12474                    // This is a system app, so we assume that the
12475                    // other users still have this package installed, so all
12476                    // we need to do is clear this user's data and save that
12477                    // it is uninstalled.
12478                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
12479                    removeUser = user.getIdentifier();
12480                    appId = ps.appId;
12481                    scheduleWritePackageRestrictionsLocked(removeUser);
12482                }
12483            }
12484        }
12485
12486        if (removeUser >= 0) {
12487            // From above, we determined that we are deleting this only
12488            // for a single user.  Continue the work here.
12489            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
12490            if (outInfo != null) {
12491                outInfo.removedPackage = packageName;
12492                outInfo.removedAppId = appId;
12493                outInfo.removedUsers = new int[] {removeUser};
12494            }
12495            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
12496            removeKeystoreDataIfNeeded(removeUser, appId);
12497            schedulePackageCleaning(packageName, removeUser, false);
12498            synchronized (mPackages) {
12499                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
12500                    scheduleWritePackageRestrictionsLocked(removeUser);
12501                }
12502            }
12503            return true;
12504        }
12505
12506        if (dataOnly) {
12507            // Delete application data first
12508            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
12509            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
12510            return true;
12511        }
12512
12513        boolean ret = false;
12514        if (isSystemApp(ps)) {
12515            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
12516            // When an updated system application is deleted we delete the existing resources as well and
12517            // fall back to existing code in system partition
12518            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
12519                    flags, outInfo, writeSettings);
12520        } else {
12521            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
12522            // Kill application pre-emptively especially for apps on sd.
12523            killApplication(packageName, ps.appId, "uninstall pkg");
12524            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
12525                    allUserHandles, perUserInstalled,
12526                    outInfo, writeSettings);
12527        }
12528
12529        return ret;
12530    }
12531
12532    private final class ClearStorageConnection implements ServiceConnection {
12533        IMediaContainerService mContainerService;
12534
12535        @Override
12536        public void onServiceConnected(ComponentName name, IBinder service) {
12537            synchronized (this) {
12538                mContainerService = IMediaContainerService.Stub.asInterface(service);
12539                notifyAll();
12540            }
12541        }
12542
12543        @Override
12544        public void onServiceDisconnected(ComponentName name) {
12545        }
12546    }
12547
12548    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
12549        final boolean mounted;
12550        if (Environment.isExternalStorageEmulated()) {
12551            mounted = true;
12552        } else {
12553            final String status = Environment.getExternalStorageState();
12554
12555            mounted = status.equals(Environment.MEDIA_MOUNTED)
12556                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
12557        }
12558
12559        if (!mounted) {
12560            return;
12561        }
12562
12563        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
12564        int[] users;
12565        if (userId == UserHandle.USER_ALL) {
12566            users = sUserManager.getUserIds();
12567        } else {
12568            users = new int[] { userId };
12569        }
12570        final ClearStorageConnection conn = new ClearStorageConnection();
12571        if (mContext.bindServiceAsUser(
12572                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
12573            try {
12574                for (int curUser : users) {
12575                    long timeout = SystemClock.uptimeMillis() + 5000;
12576                    synchronized (conn) {
12577                        long now = SystemClock.uptimeMillis();
12578                        while (conn.mContainerService == null && now < timeout) {
12579                            try {
12580                                conn.wait(timeout - now);
12581                            } catch (InterruptedException e) {
12582                            }
12583                        }
12584                    }
12585                    if (conn.mContainerService == null) {
12586                        return;
12587                    }
12588
12589                    final UserEnvironment userEnv = new UserEnvironment(curUser);
12590                    clearDirectory(conn.mContainerService,
12591                            userEnv.buildExternalStorageAppCacheDirs(packageName));
12592                    if (allData) {
12593                        clearDirectory(conn.mContainerService,
12594                                userEnv.buildExternalStorageAppDataDirs(packageName));
12595                        clearDirectory(conn.mContainerService,
12596                                userEnv.buildExternalStorageAppMediaDirs(packageName));
12597                    }
12598                }
12599            } finally {
12600                mContext.unbindService(conn);
12601            }
12602        }
12603    }
12604
12605    @Override
12606    public void clearApplicationUserData(final String packageName,
12607            final IPackageDataObserver observer, final int userId) {
12608        mContext.enforceCallingOrSelfPermission(
12609                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
12610        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
12611        // Queue up an async operation since the package deletion may take a little while.
12612        mHandler.post(new Runnable() {
12613            public void run() {
12614                mHandler.removeCallbacks(this);
12615                final boolean succeeded;
12616                synchronized (mInstallLock) {
12617                    succeeded = clearApplicationUserDataLI(packageName, userId);
12618                }
12619                clearExternalStorageDataSync(packageName, userId, true);
12620                if (succeeded) {
12621                    // invoke DeviceStorageMonitor's update method to clear any notifications
12622                    DeviceStorageMonitorInternal
12623                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
12624                    if (dsm != null) {
12625                        dsm.checkMemory();
12626                    }
12627                }
12628                if(observer != null) {
12629                    try {
12630                        observer.onRemoveCompleted(packageName, succeeded);
12631                    } catch (RemoteException e) {
12632                        Log.i(TAG, "Observer no longer exists.");
12633                    }
12634                } //end if observer
12635            } //end run
12636        });
12637    }
12638
12639    private boolean clearApplicationUserDataLI(String packageName, int userId) {
12640        if (packageName == null) {
12641            Slog.w(TAG, "Attempt to delete null packageName.");
12642            return false;
12643        }
12644
12645        // Try finding details about the requested package
12646        PackageParser.Package pkg;
12647        synchronized (mPackages) {
12648            pkg = mPackages.get(packageName);
12649            if (pkg == null) {
12650                final PackageSetting ps = mSettings.mPackages.get(packageName);
12651                if (ps != null) {
12652                    pkg = ps.pkg;
12653                }
12654            }
12655
12656            if (pkg == null) {
12657                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12658                return false;
12659            }
12660
12661            PackageSetting ps = (PackageSetting) pkg.mExtras;
12662            PermissionsState permissionsState = ps.getPermissionsState();
12663            revokeRuntimePermissionsAndClearUserSetFlagsLocked(permissionsState, userId);
12664        }
12665
12666        // Always delete data directories for package, even if we found no other
12667        // record of app. This helps users recover from UID mismatches without
12668        // resorting to a full data wipe.
12669        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
12670        if (retCode < 0) {
12671            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
12672            return false;
12673        }
12674
12675        final int appId = pkg.applicationInfo.uid;
12676        removeKeystoreDataIfNeeded(userId, appId);
12677
12678        // Create a native library symlink only if we have native libraries
12679        // and if the native libraries are 32 bit libraries. We do not provide
12680        // this symlink for 64 bit libraries.
12681        if (pkg.applicationInfo.primaryCpuAbi != null &&
12682                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
12683            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
12684            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
12685                    nativeLibPath, userId) < 0) {
12686                Slog.w(TAG, "Failed linking native library dir");
12687                return false;
12688            }
12689        }
12690
12691        return true;
12692    }
12693
12694
12695    /**
12696     * Revokes granted runtime permissions and clears resettable flags
12697     * which are flags that can be set by a user interaction.
12698     *
12699     * @param permissionsState The permission state to reset.
12700     * @param userId The device user for which to do a reset.
12701     */
12702    private void revokeRuntimePermissionsAndClearUserSetFlagsLocked(
12703            PermissionsState permissionsState, int userId) {
12704        final int userSetFlags = PackageManager.FLAG_PERMISSION_USER_SET
12705                | PackageManager.FLAG_PERMISSION_USER_FIXED
12706                | PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12707
12708        boolean needsWrite = false;
12709
12710        for (PermissionState state : permissionsState.getRuntimePermissionStates(userId)) {
12711            BasePermission bp = mSettings.mPermissions.get(state.getName());
12712            if (bp != null) {
12713                permissionsState.revokeRuntimePermission(bp, userId);
12714                permissionsState.updatePermissionFlags(bp, userId, userSetFlags, 0);
12715                needsWrite = true;
12716            }
12717        }
12718
12719        if (needsWrite) {
12720            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
12721        }
12722    }
12723
12724    /**
12725     * Remove entries from the keystore daemon. Will only remove it if the
12726     * {@code appId} is valid.
12727     */
12728    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
12729        if (appId < 0) {
12730            return;
12731        }
12732
12733        final KeyStore keyStore = KeyStore.getInstance();
12734        if (keyStore != null) {
12735            if (userId == UserHandle.USER_ALL) {
12736                for (final int individual : sUserManager.getUserIds()) {
12737                    keyStore.clearUid(UserHandle.getUid(individual, appId));
12738                }
12739            } else {
12740                keyStore.clearUid(UserHandle.getUid(userId, appId));
12741            }
12742        } else {
12743            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
12744        }
12745    }
12746
12747    @Override
12748    public void deleteApplicationCacheFiles(final String packageName,
12749            final IPackageDataObserver observer) {
12750        mContext.enforceCallingOrSelfPermission(
12751                android.Manifest.permission.DELETE_CACHE_FILES, null);
12752        // Queue up an async operation since the package deletion may take a little while.
12753        final int userId = UserHandle.getCallingUserId();
12754        mHandler.post(new Runnable() {
12755            public void run() {
12756                mHandler.removeCallbacks(this);
12757                final boolean succeded;
12758                synchronized (mInstallLock) {
12759                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
12760                }
12761                clearExternalStorageDataSync(packageName, userId, false);
12762                if (observer != null) {
12763                    try {
12764                        observer.onRemoveCompleted(packageName, succeded);
12765                    } catch (RemoteException e) {
12766                        Log.i(TAG, "Observer no longer exists.");
12767                    }
12768                } //end if observer
12769            } //end run
12770        });
12771    }
12772
12773    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
12774        if (packageName == null) {
12775            Slog.w(TAG, "Attempt to delete null packageName.");
12776            return false;
12777        }
12778        PackageParser.Package p;
12779        synchronized (mPackages) {
12780            p = mPackages.get(packageName);
12781        }
12782        if (p == null) {
12783            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12784            return false;
12785        }
12786        final ApplicationInfo applicationInfo = p.applicationInfo;
12787        if (applicationInfo == null) {
12788            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12789            return false;
12790        }
12791        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
12792        if (retCode < 0) {
12793            Slog.w(TAG, "Couldn't remove cache files for package: "
12794                       + packageName + " u" + userId);
12795            return false;
12796        }
12797        return true;
12798    }
12799
12800    @Override
12801    public void getPackageSizeInfo(final String packageName, int userHandle,
12802            final IPackageStatsObserver observer) {
12803        mContext.enforceCallingOrSelfPermission(
12804                android.Manifest.permission.GET_PACKAGE_SIZE, null);
12805        if (packageName == null) {
12806            throw new IllegalArgumentException("Attempt to get size of null packageName");
12807        }
12808
12809        PackageStats stats = new PackageStats(packageName, userHandle);
12810
12811        /*
12812         * Queue up an async operation since the package measurement may take a
12813         * little while.
12814         */
12815        Message msg = mHandler.obtainMessage(INIT_COPY);
12816        msg.obj = new MeasureParams(stats, observer);
12817        mHandler.sendMessage(msg);
12818    }
12819
12820    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
12821            PackageStats pStats) {
12822        if (packageName == null) {
12823            Slog.w(TAG, "Attempt to get size of null packageName.");
12824            return false;
12825        }
12826        PackageParser.Package p;
12827        boolean dataOnly = false;
12828        String libDirRoot = null;
12829        String asecPath = null;
12830        PackageSetting ps = null;
12831        synchronized (mPackages) {
12832            p = mPackages.get(packageName);
12833            ps = mSettings.mPackages.get(packageName);
12834            if(p == null) {
12835                dataOnly = true;
12836                if((ps == null) || (ps.pkg == null)) {
12837                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12838                    return false;
12839                }
12840                p = ps.pkg;
12841            }
12842            if (ps != null) {
12843                libDirRoot = ps.legacyNativeLibraryPathString;
12844            }
12845            if (p != null && (isExternal(p) || p.isForwardLocked())) {
12846                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
12847                if (secureContainerId != null) {
12848                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
12849                }
12850            }
12851        }
12852        String publicSrcDir = null;
12853        if(!dataOnly) {
12854            final ApplicationInfo applicationInfo = p.applicationInfo;
12855            if (applicationInfo == null) {
12856                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12857                return false;
12858            }
12859            if (p.isForwardLocked()) {
12860                publicSrcDir = applicationInfo.getBaseResourcePath();
12861            }
12862        }
12863        // TODO: extend to measure size of split APKs
12864        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
12865        // not just the first level.
12866        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
12867        // just the primary.
12868        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
12869        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
12870                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
12871        if (res < 0) {
12872            return false;
12873        }
12874
12875        // Fix-up for forward-locked applications in ASEC containers.
12876        if (!isExternal(p)) {
12877            pStats.codeSize += pStats.externalCodeSize;
12878            pStats.externalCodeSize = 0L;
12879        }
12880
12881        return true;
12882    }
12883
12884
12885    @Override
12886    public void addPackageToPreferred(String packageName) {
12887        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
12888    }
12889
12890    @Override
12891    public void removePackageFromPreferred(String packageName) {
12892        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
12893    }
12894
12895    @Override
12896    public List<PackageInfo> getPreferredPackages(int flags) {
12897        return new ArrayList<PackageInfo>();
12898    }
12899
12900    private int getUidTargetSdkVersionLockedLPr(int uid) {
12901        Object obj = mSettings.getUserIdLPr(uid);
12902        if (obj instanceof SharedUserSetting) {
12903            final SharedUserSetting sus = (SharedUserSetting) obj;
12904            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
12905            final Iterator<PackageSetting> it = sus.packages.iterator();
12906            while (it.hasNext()) {
12907                final PackageSetting ps = it.next();
12908                if (ps.pkg != null) {
12909                    int v = ps.pkg.applicationInfo.targetSdkVersion;
12910                    if (v < vers) vers = v;
12911                }
12912            }
12913            return vers;
12914        } else if (obj instanceof PackageSetting) {
12915            final PackageSetting ps = (PackageSetting) obj;
12916            if (ps.pkg != null) {
12917                return ps.pkg.applicationInfo.targetSdkVersion;
12918            }
12919        }
12920        return Build.VERSION_CODES.CUR_DEVELOPMENT;
12921    }
12922
12923    @Override
12924    public void addPreferredActivity(IntentFilter filter, int match,
12925            ComponentName[] set, ComponentName activity, int userId) {
12926        addPreferredActivityInternal(filter, match, set, activity, true, userId,
12927                "Adding preferred");
12928    }
12929
12930    private void addPreferredActivityInternal(IntentFilter filter, int match,
12931            ComponentName[] set, ComponentName activity, boolean always, int userId,
12932            String opname) {
12933        // writer
12934        int callingUid = Binder.getCallingUid();
12935        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
12936        if (filter.countActions() == 0) {
12937            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
12938            return;
12939        }
12940        synchronized (mPackages) {
12941            if (mContext.checkCallingOrSelfPermission(
12942                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12943                    != PackageManager.PERMISSION_GRANTED) {
12944                if (getUidTargetSdkVersionLockedLPr(callingUid)
12945                        < Build.VERSION_CODES.FROYO) {
12946                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
12947                            + callingUid);
12948                    return;
12949                }
12950                mContext.enforceCallingOrSelfPermission(
12951                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12952            }
12953
12954            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
12955            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
12956                    + userId + ":");
12957            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12958            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
12959            scheduleWritePackageRestrictionsLocked(userId);
12960        }
12961    }
12962
12963    @Override
12964    public void replacePreferredActivity(IntentFilter filter, int match,
12965            ComponentName[] set, ComponentName activity, int userId) {
12966        if (filter.countActions() != 1) {
12967            throw new IllegalArgumentException(
12968                    "replacePreferredActivity expects filter to have only 1 action.");
12969        }
12970        if (filter.countDataAuthorities() != 0
12971                || filter.countDataPaths() != 0
12972                || filter.countDataSchemes() > 1
12973                || filter.countDataTypes() != 0) {
12974            throw new IllegalArgumentException(
12975                    "replacePreferredActivity expects filter to have no data authorities, " +
12976                    "paths, or types; and at most one scheme.");
12977        }
12978
12979        final int callingUid = Binder.getCallingUid();
12980        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
12981        synchronized (mPackages) {
12982            if (mContext.checkCallingOrSelfPermission(
12983                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12984                    != PackageManager.PERMISSION_GRANTED) {
12985                if (getUidTargetSdkVersionLockedLPr(callingUid)
12986                        < Build.VERSION_CODES.FROYO) {
12987                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
12988                            + Binder.getCallingUid());
12989                    return;
12990                }
12991                mContext.enforceCallingOrSelfPermission(
12992                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12993            }
12994
12995            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
12996            if (pir != null) {
12997                // Get all of the existing entries that exactly match this filter.
12998                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
12999                if (existing != null && existing.size() == 1) {
13000                    PreferredActivity cur = existing.get(0);
13001                    if (DEBUG_PREFERRED) {
13002                        Slog.i(TAG, "Checking replace of preferred:");
13003                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13004                        if (!cur.mPref.mAlways) {
13005                            Slog.i(TAG, "  -- CUR; not mAlways!");
13006                        } else {
13007                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13008                            Slog.i(TAG, "  -- CUR: mSet="
13009                                    + Arrays.toString(cur.mPref.mSetComponents));
13010                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13011                            Slog.i(TAG, "  -- NEW: mMatch="
13012                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13013                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13014                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13015                        }
13016                    }
13017                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13018                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13019                            && cur.mPref.sameSet(set)) {
13020                        // Setting the preferred activity to what it happens to be already
13021                        if (DEBUG_PREFERRED) {
13022                            Slog.i(TAG, "Replacing with same preferred activity "
13023                                    + cur.mPref.mShortComponent + " for user "
13024                                    + userId + ":");
13025                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13026                        }
13027                        return;
13028                    }
13029                }
13030
13031                if (existing != null) {
13032                    if (DEBUG_PREFERRED) {
13033                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13034                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13035                    }
13036                    for (int i = 0; i < existing.size(); i++) {
13037                        PreferredActivity pa = existing.get(i);
13038                        if (DEBUG_PREFERRED) {
13039                            Slog.i(TAG, "Removing existing preferred activity "
13040                                    + pa.mPref.mComponent + ":");
13041                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13042                        }
13043                        pir.removeFilter(pa);
13044                    }
13045                }
13046            }
13047            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13048                    "Replacing preferred");
13049        }
13050    }
13051
13052    @Override
13053    public void clearPackagePreferredActivities(String packageName) {
13054        final int uid = Binder.getCallingUid();
13055        // writer
13056        synchronized (mPackages) {
13057            PackageParser.Package pkg = mPackages.get(packageName);
13058            if (pkg == null || pkg.applicationInfo.uid != uid) {
13059                if (mContext.checkCallingOrSelfPermission(
13060                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13061                        != PackageManager.PERMISSION_GRANTED) {
13062                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13063                            < Build.VERSION_CODES.FROYO) {
13064                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13065                                + Binder.getCallingUid());
13066                        return;
13067                    }
13068                    mContext.enforceCallingOrSelfPermission(
13069                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13070                }
13071            }
13072
13073            int user = UserHandle.getCallingUserId();
13074            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13075                scheduleWritePackageRestrictionsLocked(user);
13076            }
13077        }
13078    }
13079
13080    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13081    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13082        ArrayList<PreferredActivity> removed = null;
13083        boolean changed = false;
13084        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13085            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13086            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13087            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13088                continue;
13089            }
13090            Iterator<PreferredActivity> it = pir.filterIterator();
13091            while (it.hasNext()) {
13092                PreferredActivity pa = it.next();
13093                // Mark entry for removal only if it matches the package name
13094                // and the entry is of type "always".
13095                if (packageName == null ||
13096                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13097                                && pa.mPref.mAlways)) {
13098                    if (removed == null) {
13099                        removed = new ArrayList<PreferredActivity>();
13100                    }
13101                    removed.add(pa);
13102                }
13103            }
13104            if (removed != null) {
13105                for (int j=0; j<removed.size(); j++) {
13106                    PreferredActivity pa = removed.get(j);
13107                    pir.removeFilter(pa);
13108                }
13109                changed = true;
13110            }
13111        }
13112        return changed;
13113    }
13114
13115    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13116    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13117        if (userId == UserHandle.USER_ALL) {
13118            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13119                    sUserManager.getUserIds())) {
13120                for (int oneUserId : sUserManager.getUserIds()) {
13121                    scheduleWritePackageRestrictionsLocked(oneUserId);
13122                }
13123            }
13124        } else {
13125            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13126                scheduleWritePackageRestrictionsLocked(userId);
13127            }
13128        }
13129    }
13130
13131
13132    void clearDefaultBrowserIfNeeded(String packageName) {
13133        for (int oneUserId : sUserManager.getUserIds()) {
13134            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13135            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13136            if (packageName.equals(defaultBrowserPackageName)) {
13137                setDefaultBrowserPackageName(null, oneUserId);
13138            }
13139        }
13140    }
13141
13142    @Override
13143    public void resetPreferredActivities(int userId) {
13144        /* TODO: Actually use userId. Why is it being passed in? */
13145        mContext.enforceCallingOrSelfPermission(
13146                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13147        // writer
13148        synchronized (mPackages) {
13149            int user = UserHandle.getCallingUserId();
13150            clearPackagePreferredActivitiesLPw(null, user);
13151            mSettings.readDefaultPreferredAppsLPw(this, user);
13152            scheduleWritePackageRestrictionsLocked(user);
13153        }
13154    }
13155
13156    @Override
13157    public int getPreferredActivities(List<IntentFilter> outFilters,
13158            List<ComponentName> outActivities, String packageName) {
13159
13160        int num = 0;
13161        final int userId = UserHandle.getCallingUserId();
13162        // reader
13163        synchronized (mPackages) {
13164            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13165            if (pir != null) {
13166                final Iterator<PreferredActivity> it = pir.filterIterator();
13167                while (it.hasNext()) {
13168                    final PreferredActivity pa = it.next();
13169                    if (packageName == null
13170                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13171                                    && pa.mPref.mAlways)) {
13172                        if (outFilters != null) {
13173                            outFilters.add(new IntentFilter(pa));
13174                        }
13175                        if (outActivities != null) {
13176                            outActivities.add(pa.mPref.mComponent);
13177                        }
13178                    }
13179                }
13180            }
13181        }
13182
13183        return num;
13184    }
13185
13186    @Override
13187    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13188            int userId) {
13189        int callingUid = Binder.getCallingUid();
13190        if (callingUid != Process.SYSTEM_UID) {
13191            throw new SecurityException(
13192                    "addPersistentPreferredActivity can only be run by the system");
13193        }
13194        if (filter.countActions() == 0) {
13195            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13196            return;
13197        }
13198        synchronized (mPackages) {
13199            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13200                    " :");
13201            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13202            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13203                    new PersistentPreferredActivity(filter, activity));
13204            scheduleWritePackageRestrictionsLocked(userId);
13205        }
13206    }
13207
13208    @Override
13209    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13210        int callingUid = Binder.getCallingUid();
13211        if (callingUid != Process.SYSTEM_UID) {
13212            throw new SecurityException(
13213                    "clearPackagePersistentPreferredActivities can only be run by the system");
13214        }
13215        ArrayList<PersistentPreferredActivity> removed = null;
13216        boolean changed = false;
13217        synchronized (mPackages) {
13218            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13219                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13220                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13221                        .valueAt(i);
13222                if (userId != thisUserId) {
13223                    continue;
13224                }
13225                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13226                while (it.hasNext()) {
13227                    PersistentPreferredActivity ppa = it.next();
13228                    // Mark entry for removal only if it matches the package name.
13229                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13230                        if (removed == null) {
13231                            removed = new ArrayList<PersistentPreferredActivity>();
13232                        }
13233                        removed.add(ppa);
13234                    }
13235                }
13236                if (removed != null) {
13237                    for (int j=0; j<removed.size(); j++) {
13238                        PersistentPreferredActivity ppa = removed.get(j);
13239                        ppir.removeFilter(ppa);
13240                    }
13241                    changed = true;
13242                }
13243            }
13244
13245            if (changed) {
13246                scheduleWritePackageRestrictionsLocked(userId);
13247            }
13248        }
13249    }
13250
13251    /**
13252     * Non-Binder method, support for the backup/restore mechanism: write the
13253     * full set of preferred activities in its canonical XML format.  Returns true
13254     * on success; false otherwise.
13255     */
13256    @Override
13257    public byte[] getPreferredActivityBackup(int userId) {
13258        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13259            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13260        }
13261
13262        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13263        try {
13264            final XmlSerializer serializer = new FastXmlSerializer();
13265            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13266            serializer.startDocument(null, true);
13267            serializer.startTag(null, TAG_PREFERRED_BACKUP);
13268
13269            synchronized (mPackages) {
13270                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13271            }
13272
13273            serializer.endTag(null, TAG_PREFERRED_BACKUP);
13274            serializer.endDocument();
13275            serializer.flush();
13276        } catch (Exception e) {
13277            if (DEBUG_BACKUP) {
13278                Slog.e(TAG, "Unable to write preferred activities for backup", e);
13279            }
13280            return null;
13281        }
13282
13283        return dataStream.toByteArray();
13284    }
13285
13286    @Override
13287    public void restorePreferredActivities(byte[] backup, int userId) {
13288        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13289            throw new SecurityException("Only the system may call restorePreferredActivities()");
13290        }
13291
13292        try {
13293            final XmlPullParser parser = Xml.newPullParser();
13294            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13295
13296            int type;
13297            while ((type = parser.next()) != XmlPullParser.START_TAG
13298                    && type != XmlPullParser.END_DOCUMENT) {
13299            }
13300            if (type != XmlPullParser.START_TAG) {
13301                // oops didn't find a start tag?!
13302                if (DEBUG_BACKUP) {
13303                    Slog.e(TAG, "Didn't find start tag during restore");
13304                }
13305                return;
13306            }
13307
13308            // this is supposed to be TAG_PREFERRED_BACKUP
13309            if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) {
13310                if (DEBUG_BACKUP) {
13311                    Slog.e(TAG, "Found unexpected tag " + parser.getName());
13312                }
13313                return;
13314            }
13315
13316            // skip interfering stuff, then we're aligned with the backing implementation
13317            while ((type = parser.next()) == XmlPullParser.TEXT) { }
13318            synchronized (mPackages) {
13319                mSettings.readPreferredActivitiesLPw(parser, userId);
13320            }
13321        } catch (Exception e) {
13322            if (DEBUG_BACKUP) {
13323                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13324            }
13325        }
13326    }
13327
13328    @Override
13329    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
13330            int sourceUserId, int targetUserId, int flags) {
13331        mContext.enforceCallingOrSelfPermission(
13332                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13333        int callingUid = Binder.getCallingUid();
13334        enforceOwnerRights(ownerPackage, callingUid);
13335        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13336        if (intentFilter.countActions() == 0) {
13337            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
13338            return;
13339        }
13340        synchronized (mPackages) {
13341            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
13342                    ownerPackage, targetUserId, flags);
13343            CrossProfileIntentResolver resolver =
13344                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13345            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
13346            // We have all those whose filter is equal. Now checking if the rest is equal as well.
13347            if (existing != null) {
13348                int size = existing.size();
13349                for (int i = 0; i < size; i++) {
13350                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
13351                        return;
13352                    }
13353                }
13354            }
13355            resolver.addFilter(newFilter);
13356            scheduleWritePackageRestrictionsLocked(sourceUserId);
13357        }
13358    }
13359
13360    @Override
13361    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
13362        mContext.enforceCallingOrSelfPermission(
13363                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13364        int callingUid = Binder.getCallingUid();
13365        enforceOwnerRights(ownerPackage, callingUid);
13366        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13367        synchronized (mPackages) {
13368            CrossProfileIntentResolver resolver =
13369                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13370            ArraySet<CrossProfileIntentFilter> set =
13371                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
13372            for (CrossProfileIntentFilter filter : set) {
13373                if (filter.getOwnerPackage().equals(ownerPackage)) {
13374                    resolver.removeFilter(filter);
13375                }
13376            }
13377            scheduleWritePackageRestrictionsLocked(sourceUserId);
13378        }
13379    }
13380
13381    // Enforcing that callingUid is owning pkg on userId
13382    private void enforceOwnerRights(String pkg, int callingUid) {
13383        // The system owns everything.
13384        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
13385            return;
13386        }
13387        int callingUserId = UserHandle.getUserId(callingUid);
13388        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
13389        if (pi == null) {
13390            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
13391                    + callingUserId);
13392        }
13393        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
13394            throw new SecurityException("Calling uid " + callingUid
13395                    + " does not own package " + pkg);
13396        }
13397    }
13398
13399    @Override
13400    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
13401        Intent intent = new Intent(Intent.ACTION_MAIN);
13402        intent.addCategory(Intent.CATEGORY_HOME);
13403
13404        final int callingUserId = UserHandle.getCallingUserId();
13405        List<ResolveInfo> list = queryIntentActivities(intent, null,
13406                PackageManager.GET_META_DATA, callingUserId);
13407        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
13408                true, false, false, callingUserId);
13409
13410        allHomeCandidates.clear();
13411        if (list != null) {
13412            for (ResolveInfo ri : list) {
13413                allHomeCandidates.add(ri);
13414            }
13415        }
13416        return (preferred == null || preferred.activityInfo == null)
13417                ? null
13418                : new ComponentName(preferred.activityInfo.packageName,
13419                        preferred.activityInfo.name);
13420    }
13421
13422    @Override
13423    public void setApplicationEnabledSetting(String appPackageName,
13424            int newState, int flags, int userId, String callingPackage) {
13425        if (!sUserManager.exists(userId)) return;
13426        if (callingPackage == null) {
13427            callingPackage = Integer.toString(Binder.getCallingUid());
13428        }
13429        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
13430    }
13431
13432    @Override
13433    public void setComponentEnabledSetting(ComponentName componentName,
13434            int newState, int flags, int userId) {
13435        if (!sUserManager.exists(userId)) return;
13436        setEnabledSetting(componentName.getPackageName(),
13437                componentName.getClassName(), newState, flags, userId, null);
13438    }
13439
13440    private void setEnabledSetting(final String packageName, String className, int newState,
13441            final int flags, int userId, String callingPackage) {
13442        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
13443              || newState == COMPONENT_ENABLED_STATE_ENABLED
13444              || newState == COMPONENT_ENABLED_STATE_DISABLED
13445              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
13446              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
13447            throw new IllegalArgumentException("Invalid new component state: "
13448                    + newState);
13449        }
13450        PackageSetting pkgSetting;
13451        final int uid = Binder.getCallingUid();
13452        final int permission = mContext.checkCallingOrSelfPermission(
13453                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13454        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
13455        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13456        boolean sendNow = false;
13457        boolean isApp = (className == null);
13458        String componentName = isApp ? packageName : className;
13459        int packageUid = -1;
13460        ArrayList<String> components;
13461
13462        // writer
13463        synchronized (mPackages) {
13464            pkgSetting = mSettings.mPackages.get(packageName);
13465            if (pkgSetting == null) {
13466                if (className == null) {
13467                    throw new IllegalArgumentException(
13468                            "Unknown package: " + packageName);
13469                }
13470                throw new IllegalArgumentException(
13471                        "Unknown component: " + packageName
13472                        + "/" + className);
13473            }
13474            // Allow root and verify that userId is not being specified by a different user
13475            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
13476                throw new SecurityException(
13477                        "Permission Denial: attempt to change component state from pid="
13478                        + Binder.getCallingPid()
13479                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
13480            }
13481            if (className == null) {
13482                // We're dealing with an application/package level state change
13483                if (pkgSetting.getEnabled(userId) == newState) {
13484                    // Nothing to do
13485                    return;
13486                }
13487                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
13488                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
13489                    // Don't care about who enables an app.
13490                    callingPackage = null;
13491                }
13492                pkgSetting.setEnabled(newState, userId, callingPackage);
13493                // pkgSetting.pkg.mSetEnabled = newState;
13494            } else {
13495                // We're dealing with a component level state change
13496                // First, verify that this is a valid class name.
13497                PackageParser.Package pkg = pkgSetting.pkg;
13498                if (pkg == null || !pkg.hasComponentClassName(className)) {
13499                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
13500                        throw new IllegalArgumentException("Component class " + className
13501                                + " does not exist in " + packageName);
13502                    } else {
13503                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
13504                                + className + " does not exist in " + packageName);
13505                    }
13506                }
13507                switch (newState) {
13508                case COMPONENT_ENABLED_STATE_ENABLED:
13509                    if (!pkgSetting.enableComponentLPw(className, userId)) {
13510                        return;
13511                    }
13512                    break;
13513                case COMPONENT_ENABLED_STATE_DISABLED:
13514                    if (!pkgSetting.disableComponentLPw(className, userId)) {
13515                        return;
13516                    }
13517                    break;
13518                case COMPONENT_ENABLED_STATE_DEFAULT:
13519                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
13520                        return;
13521                    }
13522                    break;
13523                default:
13524                    Slog.e(TAG, "Invalid new component state: " + newState);
13525                    return;
13526                }
13527            }
13528            scheduleWritePackageRestrictionsLocked(userId);
13529            components = mPendingBroadcasts.get(userId, packageName);
13530            final boolean newPackage = components == null;
13531            if (newPackage) {
13532                components = new ArrayList<String>();
13533            }
13534            if (!components.contains(componentName)) {
13535                components.add(componentName);
13536            }
13537            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
13538                sendNow = true;
13539                // Purge entry from pending broadcast list if another one exists already
13540                // since we are sending one right away.
13541                mPendingBroadcasts.remove(userId, packageName);
13542            } else {
13543                if (newPackage) {
13544                    mPendingBroadcasts.put(userId, packageName, components);
13545                }
13546                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
13547                    // Schedule a message
13548                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
13549                }
13550            }
13551        }
13552
13553        long callingId = Binder.clearCallingIdentity();
13554        try {
13555            if (sendNow) {
13556                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
13557                sendPackageChangedBroadcast(packageName,
13558                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
13559            }
13560        } finally {
13561            Binder.restoreCallingIdentity(callingId);
13562        }
13563    }
13564
13565    private void sendPackageChangedBroadcast(String packageName,
13566            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
13567        if (DEBUG_INSTALL)
13568            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
13569                    + componentNames);
13570        Bundle extras = new Bundle(4);
13571        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
13572        String nameList[] = new String[componentNames.size()];
13573        componentNames.toArray(nameList);
13574        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
13575        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
13576        extras.putInt(Intent.EXTRA_UID, packageUid);
13577        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
13578                new int[] {UserHandle.getUserId(packageUid)});
13579    }
13580
13581    @Override
13582    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
13583        if (!sUserManager.exists(userId)) return;
13584        final int uid = Binder.getCallingUid();
13585        final int permission = mContext.checkCallingOrSelfPermission(
13586                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13587        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13588        enforceCrossUserPermission(uid, userId, true, true, "stop package");
13589        // writer
13590        synchronized (mPackages) {
13591            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
13592                    allowedByPermission, uid, userId)) {
13593                scheduleWritePackageRestrictionsLocked(userId);
13594            }
13595        }
13596    }
13597
13598    @Override
13599    public String getInstallerPackageName(String packageName) {
13600        // reader
13601        synchronized (mPackages) {
13602            return mSettings.getInstallerPackageNameLPr(packageName);
13603        }
13604    }
13605
13606    @Override
13607    public int getApplicationEnabledSetting(String packageName, int userId) {
13608        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13609        int uid = Binder.getCallingUid();
13610        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
13611        // reader
13612        synchronized (mPackages) {
13613            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
13614        }
13615    }
13616
13617    @Override
13618    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
13619        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13620        int uid = Binder.getCallingUid();
13621        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
13622        // reader
13623        synchronized (mPackages) {
13624            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
13625        }
13626    }
13627
13628    @Override
13629    public void enterSafeMode() {
13630        enforceSystemOrRoot("Only the system can request entering safe mode");
13631
13632        if (!mSystemReady) {
13633            mSafeMode = true;
13634        }
13635    }
13636
13637    @Override
13638    public void systemReady() {
13639        mSystemReady = true;
13640
13641        // Read the compatibilty setting when the system is ready.
13642        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
13643                mContext.getContentResolver(),
13644                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
13645        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
13646        if (DEBUG_SETTINGS) {
13647            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
13648        }
13649
13650        synchronized (mPackages) {
13651            // Verify that all of the preferred activity components actually
13652            // exist.  It is possible for applications to be updated and at
13653            // that point remove a previously declared activity component that
13654            // had been set as a preferred activity.  We try to clean this up
13655            // the next time we encounter that preferred activity, but it is
13656            // possible for the user flow to never be able to return to that
13657            // situation so here we do a sanity check to make sure we haven't
13658            // left any junk around.
13659            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
13660            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13661                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13662                removed.clear();
13663                for (PreferredActivity pa : pir.filterSet()) {
13664                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
13665                        removed.add(pa);
13666                    }
13667                }
13668                if (removed.size() > 0) {
13669                    for (int r=0; r<removed.size(); r++) {
13670                        PreferredActivity pa = removed.get(r);
13671                        Slog.w(TAG, "Removing dangling preferred activity: "
13672                                + pa.mPref.mComponent);
13673                        pir.removeFilter(pa);
13674                    }
13675                    mSettings.writePackageRestrictionsLPr(
13676                            mSettings.mPreferredActivities.keyAt(i));
13677                }
13678            }
13679        }
13680        sUserManager.systemReady();
13681
13682        // Kick off any messages waiting for system ready
13683        if (mPostSystemReadyMessages != null) {
13684            for (Message msg : mPostSystemReadyMessages) {
13685                msg.sendToTarget();
13686            }
13687            mPostSystemReadyMessages = null;
13688        }
13689
13690        // Watch for external volumes that come and go over time
13691        final StorageManager storage = mContext.getSystemService(StorageManager.class);
13692        storage.registerListener(mStorageListener);
13693
13694        mInstallerService.systemReady();
13695        mPackageDexOptimizer.systemReady();
13696    }
13697
13698    @Override
13699    public boolean isSafeMode() {
13700        return mSafeMode;
13701    }
13702
13703    @Override
13704    public boolean hasSystemUidErrors() {
13705        return mHasSystemUidErrors;
13706    }
13707
13708    static String arrayToString(int[] array) {
13709        StringBuffer buf = new StringBuffer(128);
13710        buf.append('[');
13711        if (array != null) {
13712            for (int i=0; i<array.length; i++) {
13713                if (i > 0) buf.append(", ");
13714                buf.append(array[i]);
13715            }
13716        }
13717        buf.append(']');
13718        return buf.toString();
13719    }
13720
13721    static class DumpState {
13722        public static final int DUMP_LIBS = 1 << 0;
13723        public static final int DUMP_FEATURES = 1 << 1;
13724        public static final int DUMP_RESOLVERS = 1 << 2;
13725        public static final int DUMP_PERMISSIONS = 1 << 3;
13726        public static final int DUMP_PACKAGES = 1 << 4;
13727        public static final int DUMP_SHARED_USERS = 1 << 5;
13728        public static final int DUMP_MESSAGES = 1 << 6;
13729        public static final int DUMP_PROVIDERS = 1 << 7;
13730        public static final int DUMP_VERIFIERS = 1 << 8;
13731        public static final int DUMP_PREFERRED = 1 << 9;
13732        public static final int DUMP_PREFERRED_XML = 1 << 10;
13733        public static final int DUMP_KEYSETS = 1 << 11;
13734        public static final int DUMP_VERSION = 1 << 12;
13735        public static final int DUMP_INSTALLS = 1 << 13;
13736        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
13737        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
13738
13739        public static final int OPTION_SHOW_FILTERS = 1 << 0;
13740
13741        private int mTypes;
13742
13743        private int mOptions;
13744
13745        private boolean mTitlePrinted;
13746
13747        private SharedUserSetting mSharedUser;
13748
13749        public boolean isDumping(int type) {
13750            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
13751                return true;
13752            }
13753
13754            return (mTypes & type) != 0;
13755        }
13756
13757        public void setDump(int type) {
13758            mTypes |= type;
13759        }
13760
13761        public boolean isOptionEnabled(int option) {
13762            return (mOptions & option) != 0;
13763        }
13764
13765        public void setOptionEnabled(int option) {
13766            mOptions |= option;
13767        }
13768
13769        public boolean onTitlePrinted() {
13770            final boolean printed = mTitlePrinted;
13771            mTitlePrinted = true;
13772            return printed;
13773        }
13774
13775        public boolean getTitlePrinted() {
13776            return mTitlePrinted;
13777        }
13778
13779        public void setTitlePrinted(boolean enabled) {
13780            mTitlePrinted = enabled;
13781        }
13782
13783        public SharedUserSetting getSharedUser() {
13784            return mSharedUser;
13785        }
13786
13787        public void setSharedUser(SharedUserSetting user) {
13788            mSharedUser = user;
13789        }
13790    }
13791
13792    @Override
13793    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
13794        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
13795                != PackageManager.PERMISSION_GRANTED) {
13796            pw.println("Permission Denial: can't dump ActivityManager from from pid="
13797                    + Binder.getCallingPid()
13798                    + ", uid=" + Binder.getCallingUid()
13799                    + " without permission "
13800                    + android.Manifest.permission.DUMP);
13801            return;
13802        }
13803
13804        DumpState dumpState = new DumpState();
13805        boolean fullPreferred = false;
13806        boolean checkin = false;
13807
13808        String packageName = null;
13809
13810        int opti = 0;
13811        while (opti < args.length) {
13812            String opt = args[opti];
13813            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
13814                break;
13815            }
13816            opti++;
13817
13818            if ("-a".equals(opt)) {
13819                // Right now we only know how to print all.
13820            } else if ("-h".equals(opt)) {
13821                pw.println("Package manager dump options:");
13822                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
13823                pw.println("    --checkin: dump for a checkin");
13824                pw.println("    -f: print details of intent filters");
13825                pw.println("    -h: print this help");
13826                pw.println("  cmd may be one of:");
13827                pw.println("    l[ibraries]: list known shared libraries");
13828                pw.println("    f[ibraries]: list device features");
13829                pw.println("    k[eysets]: print known keysets");
13830                pw.println("    r[esolvers]: dump intent resolvers");
13831                pw.println("    perm[issions]: dump permissions");
13832                pw.println("    pref[erred]: print preferred package settings");
13833                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
13834                pw.println("    prov[iders]: dump content providers");
13835                pw.println("    p[ackages]: dump installed packages");
13836                pw.println("    s[hared-users]: dump shared user IDs");
13837                pw.println("    m[essages]: print collected runtime messages");
13838                pw.println("    v[erifiers]: print package verifier info");
13839                pw.println("    version: print database version info");
13840                pw.println("    write: write current settings now");
13841                pw.println("    <package.name>: info about given package");
13842                pw.println("    installs: details about install sessions");
13843                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
13844                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
13845                return;
13846            } else if ("--checkin".equals(opt)) {
13847                checkin = true;
13848            } else if ("-f".equals(opt)) {
13849                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
13850            } else {
13851                pw.println("Unknown argument: " + opt + "; use -h for help");
13852            }
13853        }
13854
13855        // Is the caller requesting to dump a particular piece of data?
13856        if (opti < args.length) {
13857            String cmd = args[opti];
13858            opti++;
13859            // Is this a package name?
13860            if ("android".equals(cmd) || cmd.contains(".")) {
13861                packageName = cmd;
13862                // When dumping a single package, we always dump all of its
13863                // filter information since the amount of data will be reasonable.
13864                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
13865            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
13866                dumpState.setDump(DumpState.DUMP_LIBS);
13867            } else if ("f".equals(cmd) || "features".equals(cmd)) {
13868                dumpState.setDump(DumpState.DUMP_FEATURES);
13869            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
13870                dumpState.setDump(DumpState.DUMP_RESOLVERS);
13871            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
13872                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
13873            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
13874                dumpState.setDump(DumpState.DUMP_PREFERRED);
13875            } else if ("preferred-xml".equals(cmd)) {
13876                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
13877                if (opti < args.length && "--full".equals(args[opti])) {
13878                    fullPreferred = true;
13879                    opti++;
13880                }
13881            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
13882                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
13883            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
13884                dumpState.setDump(DumpState.DUMP_PACKAGES);
13885            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
13886                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
13887            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
13888                dumpState.setDump(DumpState.DUMP_PROVIDERS);
13889            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
13890                dumpState.setDump(DumpState.DUMP_MESSAGES);
13891            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
13892                dumpState.setDump(DumpState.DUMP_VERIFIERS);
13893            } else if ("i".equals(cmd) || "ifv".equals(cmd)
13894                    || "intent-filter-verifiers".equals(cmd)) {
13895                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
13896            } else if ("version".equals(cmd)) {
13897                dumpState.setDump(DumpState.DUMP_VERSION);
13898            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
13899                dumpState.setDump(DumpState.DUMP_KEYSETS);
13900            } else if ("installs".equals(cmd)) {
13901                dumpState.setDump(DumpState.DUMP_INSTALLS);
13902            } else if ("write".equals(cmd)) {
13903                synchronized (mPackages) {
13904                    mSettings.writeLPr();
13905                    pw.println("Settings written.");
13906                    return;
13907                }
13908            }
13909        }
13910
13911        if (checkin) {
13912            pw.println("vers,1");
13913        }
13914
13915        // reader
13916        synchronized (mPackages) {
13917            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
13918                if (!checkin) {
13919                    if (dumpState.onTitlePrinted())
13920                        pw.println();
13921                    pw.println("Database versions:");
13922                    pw.print("  SDK Version:");
13923                    pw.print(" internal=");
13924                    pw.print(mSettings.mInternalSdkPlatform);
13925                    pw.print(" external=");
13926                    pw.println(mSettings.mExternalSdkPlatform);
13927                    pw.print("  DB Version:");
13928                    pw.print(" internal=");
13929                    pw.print(mSettings.mInternalDatabaseVersion);
13930                    pw.print(" external=");
13931                    pw.println(mSettings.mExternalDatabaseVersion);
13932                }
13933            }
13934
13935            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
13936                if (!checkin) {
13937                    if (dumpState.onTitlePrinted())
13938                        pw.println();
13939                    pw.println("Verifiers:");
13940                    pw.print("  Required: ");
13941                    pw.print(mRequiredVerifierPackage);
13942                    pw.print(" (uid=");
13943                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
13944                    pw.println(")");
13945                } else if (mRequiredVerifierPackage != null) {
13946                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
13947                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
13948                }
13949            }
13950
13951            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
13952                    packageName == null) {
13953                if (mIntentFilterVerifierComponent != null) {
13954                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
13955                    if (!checkin) {
13956                        if (dumpState.onTitlePrinted())
13957                            pw.println();
13958                        pw.println("Intent Filter Verifier:");
13959                        pw.print("  Using: ");
13960                        pw.print(verifierPackageName);
13961                        pw.print(" (uid=");
13962                        pw.print(getPackageUid(verifierPackageName, 0));
13963                        pw.println(")");
13964                    } else if (verifierPackageName != null) {
13965                        pw.print("ifv,"); pw.print(verifierPackageName);
13966                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
13967                    }
13968                } else {
13969                    pw.println();
13970                    pw.println("No Intent Filter Verifier available!");
13971                }
13972            }
13973
13974            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
13975                boolean printedHeader = false;
13976                final Iterator<String> it = mSharedLibraries.keySet().iterator();
13977                while (it.hasNext()) {
13978                    String name = it.next();
13979                    SharedLibraryEntry ent = mSharedLibraries.get(name);
13980                    if (!checkin) {
13981                        if (!printedHeader) {
13982                            if (dumpState.onTitlePrinted())
13983                                pw.println();
13984                            pw.println("Libraries:");
13985                            printedHeader = true;
13986                        }
13987                        pw.print("  ");
13988                    } else {
13989                        pw.print("lib,");
13990                    }
13991                    pw.print(name);
13992                    if (!checkin) {
13993                        pw.print(" -> ");
13994                    }
13995                    if (ent.path != null) {
13996                        if (!checkin) {
13997                            pw.print("(jar) ");
13998                            pw.print(ent.path);
13999                        } else {
14000                            pw.print(",jar,");
14001                            pw.print(ent.path);
14002                        }
14003                    } else {
14004                        if (!checkin) {
14005                            pw.print("(apk) ");
14006                            pw.print(ent.apk);
14007                        } else {
14008                            pw.print(",apk,");
14009                            pw.print(ent.apk);
14010                        }
14011                    }
14012                    pw.println();
14013                }
14014            }
14015
14016            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14017                if (dumpState.onTitlePrinted())
14018                    pw.println();
14019                if (!checkin) {
14020                    pw.println("Features:");
14021                }
14022                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14023                while (it.hasNext()) {
14024                    String name = it.next();
14025                    if (!checkin) {
14026                        pw.print("  ");
14027                    } else {
14028                        pw.print("feat,");
14029                    }
14030                    pw.println(name);
14031                }
14032            }
14033
14034            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14035                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14036                        : "Activity Resolver Table:", "  ", packageName,
14037                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14038                    dumpState.setTitlePrinted(true);
14039                }
14040                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14041                        : "Receiver Resolver Table:", "  ", packageName,
14042                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14043                    dumpState.setTitlePrinted(true);
14044                }
14045                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14046                        : "Service Resolver Table:", "  ", packageName,
14047                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14048                    dumpState.setTitlePrinted(true);
14049                }
14050                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14051                        : "Provider Resolver Table:", "  ", packageName,
14052                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14053                    dumpState.setTitlePrinted(true);
14054                }
14055            }
14056
14057            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14058                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14059                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14060                    int user = mSettings.mPreferredActivities.keyAt(i);
14061                    if (pir.dump(pw,
14062                            dumpState.getTitlePrinted()
14063                                ? "\nPreferred Activities User " + user + ":"
14064                                : "Preferred Activities User " + user + ":", "  ",
14065                            packageName, true, false)) {
14066                        dumpState.setTitlePrinted(true);
14067                    }
14068                }
14069            }
14070
14071            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14072                pw.flush();
14073                FileOutputStream fout = new FileOutputStream(fd);
14074                BufferedOutputStream str = new BufferedOutputStream(fout);
14075                XmlSerializer serializer = new FastXmlSerializer();
14076                try {
14077                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14078                    serializer.startDocument(null, true);
14079                    serializer.setFeature(
14080                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14081                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14082                    serializer.endDocument();
14083                    serializer.flush();
14084                } catch (IllegalArgumentException e) {
14085                    pw.println("Failed writing: " + e);
14086                } catch (IllegalStateException e) {
14087                    pw.println("Failed writing: " + e);
14088                } catch (IOException e) {
14089                    pw.println("Failed writing: " + e);
14090                }
14091            }
14092
14093            if (!checkin
14094                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
14095                    && packageName == null) {
14096                pw.println();
14097                int count = mSettings.mPackages.size();
14098                if (count == 0) {
14099                    pw.println("No domain preferred apps!");
14100                    pw.println();
14101                } else {
14102                    final String prefix = "  ";
14103                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
14104                    if (allPackageSettings.size() == 0) {
14105                        pw.println("No domain preferred apps!");
14106                        pw.println();
14107                    } else {
14108                        pw.println("Domain preferred apps status:");
14109                        pw.println();
14110                        count = 0;
14111                        for (PackageSetting ps : allPackageSettings) {
14112                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14113                            if (ivi == null || ivi.getPackageName() == null) continue;
14114                            pw.println(prefix + "Package Name: " + ivi.getPackageName());
14115                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
14116                            pw.println(prefix + "Status: " + ivi.getStatusString());
14117                            pw.println();
14118                            count++;
14119                        }
14120                        if (count == 0) {
14121                            pw.println(prefix + "No domain preferred app status!");
14122                            pw.println();
14123                        }
14124                        for (int userId : sUserManager.getUserIds()) {
14125                            pw.println("Domain preferred apps for User " + userId + ":");
14126                            pw.println();
14127                            count = 0;
14128                            for (PackageSetting ps : allPackageSettings) {
14129                                IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14130                                if (ivi == null || ivi.getPackageName() == null) {
14131                                    continue;
14132                                }
14133                                final int status = ps.getDomainVerificationStatusForUser(userId);
14134                                if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
14135                                    continue;
14136                                }
14137                                pw.println(prefix + "Package Name: " + ivi.getPackageName());
14138                                pw.println(prefix + "Domains: " + ivi.getDomainsString());
14139                                String statusStr = IntentFilterVerificationInfo.
14140                                        getStatusStringFromValue(status);
14141                                pw.println(prefix + "Status: " + statusStr);
14142                                pw.println();
14143                                count++;
14144                            }
14145                            if (count == 0) {
14146                                pw.println(prefix + "No domain preferred apps!");
14147                                pw.println();
14148                            }
14149                        }
14150                    }
14151                }
14152            }
14153
14154            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
14155                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
14156                if (packageName == null) {
14157                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
14158                        if (iperm == 0) {
14159                            if (dumpState.onTitlePrinted())
14160                                pw.println();
14161                            pw.println("AppOp Permissions:");
14162                        }
14163                        pw.print("  AppOp Permission ");
14164                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
14165                        pw.println(":");
14166                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
14167                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
14168                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
14169                        }
14170                    }
14171                }
14172            }
14173
14174            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
14175                boolean printedSomething = false;
14176                for (PackageParser.Provider p : mProviders.mProviders.values()) {
14177                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14178                        continue;
14179                    }
14180                    if (!printedSomething) {
14181                        if (dumpState.onTitlePrinted())
14182                            pw.println();
14183                        pw.println("Registered ContentProviders:");
14184                        printedSomething = true;
14185                    }
14186                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
14187                    pw.print("    "); pw.println(p.toString());
14188                }
14189                printedSomething = false;
14190                for (Map.Entry<String, PackageParser.Provider> entry :
14191                        mProvidersByAuthority.entrySet()) {
14192                    PackageParser.Provider p = entry.getValue();
14193                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14194                        continue;
14195                    }
14196                    if (!printedSomething) {
14197                        if (dumpState.onTitlePrinted())
14198                            pw.println();
14199                        pw.println("ContentProvider Authorities:");
14200                        printedSomething = true;
14201                    }
14202                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
14203                    pw.print("    "); pw.println(p.toString());
14204                    if (p.info != null && p.info.applicationInfo != null) {
14205                        final String appInfo = p.info.applicationInfo.toString();
14206                        pw.print("      applicationInfo="); pw.println(appInfo);
14207                    }
14208                }
14209            }
14210
14211            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
14212                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
14213            }
14214
14215            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
14216                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
14217            }
14218
14219            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
14220                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin);
14221            }
14222
14223            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
14224                // XXX should handle packageName != null by dumping only install data that
14225                // the given package is involved with.
14226                if (dumpState.onTitlePrinted()) pw.println();
14227                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
14228            }
14229
14230            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
14231                if (dumpState.onTitlePrinted()) pw.println();
14232                mSettings.dumpReadMessagesLPr(pw, dumpState);
14233
14234                pw.println();
14235                pw.println("Package warning messages:");
14236                BufferedReader in = null;
14237                String line = null;
14238                try {
14239                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14240                    while ((line = in.readLine()) != null) {
14241                        if (line.contains("ignored: updated version")) continue;
14242                        pw.println(line);
14243                    }
14244                } catch (IOException ignored) {
14245                } finally {
14246                    IoUtils.closeQuietly(in);
14247                }
14248            }
14249
14250            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
14251                BufferedReader in = null;
14252                String line = null;
14253                try {
14254                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14255                    while ((line = in.readLine()) != null) {
14256                        if (line.contains("ignored: updated version")) continue;
14257                        pw.print("msg,");
14258                        pw.println(line);
14259                    }
14260                } catch (IOException ignored) {
14261                } finally {
14262                    IoUtils.closeQuietly(in);
14263                }
14264            }
14265        }
14266    }
14267
14268    // ------- apps on sdcard specific code -------
14269    static final boolean DEBUG_SD_INSTALL = false;
14270
14271    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
14272
14273    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
14274
14275    private boolean mMediaMounted = false;
14276
14277    static String getEncryptKey() {
14278        try {
14279            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
14280                    SD_ENCRYPTION_KEYSTORE_NAME);
14281            if (sdEncKey == null) {
14282                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
14283                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
14284                if (sdEncKey == null) {
14285                    Slog.e(TAG, "Failed to create encryption keys");
14286                    return null;
14287                }
14288            }
14289            return sdEncKey;
14290        } catch (NoSuchAlgorithmException nsae) {
14291            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
14292            return null;
14293        } catch (IOException ioe) {
14294            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
14295            return null;
14296        }
14297    }
14298
14299    /*
14300     * Update media status on PackageManager.
14301     */
14302    @Override
14303    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
14304        int callingUid = Binder.getCallingUid();
14305        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
14306            throw new SecurityException("Media status can only be updated by the system");
14307        }
14308        // reader; this apparently protects mMediaMounted, but should probably
14309        // be a different lock in that case.
14310        synchronized (mPackages) {
14311            Log.i(TAG, "Updating external media status from "
14312                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
14313                    + (mediaStatus ? "mounted" : "unmounted"));
14314            if (DEBUG_SD_INSTALL)
14315                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
14316                        + ", mMediaMounted=" + mMediaMounted);
14317            if (mediaStatus == mMediaMounted) {
14318                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
14319                        : 0, -1);
14320                mHandler.sendMessage(msg);
14321                return;
14322            }
14323            mMediaMounted = mediaStatus;
14324        }
14325        // Queue up an async operation since the package installation may take a
14326        // little while.
14327        mHandler.post(new Runnable() {
14328            public void run() {
14329                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
14330            }
14331        });
14332    }
14333
14334    /**
14335     * Called by MountService when the initial ASECs to scan are available.
14336     * Should block until all the ASEC containers are finished being scanned.
14337     */
14338    public void scanAvailableAsecs() {
14339        updateExternalMediaStatusInner(true, false, false);
14340        if (mShouldRestoreconData) {
14341            SELinuxMMAC.setRestoreconDone();
14342            mShouldRestoreconData = false;
14343        }
14344    }
14345
14346    /*
14347     * Collect information of applications on external media, map them against
14348     * existing containers and update information based on current mount status.
14349     * Please note that we always have to report status if reportStatus has been
14350     * set to true especially when unloading packages.
14351     */
14352    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
14353            boolean externalStorage) {
14354        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
14355        int[] uidArr = EmptyArray.INT;
14356
14357        final String[] list = PackageHelper.getSecureContainerList();
14358        if (ArrayUtils.isEmpty(list)) {
14359            Log.i(TAG, "No secure containers found");
14360        } else {
14361            // Process list of secure containers and categorize them
14362            // as active or stale based on their package internal state.
14363
14364            // reader
14365            synchronized (mPackages) {
14366                for (String cid : list) {
14367                    // Leave stages untouched for now; installer service owns them
14368                    if (PackageInstallerService.isStageName(cid)) continue;
14369
14370                    if (DEBUG_SD_INSTALL)
14371                        Log.i(TAG, "Processing container " + cid);
14372                    String pkgName = getAsecPackageName(cid);
14373                    if (pkgName == null) {
14374                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
14375                        continue;
14376                    }
14377                    if (DEBUG_SD_INSTALL)
14378                        Log.i(TAG, "Looking for pkg : " + pkgName);
14379
14380                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
14381                    if (ps == null) {
14382                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
14383                        continue;
14384                    }
14385
14386                    /*
14387                     * Skip packages that are not external if we're unmounting
14388                     * external storage.
14389                     */
14390                    if (externalStorage && !isMounted && !isExternal(ps)) {
14391                        continue;
14392                    }
14393
14394                    final AsecInstallArgs args = new AsecInstallArgs(cid,
14395                            getAppDexInstructionSets(ps), ps.isForwardLocked());
14396                    // The package status is changed only if the code path
14397                    // matches between settings and the container id.
14398                    if (ps.codePathString != null
14399                            && ps.codePathString.startsWith(args.getCodePath())) {
14400                        if (DEBUG_SD_INSTALL) {
14401                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
14402                                    + " at code path: " + ps.codePathString);
14403                        }
14404
14405                        // We do have a valid package installed on sdcard
14406                        processCids.put(args, ps.codePathString);
14407                        final int uid = ps.appId;
14408                        if (uid != -1) {
14409                            uidArr = ArrayUtils.appendInt(uidArr, uid);
14410                        }
14411                    } else {
14412                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
14413                                + ps.codePathString);
14414                    }
14415                }
14416            }
14417
14418            Arrays.sort(uidArr);
14419        }
14420
14421        // Process packages with valid entries.
14422        if (isMounted) {
14423            if (DEBUG_SD_INSTALL)
14424                Log.i(TAG, "Loading packages");
14425            loadMediaPackages(processCids, uidArr);
14426            startCleaningPackages();
14427            mInstallerService.onSecureContainersAvailable();
14428        } else {
14429            if (DEBUG_SD_INSTALL)
14430                Log.i(TAG, "Unloading packages");
14431            unloadMediaPackages(processCids, uidArr, reportStatus);
14432        }
14433    }
14434
14435    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14436            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
14437        final int size = infos.size();
14438        final String[] packageNames = new String[size];
14439        final int[] packageUids = new int[size];
14440        for (int i = 0; i < size; i++) {
14441            final ApplicationInfo info = infos.get(i);
14442            packageNames[i] = info.packageName;
14443            packageUids[i] = info.uid;
14444        }
14445        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
14446                finishedReceiver);
14447    }
14448
14449    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14450            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14451        sendResourcesChangedBroadcast(mediaStatus, replacing,
14452                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
14453    }
14454
14455    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14456            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14457        int size = pkgList.length;
14458        if (size > 0) {
14459            // Send broadcasts here
14460            Bundle extras = new Bundle();
14461            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14462            if (uidArr != null) {
14463                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
14464            }
14465            if (replacing) {
14466                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
14467            }
14468            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
14469                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
14470            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
14471        }
14472    }
14473
14474   /*
14475     * Look at potentially valid container ids from processCids If package
14476     * information doesn't match the one on record or package scanning fails,
14477     * the cid is added to list of removeCids. We currently don't delete stale
14478     * containers.
14479     */
14480    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
14481        ArrayList<String> pkgList = new ArrayList<String>();
14482        Set<AsecInstallArgs> keys = processCids.keySet();
14483
14484        for (AsecInstallArgs args : keys) {
14485            String codePath = processCids.get(args);
14486            if (DEBUG_SD_INSTALL)
14487                Log.i(TAG, "Loading container : " + args.cid);
14488            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14489            try {
14490                // Make sure there are no container errors first.
14491                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
14492                    Slog.e(TAG, "Failed to mount cid : " + args.cid
14493                            + " when installing from sdcard");
14494                    continue;
14495                }
14496                // Check code path here.
14497                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
14498                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
14499                            + " does not match one in settings " + codePath);
14500                    continue;
14501                }
14502                // Parse package
14503                int parseFlags = mDefParseFlags;
14504                if (args.isExternalAsec()) {
14505                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
14506                }
14507                if (args.isFwdLocked()) {
14508                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
14509                }
14510
14511                synchronized (mInstallLock) {
14512                    PackageParser.Package pkg = null;
14513                    try {
14514                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
14515                    } catch (PackageManagerException e) {
14516                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
14517                    }
14518                    // Scan the package
14519                    if (pkg != null) {
14520                        /*
14521                         * TODO why is the lock being held? doPostInstall is
14522                         * called in other places without the lock. This needs
14523                         * to be straightened out.
14524                         */
14525                        // writer
14526                        synchronized (mPackages) {
14527                            retCode = PackageManager.INSTALL_SUCCEEDED;
14528                            pkgList.add(pkg.packageName);
14529                            // Post process args
14530                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
14531                                    pkg.applicationInfo.uid);
14532                        }
14533                    } else {
14534                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
14535                    }
14536                }
14537
14538            } finally {
14539                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
14540                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
14541                }
14542            }
14543        }
14544        // writer
14545        synchronized (mPackages) {
14546            // If the platform SDK has changed since the last time we booted,
14547            // we need to re-grant app permission to catch any new ones that
14548            // appear. This is really a hack, and means that apps can in some
14549            // cases get permissions that the user didn't initially explicitly
14550            // allow... it would be nice to have some better way to handle
14551            // this situation.
14552            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
14553            if (regrantPermissions)
14554                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
14555                        + mSdkVersion + "; regranting permissions for external storage");
14556            mSettings.mExternalSdkPlatform = mSdkVersion;
14557
14558            // Make sure group IDs have been assigned, and any permission
14559            // changes in other apps are accounted for
14560            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
14561                    | (regrantPermissions
14562                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
14563                            : 0));
14564
14565            mSettings.updateExternalDatabaseVersion();
14566
14567            // can downgrade to reader
14568            // Persist settings
14569            mSettings.writeLPr();
14570        }
14571        // Send a broadcast to let everyone know we are done processing
14572        if (pkgList.size() > 0) {
14573            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
14574        }
14575    }
14576
14577   /*
14578     * Utility method to unload a list of specified containers
14579     */
14580    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
14581        // Just unmount all valid containers.
14582        for (AsecInstallArgs arg : cidArgs) {
14583            synchronized (mInstallLock) {
14584                arg.doPostDeleteLI(false);
14585           }
14586       }
14587   }
14588
14589    /*
14590     * Unload packages mounted on external media. This involves deleting package
14591     * data from internal structures, sending broadcasts about diabled packages,
14592     * gc'ing to free up references, unmounting all secure containers
14593     * corresponding to packages on external media, and posting a
14594     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
14595     * that we always have to post this message if status has been requested no
14596     * matter what.
14597     */
14598    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
14599            final boolean reportStatus) {
14600        if (DEBUG_SD_INSTALL)
14601            Log.i(TAG, "unloading media packages");
14602        ArrayList<String> pkgList = new ArrayList<String>();
14603        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
14604        final Set<AsecInstallArgs> keys = processCids.keySet();
14605        for (AsecInstallArgs args : keys) {
14606            String pkgName = args.getPackageName();
14607            if (DEBUG_SD_INSTALL)
14608                Log.i(TAG, "Trying to unload pkg : " + pkgName);
14609            // Delete package internally
14610            PackageRemovedInfo outInfo = new PackageRemovedInfo();
14611            synchronized (mInstallLock) {
14612                boolean res = deletePackageLI(pkgName, null, false, null, null,
14613                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
14614                if (res) {
14615                    pkgList.add(pkgName);
14616                } else {
14617                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
14618                    failedList.add(args);
14619                }
14620            }
14621        }
14622
14623        // reader
14624        synchronized (mPackages) {
14625            // We didn't update the settings after removing each package;
14626            // write them now for all packages.
14627            mSettings.writeLPr();
14628        }
14629
14630        // We have to absolutely send UPDATED_MEDIA_STATUS only
14631        // after confirming that all the receivers processed the ordered
14632        // broadcast when packages get disabled, force a gc to clean things up.
14633        // and unload all the containers.
14634        if (pkgList.size() > 0) {
14635            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
14636                    new IIntentReceiver.Stub() {
14637                public void performReceive(Intent intent, int resultCode, String data,
14638                        Bundle extras, boolean ordered, boolean sticky,
14639                        int sendingUser) throws RemoteException {
14640                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
14641                            reportStatus ? 1 : 0, 1, keys);
14642                    mHandler.sendMessage(msg);
14643                }
14644            });
14645        } else {
14646            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
14647                    keys);
14648            mHandler.sendMessage(msg);
14649        }
14650    }
14651
14652    private void loadPrivatePackages(VolumeInfo vol) {
14653        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
14654        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
14655        synchronized (mInstallLock) {
14656        synchronized (mPackages) {
14657            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14658            for (PackageSetting ps : packages) {
14659                final PackageParser.Package pkg;
14660                try {
14661                    pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null);
14662                    loaded.add(pkg.applicationInfo);
14663                } catch (PackageManagerException e) {
14664                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
14665                }
14666            }
14667
14668            // TODO: regrant any permissions that changed based since original install
14669
14670            mSettings.writeLPr();
14671        }
14672        }
14673
14674        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
14675        sendResourcesChangedBroadcast(true, false, loaded, null);
14676    }
14677
14678    private void unloadPrivatePackages(VolumeInfo vol) {
14679        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
14680        synchronized (mInstallLock) {
14681        synchronized (mPackages) {
14682            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14683            for (PackageSetting ps : packages) {
14684                if (ps.pkg == null) continue;
14685
14686                final ApplicationInfo info = ps.pkg.applicationInfo;
14687                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
14688                if (deletePackageLI(ps.name, null, false, null, null,
14689                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
14690                    unloaded.add(info);
14691                } else {
14692                    Slog.w(TAG, "Failed to unload " + ps.codePath);
14693                }
14694            }
14695
14696            mSettings.writeLPr();
14697        }
14698        }
14699
14700        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
14701        sendResourcesChangedBroadcast(false, false, unloaded, null);
14702    }
14703
14704    private void unfreezePackage(String packageName) {
14705        synchronized (mPackages) {
14706            final PackageSetting ps = mSettings.mPackages.get(packageName);
14707            if (ps != null) {
14708                ps.frozen = false;
14709            }
14710        }
14711    }
14712
14713    @Override
14714    public int movePackage(final String packageName, final String volumeUuid) {
14715        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
14716
14717        final int moveId = mNextMoveId.getAndIncrement();
14718        try {
14719            movePackageInternal(packageName, volumeUuid, moveId);
14720        } catch (PackageManagerException e) {
14721            Slog.w(TAG, "Failed to move " + packageName, e);
14722            mMoveCallbacks.notifyStatusChanged(moveId,
14723                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
14724        }
14725        return moveId;
14726    }
14727
14728    private void movePackageInternal(final String packageName, final String volumeUuid,
14729            final int moveId) throws PackageManagerException {
14730        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
14731        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14732        final PackageManager pm = mContext.getPackageManager();
14733
14734        final boolean currentAsec;
14735        final String currentVolumeUuid;
14736        final File codeFile;
14737        final String installerPackageName;
14738        final String packageAbiOverride;
14739        final int appId;
14740        final String seinfo;
14741        final String label;
14742
14743        // reader
14744        synchronized (mPackages) {
14745            final PackageParser.Package pkg = mPackages.get(packageName);
14746            final PackageSetting ps = mSettings.mPackages.get(packageName);
14747            if (pkg == null || ps == null) {
14748                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
14749            }
14750
14751            if (pkg.applicationInfo.isSystemApp()) {
14752                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
14753                        "Cannot move system application");
14754            }
14755
14756            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
14757                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14758                        "Package already moved to " + volumeUuid);
14759            }
14760
14761            final File probe = new File(pkg.codePath);
14762            final File probeOat = new File(probe, "oat");
14763            if (!probe.isDirectory() || !probeOat.isDirectory()) {
14764                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14765                        "Move only supported for modern cluster style installs");
14766            }
14767
14768            if (ps.frozen) {
14769                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
14770                        "Failed to move already frozen package");
14771            }
14772            ps.frozen = true;
14773
14774            currentAsec = pkg.applicationInfo.isForwardLocked()
14775                    || pkg.applicationInfo.isExternalAsec();
14776            currentVolumeUuid = ps.volumeUuid;
14777            codeFile = new File(pkg.codePath);
14778            installerPackageName = ps.installerPackageName;
14779            packageAbiOverride = ps.cpuAbiOverrideString;
14780            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
14781            seinfo = pkg.applicationInfo.seinfo;
14782            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
14783        }
14784
14785        // Now that we're guarded by frozen state, kill app during move
14786        killApplication(packageName, appId, "move pkg");
14787
14788        final Bundle extras = new Bundle();
14789        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
14790        extras.putString(Intent.EXTRA_TITLE, label);
14791        mMoveCallbacks.notifyCreated(moveId, extras);
14792
14793        int installFlags;
14794        final boolean moveCompleteApp;
14795        final File measurePath;
14796
14797        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
14798            installFlags = INSTALL_INTERNAL;
14799            moveCompleteApp = !currentAsec;
14800            measurePath = Environment.getDataAppDirectory(volumeUuid);
14801        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
14802            installFlags = INSTALL_EXTERNAL;
14803            moveCompleteApp = false;
14804            measurePath = storage.getPrimaryPhysicalVolume().getPath();
14805        } else {
14806            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
14807            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
14808                    || !volume.isMountedWritable()) {
14809                unfreezePackage(packageName);
14810                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14811                        "Move location not mounted private volume");
14812            }
14813
14814            Preconditions.checkState(!currentAsec);
14815
14816            installFlags = INSTALL_INTERNAL;
14817            moveCompleteApp = true;
14818            measurePath = Environment.getDataAppDirectory(volumeUuid);
14819        }
14820
14821        final PackageStats stats = new PackageStats(null, -1);
14822        synchronized (mInstaller) {
14823            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
14824                unfreezePackage(packageName);
14825                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14826                        "Failed to measure package size");
14827            }
14828        }
14829
14830        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
14831                + stats.dataSize);
14832
14833        final long startFreeBytes = measurePath.getFreeSpace();
14834        final long sizeBytes;
14835        if (moveCompleteApp) {
14836            sizeBytes = stats.codeSize + stats.dataSize;
14837        } else {
14838            sizeBytes = stats.codeSize;
14839        }
14840
14841        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
14842            unfreezePackage(packageName);
14843            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14844                    "Not enough free space to move");
14845        }
14846
14847        mMoveCallbacks.notifyStatusChanged(moveId, 10);
14848
14849        final CountDownLatch installedLatch = new CountDownLatch(1);
14850        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
14851            @Override
14852            public void onUserActionRequired(Intent intent) throws RemoteException {
14853                throw new IllegalStateException();
14854            }
14855
14856            @Override
14857            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
14858                    Bundle extras) throws RemoteException {
14859                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
14860                        + PackageManager.installStatusToString(returnCode, msg));
14861
14862                installedLatch.countDown();
14863
14864                // Regardless of success or failure of the move operation,
14865                // always unfreeze the package
14866                unfreezePackage(packageName);
14867
14868                final int status = PackageManager.installStatusToPublicStatus(returnCode);
14869                switch (status) {
14870                    case PackageInstaller.STATUS_SUCCESS:
14871                        mMoveCallbacks.notifyStatusChanged(moveId,
14872                                PackageManager.MOVE_SUCCEEDED);
14873                        break;
14874                    case PackageInstaller.STATUS_FAILURE_STORAGE:
14875                        mMoveCallbacks.notifyStatusChanged(moveId,
14876                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
14877                        break;
14878                    default:
14879                        mMoveCallbacks.notifyStatusChanged(moveId,
14880                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
14881                        break;
14882                }
14883            }
14884        };
14885
14886        final MoveInfo move;
14887        if (moveCompleteApp) {
14888            // Kick off a thread to report progress estimates
14889            new Thread() {
14890                @Override
14891                public void run() {
14892                    while (true) {
14893                        try {
14894                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
14895                                break;
14896                            }
14897                        } catch (InterruptedException ignored) {
14898                        }
14899
14900                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
14901                        final int progress = 10 + (int) MathUtils.constrain(
14902                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
14903                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
14904                    }
14905                }
14906            }.start();
14907
14908            final String dataAppName = codeFile.getName();
14909            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
14910                    dataAppName, appId, seinfo);
14911        } else {
14912            move = null;
14913        }
14914
14915        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
14916
14917        final Message msg = mHandler.obtainMessage(INIT_COPY);
14918        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
14919        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
14920                installerPackageName, volumeUuid, null, user, packageAbiOverride);
14921        mHandler.sendMessage(msg);
14922    }
14923
14924    @Override
14925    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
14926        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
14927
14928        final int realMoveId = mNextMoveId.getAndIncrement();
14929        final Bundle extras = new Bundle();
14930        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
14931        mMoveCallbacks.notifyCreated(realMoveId, extras);
14932
14933        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
14934            @Override
14935            public void onCreated(int moveId, Bundle extras) {
14936                // Ignored
14937            }
14938
14939            @Override
14940            public void onStatusChanged(int moveId, int status, long estMillis) {
14941                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
14942            }
14943        };
14944
14945        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14946        storage.setPrimaryStorageUuid(volumeUuid, callback);
14947        return realMoveId;
14948    }
14949
14950    @Override
14951    public int getMoveStatus(int moveId) {
14952        mContext.enforceCallingOrSelfPermission(
14953                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
14954        return mMoveCallbacks.mLastStatus.get(moveId);
14955    }
14956
14957    @Override
14958    public void registerMoveCallback(IPackageMoveObserver callback) {
14959        mContext.enforceCallingOrSelfPermission(
14960                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
14961        mMoveCallbacks.register(callback);
14962    }
14963
14964    @Override
14965    public void unregisterMoveCallback(IPackageMoveObserver callback) {
14966        mContext.enforceCallingOrSelfPermission(
14967                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
14968        mMoveCallbacks.unregister(callback);
14969    }
14970
14971    @Override
14972    public boolean setInstallLocation(int loc) {
14973        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
14974                null);
14975        if (getInstallLocation() == loc) {
14976            return true;
14977        }
14978        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
14979                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
14980            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
14981                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
14982            return true;
14983        }
14984        return false;
14985   }
14986
14987    @Override
14988    public int getInstallLocation() {
14989        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14990                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
14991                PackageHelper.APP_INSTALL_AUTO);
14992    }
14993
14994    /** Called by UserManagerService */
14995    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
14996        mDirtyUsers.remove(userHandle);
14997        mSettings.removeUserLPw(userHandle);
14998        mPendingBroadcasts.remove(userHandle);
14999        if (mInstaller != null) {
15000            // Technically, we shouldn't be doing this with the package lock
15001            // held.  However, this is very rare, and there is already so much
15002            // other disk I/O going on, that we'll let it slide for now.
15003            final StorageManager storage = StorageManager.from(mContext);
15004            final List<VolumeInfo> vols = storage.getVolumes();
15005            for (VolumeInfo vol : vols) {
15006                if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) {
15007                    final String volumeUuid = vol.getFsUuid();
15008                    if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
15009                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
15010                }
15011            }
15012        }
15013        mUserNeedsBadging.delete(userHandle);
15014        removeUnusedPackagesLILPw(userManager, userHandle);
15015    }
15016
15017    /**
15018     * We're removing userHandle and would like to remove any downloaded packages
15019     * that are no longer in use by any other user.
15020     * @param userHandle the user being removed
15021     */
15022    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
15023        final boolean DEBUG_CLEAN_APKS = false;
15024        int [] users = userManager.getUserIdsLPr();
15025        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
15026        while (psit.hasNext()) {
15027            PackageSetting ps = psit.next();
15028            if (ps.pkg == null) {
15029                continue;
15030            }
15031            final String packageName = ps.pkg.packageName;
15032            // Skip over if system app
15033            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15034                continue;
15035            }
15036            if (DEBUG_CLEAN_APKS) {
15037                Slog.i(TAG, "Checking package " + packageName);
15038            }
15039            boolean keep = false;
15040            for (int i = 0; i < users.length; i++) {
15041                if (users[i] != userHandle && ps.getInstalled(users[i])) {
15042                    keep = true;
15043                    if (DEBUG_CLEAN_APKS) {
15044                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
15045                                + users[i]);
15046                    }
15047                    break;
15048                }
15049            }
15050            if (!keep) {
15051                if (DEBUG_CLEAN_APKS) {
15052                    Slog.i(TAG, "  Removing package " + packageName);
15053                }
15054                mHandler.post(new Runnable() {
15055                    public void run() {
15056                        deletePackageX(packageName, userHandle, 0);
15057                    } //end run
15058                });
15059            }
15060        }
15061    }
15062
15063    /** Called by UserManagerService */
15064    void createNewUserLILPw(int userHandle, File path) {
15065        if (mInstaller != null) {
15066            mInstaller.createUserConfig(userHandle);
15067            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
15068        }
15069    }
15070
15071    void newUserCreatedLILPw(int userHandle) {
15072        // Adding a user requires updating runtime permissions for system apps.
15073        updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
15074    }
15075
15076    @Override
15077    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
15078        mContext.enforceCallingOrSelfPermission(
15079                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15080                "Only package verification agents can read the verifier device identity");
15081
15082        synchronized (mPackages) {
15083            return mSettings.getVerifierDeviceIdentityLPw();
15084        }
15085    }
15086
15087    @Override
15088    public void setPermissionEnforced(String permission, boolean enforced) {
15089        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
15090        if (READ_EXTERNAL_STORAGE.equals(permission)) {
15091            synchronized (mPackages) {
15092                if (mSettings.mReadExternalStorageEnforced == null
15093                        || mSettings.mReadExternalStorageEnforced != enforced) {
15094                    mSettings.mReadExternalStorageEnforced = enforced;
15095                    mSettings.writeLPr();
15096                }
15097            }
15098            // kill any non-foreground processes so we restart them and
15099            // grant/revoke the GID.
15100            final IActivityManager am = ActivityManagerNative.getDefault();
15101            if (am != null) {
15102                final long token = Binder.clearCallingIdentity();
15103                try {
15104                    am.killProcessesBelowForeground("setPermissionEnforcement");
15105                } catch (RemoteException e) {
15106                } finally {
15107                    Binder.restoreCallingIdentity(token);
15108                }
15109            }
15110        } else {
15111            throw new IllegalArgumentException("No selective enforcement for " + permission);
15112        }
15113    }
15114
15115    @Override
15116    @Deprecated
15117    public boolean isPermissionEnforced(String permission) {
15118        return true;
15119    }
15120
15121    @Override
15122    public boolean isStorageLow() {
15123        final long token = Binder.clearCallingIdentity();
15124        try {
15125            final DeviceStorageMonitorInternal
15126                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
15127            if (dsm != null) {
15128                return dsm.isMemoryLow();
15129            } else {
15130                return false;
15131            }
15132        } finally {
15133            Binder.restoreCallingIdentity(token);
15134        }
15135    }
15136
15137    @Override
15138    public IPackageInstaller getPackageInstaller() {
15139        return mInstallerService;
15140    }
15141
15142    private boolean userNeedsBadging(int userId) {
15143        int index = mUserNeedsBadging.indexOfKey(userId);
15144        if (index < 0) {
15145            final UserInfo userInfo;
15146            final long token = Binder.clearCallingIdentity();
15147            try {
15148                userInfo = sUserManager.getUserInfo(userId);
15149            } finally {
15150                Binder.restoreCallingIdentity(token);
15151            }
15152            final boolean b;
15153            if (userInfo != null && userInfo.isManagedProfile()) {
15154                b = true;
15155            } else {
15156                b = false;
15157            }
15158            mUserNeedsBadging.put(userId, b);
15159            return b;
15160        }
15161        return mUserNeedsBadging.valueAt(index);
15162    }
15163
15164    @Override
15165    public KeySet getKeySetByAlias(String packageName, String alias) {
15166        if (packageName == null || alias == null) {
15167            return null;
15168        }
15169        synchronized(mPackages) {
15170            final PackageParser.Package pkg = mPackages.get(packageName);
15171            if (pkg == null) {
15172                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15173                throw new IllegalArgumentException("Unknown package: " + packageName);
15174            }
15175            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15176            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
15177        }
15178    }
15179
15180    @Override
15181    public KeySet getSigningKeySet(String packageName) {
15182        if (packageName == null) {
15183            return null;
15184        }
15185        synchronized(mPackages) {
15186            final PackageParser.Package pkg = mPackages.get(packageName);
15187            if (pkg == null) {
15188                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15189                throw new IllegalArgumentException("Unknown package: " + packageName);
15190            }
15191            if (pkg.applicationInfo.uid != Binder.getCallingUid()
15192                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
15193                throw new SecurityException("May not access signing KeySet of other apps.");
15194            }
15195            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15196            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
15197        }
15198    }
15199
15200    @Override
15201    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
15202        if (packageName == null || ks == null) {
15203            return false;
15204        }
15205        synchronized(mPackages) {
15206            final PackageParser.Package pkg = mPackages.get(packageName);
15207            if (pkg == null) {
15208                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15209                throw new IllegalArgumentException("Unknown package: " + packageName);
15210            }
15211            IBinder ksh = ks.getToken();
15212            if (ksh instanceof KeySetHandle) {
15213                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15214                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
15215            }
15216            return false;
15217        }
15218    }
15219
15220    @Override
15221    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
15222        if (packageName == null || ks == null) {
15223            return false;
15224        }
15225        synchronized(mPackages) {
15226            final PackageParser.Package pkg = mPackages.get(packageName);
15227            if (pkg == null) {
15228                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15229                throw new IllegalArgumentException("Unknown package: " + packageName);
15230            }
15231            IBinder ksh = ks.getToken();
15232            if (ksh instanceof KeySetHandle) {
15233                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15234                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
15235            }
15236            return false;
15237        }
15238    }
15239
15240    public void getUsageStatsIfNoPackageUsageInfo() {
15241        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
15242            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
15243            if (usm == null) {
15244                throw new IllegalStateException("UsageStatsManager must be initialized");
15245            }
15246            long now = System.currentTimeMillis();
15247            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
15248            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
15249                String packageName = entry.getKey();
15250                PackageParser.Package pkg = mPackages.get(packageName);
15251                if (pkg == null) {
15252                    continue;
15253                }
15254                UsageStats usage = entry.getValue();
15255                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
15256                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
15257            }
15258        }
15259    }
15260
15261    /**
15262     * Check and throw if the given before/after packages would be considered a
15263     * downgrade.
15264     */
15265    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
15266            throws PackageManagerException {
15267        if (after.versionCode < before.mVersionCode) {
15268            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15269                    "Update version code " + after.versionCode + " is older than current "
15270                    + before.mVersionCode);
15271        } else if (after.versionCode == before.mVersionCode) {
15272            if (after.baseRevisionCode < before.baseRevisionCode) {
15273                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15274                        "Update base revision code " + after.baseRevisionCode
15275                        + " is older than current " + before.baseRevisionCode);
15276            }
15277
15278            if (!ArrayUtils.isEmpty(after.splitNames)) {
15279                for (int i = 0; i < after.splitNames.length; i++) {
15280                    final String splitName = after.splitNames[i];
15281                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
15282                    if (j != -1) {
15283                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
15284                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15285                                    "Update split " + splitName + " revision code "
15286                                    + after.splitRevisionCodes[i] + " is older than current "
15287                                    + before.splitRevisionCodes[j]);
15288                        }
15289                    }
15290                }
15291            }
15292        }
15293    }
15294
15295    private static class MoveCallbacks extends Handler {
15296        private static final int MSG_CREATED = 1;
15297        private static final int MSG_STATUS_CHANGED = 2;
15298
15299        private final RemoteCallbackList<IPackageMoveObserver>
15300                mCallbacks = new RemoteCallbackList<>();
15301
15302        private final SparseIntArray mLastStatus = new SparseIntArray();
15303
15304        public MoveCallbacks(Looper looper) {
15305            super(looper);
15306        }
15307
15308        public void register(IPackageMoveObserver callback) {
15309            mCallbacks.register(callback);
15310        }
15311
15312        public void unregister(IPackageMoveObserver callback) {
15313            mCallbacks.unregister(callback);
15314        }
15315
15316        @Override
15317        public void handleMessage(Message msg) {
15318            final SomeArgs args = (SomeArgs) msg.obj;
15319            final int n = mCallbacks.beginBroadcast();
15320            for (int i = 0; i < n; i++) {
15321                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
15322                try {
15323                    invokeCallback(callback, msg.what, args);
15324                } catch (RemoteException ignored) {
15325                }
15326            }
15327            mCallbacks.finishBroadcast();
15328            args.recycle();
15329        }
15330
15331        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
15332                throws RemoteException {
15333            switch (what) {
15334                case MSG_CREATED: {
15335                    callback.onCreated(args.argi1, (Bundle) args.arg2);
15336                    break;
15337                }
15338                case MSG_STATUS_CHANGED: {
15339                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
15340                    break;
15341                }
15342            }
15343        }
15344
15345        private void notifyCreated(int moveId, Bundle extras) {
15346            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
15347
15348            final SomeArgs args = SomeArgs.obtain();
15349            args.argi1 = moveId;
15350            args.arg2 = extras;
15351            obtainMessage(MSG_CREATED, args).sendToTarget();
15352        }
15353
15354        private void notifyStatusChanged(int moveId, int status) {
15355            notifyStatusChanged(moveId, status, -1);
15356        }
15357
15358        private void notifyStatusChanged(int moveId, int status, long estMillis) {
15359            Slog.v(TAG, "Move " + moveId + " status " + status);
15360
15361            final SomeArgs args = SomeArgs.obtain();
15362            args.argi1 = moveId;
15363            args.argi2 = status;
15364            args.arg3 = estMillis;
15365            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
15366
15367            synchronized (mLastStatus) {
15368                mLastStatus.put(moveId, status);
15369            }
15370        }
15371    }
15372
15373    private final class OnPermissionChangeListeners extends Handler {
15374        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
15375
15376        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
15377                new RemoteCallbackList<>();
15378
15379        public OnPermissionChangeListeners(Looper looper) {
15380            super(looper);
15381        }
15382
15383        @Override
15384        public void handleMessage(Message msg) {
15385            switch (msg.what) {
15386                case MSG_ON_PERMISSIONS_CHANGED: {
15387                    final int uid = msg.arg1;
15388                    handleOnPermissionsChanged(uid);
15389                } break;
15390            }
15391        }
15392
15393        public void addListenerLocked(IOnPermissionsChangeListener listener) {
15394            mPermissionListeners.register(listener);
15395
15396        }
15397
15398        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
15399            mPermissionListeners.unregister(listener);
15400        }
15401
15402        public void onPermissionsChanged(int uid) {
15403            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
15404                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
15405            }
15406        }
15407
15408        private void handleOnPermissionsChanged(int uid) {
15409            final int count = mPermissionListeners.beginBroadcast();
15410            try {
15411                for (int i = 0; i < count; i++) {
15412                    IOnPermissionsChangeListener callback = mPermissionListeners
15413                            .getBroadcastItem(i);
15414                    try {
15415                        callback.onPermissionsChanged(uid);
15416                    } catch (RemoteException e) {
15417                        Log.e(TAG, "Permission listener is dead", e);
15418                    }
15419                }
15420            } finally {
15421                mPermissionListeners.finishBroadcast();
15422            }
15423        }
15424    }
15425}
15426