PackageManagerService.java revision 6d9a53abbc94788dc02f7ebde30744753e0a5a3d
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.IPackageDataObserver;
96import android.content.pm.IPackageDeleteObserver;
97import android.content.pm.IPackageDeleteObserver2;
98import android.content.pm.IPackageInstallObserver2;
99import android.content.pm.IPackageInstaller;
100import android.content.pm.IPackageManager;
101import android.content.pm.IPackageMoveObserver;
102import android.content.pm.IPackageStatsObserver;
103import android.content.pm.InstrumentationInfo;
104import android.content.pm.IntentFilterVerificationInfo;
105import android.content.pm.KeySet;
106import android.content.pm.ManifestDigest;
107import android.content.pm.PackageCleanItem;
108import android.content.pm.PackageInfo;
109import android.content.pm.PackageInfoLite;
110import android.content.pm.PackageInstaller;
111import android.content.pm.PackageManager;
112import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
113import android.content.pm.PackageParser;
114import android.content.pm.PackageParser.ActivityIntentInfo;
115import android.content.pm.PackageParser.PackageLite;
116import android.content.pm.PackageParser.PackageParserException;
117import android.content.pm.PackageStats;
118import android.content.pm.PackageUserState;
119import android.content.pm.ParceledListSlice;
120import android.content.pm.PermissionGroupInfo;
121import android.content.pm.PermissionInfo;
122import android.content.pm.ProviderInfo;
123import android.content.pm.ResolveInfo;
124import android.content.pm.ServiceInfo;
125import android.content.pm.Signature;
126import android.content.pm.UserInfo;
127import android.content.pm.VerificationParams;
128import android.content.pm.VerifierDeviceIdentity;
129import android.content.pm.VerifierInfo;
130import android.content.res.Resources;
131import android.hardware.display.DisplayManager;
132import android.net.Uri;
133import android.os.Binder;
134import android.os.Build;
135import android.os.Bundle;
136import android.os.Debug;
137import android.os.Environment;
138import android.os.Environment.UserEnvironment;
139import android.os.FileUtils;
140import android.os.Handler;
141import android.os.IBinder;
142import android.os.Looper;
143import android.os.Message;
144import android.os.Parcel;
145import android.os.ParcelFileDescriptor;
146import android.os.Process;
147import android.os.RemoteCallbackList;
148import android.os.RemoteException;
149import android.os.SELinux;
150import android.os.ServiceManager;
151import android.os.SystemClock;
152import android.os.SystemProperties;
153import android.os.UserHandle;
154import android.os.UserManager;
155import android.os.storage.IMountService;
156import android.os.storage.StorageEventListener;
157import android.os.storage.StorageManager;
158import android.os.storage.VolumeInfo;
159import android.os.storage.VolumeRecord;
160import android.security.KeyStore;
161import android.security.SystemKeyStore;
162import android.system.ErrnoException;
163import android.system.Os;
164import android.system.StructStat;
165import android.text.TextUtils;
166import android.text.format.DateUtils;
167import android.util.ArrayMap;
168import android.util.ArraySet;
169import android.util.AtomicFile;
170import android.util.DisplayMetrics;
171import android.util.EventLog;
172import android.util.ExceptionUtils;
173import android.util.Log;
174import android.util.LogPrinter;
175import android.util.MathUtils;
176import android.util.PrintStreamPrinter;
177import android.util.Slog;
178import android.util.SparseArray;
179import android.util.SparseBooleanArray;
180import android.util.SparseIntArray;
181import android.util.Xml;
182import android.view.Display;
183
184import dalvik.system.DexFile;
185import dalvik.system.VMRuntime;
186
187import libcore.io.IoUtils;
188import libcore.util.EmptyArray;
189
190import com.android.internal.R;
191import com.android.internal.app.IMediaContainerService;
192import com.android.internal.app.ResolverActivity;
193import com.android.internal.content.NativeLibraryHelper;
194import com.android.internal.content.PackageHelper;
195import com.android.internal.os.IParcelFileDescriptorFactory;
196import com.android.internal.os.SomeArgs;
197import com.android.internal.util.ArrayUtils;
198import com.android.internal.util.FastPrintWriter;
199import com.android.internal.util.FastXmlSerializer;
200import com.android.internal.util.IndentingPrintWriter;
201import com.android.internal.util.Preconditions;
202import com.android.server.EventLogTags;
203import com.android.server.FgThread;
204import com.android.server.IntentResolver;
205import com.android.server.LocalServices;
206import com.android.server.ServiceThread;
207import com.android.server.SystemConfig;
208import com.android.server.Watchdog;
209import com.android.server.pm.Settings.DatabaseVersion;
210import com.android.server.pm.PermissionsState.PermissionState;
211import com.android.server.storage.DeviceStorageMonitorInternal;
212
213import org.xmlpull.v1.XmlPullParser;
214import org.xmlpull.v1.XmlSerializer;
215
216import java.io.BufferedInputStream;
217import java.io.BufferedOutputStream;
218import java.io.BufferedReader;
219import java.io.ByteArrayInputStream;
220import java.io.ByteArrayOutputStream;
221import java.io.File;
222import java.io.FileDescriptor;
223import java.io.FileNotFoundException;
224import java.io.FileOutputStream;
225import java.io.FileReader;
226import java.io.FilenameFilter;
227import java.io.IOException;
228import java.io.InputStream;
229import java.io.PrintWriter;
230import java.nio.charset.StandardCharsets;
231import java.security.NoSuchAlgorithmException;
232import java.security.PublicKey;
233import java.security.cert.CertificateEncodingException;
234import java.security.cert.CertificateException;
235import java.text.SimpleDateFormat;
236import java.util.ArrayList;
237import java.util.Arrays;
238import java.util.Collection;
239import java.util.Collections;
240import java.util.Comparator;
241import java.util.Date;
242import java.util.Iterator;
243import java.util.List;
244import java.util.Map;
245import java.util.Objects;
246import java.util.Set;
247import java.util.concurrent.CountDownLatch;
248import java.util.concurrent.TimeUnit;
249import java.util.concurrent.atomic.AtomicBoolean;
250import java.util.concurrent.atomic.AtomicInteger;
251import java.util.concurrent.atomic.AtomicLong;
252
253/**
254 * Keep track of all those .apks everywhere.
255 *
256 * This is very central to the platform's security; please run the unit
257 * tests whenever making modifications here:
258 *
259mmm frameworks/base/tests/AndroidTests
260adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
261adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
262 *
263 * {@hide}
264 */
265public class PackageManagerService extends IPackageManager.Stub {
266    static final String TAG = "PackageManager";
267    static final boolean DEBUG_SETTINGS = false;
268    static final boolean DEBUG_PREFERRED = false;
269    static final boolean DEBUG_UPGRADE = false;
270    private static final boolean DEBUG_BACKUP = true;
271    private static final boolean DEBUG_INSTALL = false;
272    private static final boolean DEBUG_REMOVE = false;
273    private static final boolean DEBUG_BROADCASTS = false;
274    private static final boolean DEBUG_SHOW_INFO = false;
275    private static final boolean DEBUG_PACKAGE_INFO = false;
276    private static final boolean DEBUG_INTENT_MATCHING = false;
277    private static final boolean DEBUG_PACKAGE_SCANNING = false;
278    private static final boolean DEBUG_VERIFY = false;
279    private static final boolean DEBUG_DEXOPT = false;
280    private static final boolean DEBUG_ABI_SELECTION = false;
281
282    private static final int RADIO_UID = Process.PHONE_UID;
283    private static final int LOG_UID = Process.LOG_UID;
284    private static final int NFC_UID = Process.NFC_UID;
285    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
286    private static final int SHELL_UID = Process.SHELL_UID;
287
288    // Cap the size of permission trees that 3rd party apps can define
289    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
290
291    // Suffix used during package installation when copying/moving
292    // package apks to install directory.
293    private static final String INSTALL_PACKAGE_SUFFIX = "-";
294
295    static final int SCAN_NO_DEX = 1<<1;
296    static final int SCAN_FORCE_DEX = 1<<2;
297    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
298    static final int SCAN_NEW_INSTALL = 1<<4;
299    static final int SCAN_NO_PATHS = 1<<5;
300    static final int SCAN_UPDATE_TIME = 1<<6;
301    static final int SCAN_DEFER_DEX = 1<<7;
302    static final int SCAN_BOOTING = 1<<8;
303    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
304    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
305    static final int SCAN_REQUIRE_KNOWN = 1<<12;
306
307    static final int REMOVE_CHATTY = 1<<16;
308
309    private static final int[] EMPTY_INT_ARRAY = new int[0];
310
311    /**
312     * Timeout (in milliseconds) after which the watchdog should declare that
313     * our handler thread is wedged.  The usual default for such things is one
314     * minute but we sometimes do very lengthy I/O operations on this thread,
315     * such as installing multi-gigabyte applications, so ours needs to be longer.
316     */
317    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
318
319    /**
320     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
321     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
322     * settings entry if available, otherwise we use the hardcoded default.  If it's been
323     * more than this long since the last fstrim, we force one during the boot sequence.
324     *
325     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
326     * one gets run at the next available charging+idle time.  This final mandatory
327     * no-fstrim check kicks in only of the other scheduling criteria is never met.
328     */
329    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
330
331    /**
332     * Whether verification is enabled by default.
333     */
334    private static final boolean DEFAULT_VERIFY_ENABLE = true;
335
336    /**
337     * The default maximum time to wait for the verification agent to return in
338     * milliseconds.
339     */
340    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
341
342    /**
343     * The default response for package verification timeout.
344     *
345     * This can be either PackageManager.VERIFICATION_ALLOW or
346     * PackageManager.VERIFICATION_REJECT.
347     */
348    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
349
350    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
351
352    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
353            DEFAULT_CONTAINER_PACKAGE,
354            "com.android.defcontainer.DefaultContainerService");
355
356    private static final String KILL_APP_REASON_GIDS_CHANGED =
357            "permission grant or revoke changed gids";
358
359    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
360            "permissions revoked";
361
362    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
363
364    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
365
366    /** Permission grant: not grant the permission. */
367    private static final int GRANT_DENIED = 1;
368
369    /** Permission grant: grant the permission as an install permission. */
370    private static final int GRANT_INSTALL = 2;
371
372    /** Permission grant: grant the permission as an install permission for a legacy app. */
373    private static final int GRANT_INSTALL_LEGACY = 3;
374
375    /** Permission grant: grant the permission as a runtime one. */
376    private static final int GRANT_RUNTIME = 4;
377
378    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
379    private static final int GRANT_UPGRADE = 5;
380
381    final ServiceThread mHandlerThread;
382
383    final PackageHandler mHandler;
384
385    /**
386     * Messages for {@link #mHandler} that need to wait for system ready before
387     * being dispatched.
388     */
389    private ArrayList<Message> mPostSystemReadyMessages;
390
391    final int mSdkVersion = Build.VERSION.SDK_INT;
392
393    final Context mContext;
394    final boolean mFactoryTest;
395    final boolean mOnlyCore;
396    final boolean mLazyDexOpt;
397    final long mDexOptLRUThresholdInMills;
398    final DisplayMetrics mMetrics;
399    final int mDefParseFlags;
400    final String[] mSeparateProcesses;
401    final boolean mIsUpgrade;
402
403    // This is where all application persistent data goes.
404    final File mAppDataDir;
405
406    // This is where all application persistent data goes for secondary users.
407    final File mUserAppDataDir;
408
409    /** The location for ASEC container files on internal storage. */
410    final String mAsecInternalPath;
411
412    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
413    // LOCK HELD.  Can be called with mInstallLock held.
414    final Installer mInstaller;
415
416    /** Directory where installed third-party apps stored */
417    final File mAppInstallDir;
418
419    /**
420     * Directory to which applications installed internally have their
421     * 32 bit native libraries copied.
422     */
423    private File mAppLib32InstallDir;
424
425    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
426    // apps.
427    final File mDrmAppPrivateInstallDir;
428
429    // ----------------------------------------------------------------
430
431    // Lock for state used when installing and doing other long running
432    // operations.  Methods that must be called with this lock held have
433    // the suffix "LI".
434    final Object mInstallLock = new Object();
435
436    // ----------------------------------------------------------------
437
438    // Keys are String (package name), values are Package.  This also serves
439    // as the lock for the global state.  Methods that must be called with
440    // this lock held have the prefix "LP".
441    final ArrayMap<String, PackageParser.Package> mPackages =
442            new ArrayMap<String, PackageParser.Package>();
443
444    // Tracks available target package names -> overlay package paths.
445    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
446        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
447
448    final Settings mSettings;
449    boolean mRestoredSettings;
450
451    // System configuration read by SystemConfig.
452    final int[] mGlobalGids;
453    final SparseArray<ArraySet<String>> mSystemPermissions;
454    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
455
456    // If mac_permissions.xml was found for seinfo labeling.
457    boolean mFoundPolicyFile;
458
459    // If a recursive restorecon of /data/data/<pkg> is needed.
460    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
461
462    public static final class SharedLibraryEntry {
463        public final String path;
464        public final String apk;
465
466        SharedLibraryEntry(String _path, String _apk) {
467            path = _path;
468            apk = _apk;
469        }
470    }
471
472    // Currently known shared libraries.
473    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
474            new ArrayMap<String, SharedLibraryEntry>();
475
476    // All available activities, for your resolving pleasure.
477    final ActivityIntentResolver mActivities =
478            new ActivityIntentResolver();
479
480    // All available receivers, for your resolving pleasure.
481    final ActivityIntentResolver mReceivers =
482            new ActivityIntentResolver();
483
484    // All available services, for your resolving pleasure.
485    final ServiceIntentResolver mServices = new ServiceIntentResolver();
486
487    // All available providers, for your resolving pleasure.
488    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
489
490    // Mapping from provider base names (first directory in content URI codePath)
491    // to the provider information.
492    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
493            new ArrayMap<String, PackageParser.Provider>();
494
495    // Mapping from instrumentation class names to info about them.
496    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
497            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
498
499    // Mapping from permission names to info about them.
500    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
501            new ArrayMap<String, PackageParser.PermissionGroup>();
502
503    // Packages whose data we have transfered into another package, thus
504    // should no longer exist.
505    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
506
507    // Broadcast actions that are only available to the system.
508    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
509
510    /** List of packages waiting for verification. */
511    final SparseArray<PackageVerificationState> mPendingVerification
512            = new SparseArray<PackageVerificationState>();
513
514    /** Set of packages associated with each app op permission. */
515    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
516
517    final PackageInstallerService mInstallerService;
518
519    private final PackageDexOptimizer mPackageDexOptimizer;
520
521    private AtomicInteger mNextMoveId = new AtomicInteger();
522    private final MoveCallbacks mMoveCallbacks;
523
524    // Cache of users who need badging.
525    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
526
527    /** Token for keys in mPendingVerification. */
528    private int mPendingVerificationToken = 0;
529
530    volatile boolean mSystemReady;
531    volatile boolean mSafeMode;
532    volatile boolean mHasSystemUidErrors;
533
534    ApplicationInfo mAndroidApplication;
535    final ActivityInfo mResolveActivity = new ActivityInfo();
536    final ResolveInfo mResolveInfo = new ResolveInfo();
537    ComponentName mResolveComponentName;
538    PackageParser.Package mPlatformPackage;
539    ComponentName mCustomResolverComponentName;
540
541    boolean mResolverReplaced = false;
542
543    private final ComponentName mIntentFilterVerifierComponent;
544    private int mIntentFilterVerificationToken = 0;
545
546    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
547            = new SparseArray<IntentFilterVerificationState>();
548
549    private interface IntentFilterVerifier<T extends IntentFilter> {
550        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
551                                               T filter, String packageName);
552        void startVerifications(int userId);
553        void receiveVerificationResponse(int verificationId);
554    }
555
556    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
557        private Context mContext;
558        private ComponentName mIntentFilterVerifierComponent;
559        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
560
561        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
562            mContext = context;
563            mIntentFilterVerifierComponent = verifierComponent;
564        }
565
566        private String getDefaultScheme() {
567            // TODO: replace SCHEME_HTTP with SCHEME_HTTPS
568            return IntentFilter.SCHEME_HTTP;
569        }
570
571        @Override
572        public void startVerifications(int userId) {
573            // Launch verifications requests
574            int count = mCurrentIntentFilterVerifications.size();
575            for (int n=0; n<count; n++) {
576                int verificationId = mCurrentIntentFilterVerifications.get(n);
577                final IntentFilterVerificationState ivs =
578                        mIntentFilterVerificationStates.get(verificationId);
579
580                String packageName = ivs.getPackageName();
581
582                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
583                final int filterCount = filters.size();
584                ArraySet<String> domainsSet = new ArraySet<>();
585                for (int m=0; m<filterCount; m++) {
586                    PackageParser.ActivityIntentInfo filter = filters.get(m);
587                    domainsSet.addAll(filter.getHostsList());
588                }
589                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
590                synchronized (mPackages) {
591                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
592                            packageName, domainsList) != null) {
593                        scheduleWriteSettingsLocked();
594                    }
595                }
596                sendVerificationRequest(userId, verificationId, ivs);
597            }
598            mCurrentIntentFilterVerifications.clear();
599        }
600
601        private void sendVerificationRequest(int userId, int verificationId,
602                IntentFilterVerificationState ivs) {
603
604            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
605            verificationIntent.putExtra(
606                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
607                    verificationId);
608            verificationIntent.putExtra(
609                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
610                    getDefaultScheme());
611            verificationIntent.putExtra(
612                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
613                    ivs.getHostsString());
614            verificationIntent.putExtra(
615                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
616                    ivs.getPackageName());
617            verificationIntent.setComponent(mIntentFilterVerifierComponent);
618            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
619
620            UserHandle user = new UserHandle(userId);
621            mContext.sendBroadcastAsUser(verificationIntent, user);
622            Slog.d(TAG, "Sending IntenFilter verification broadcast");
623        }
624
625        public void receiveVerificationResponse(int verificationId) {
626            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
627
628            final boolean verified = ivs.isVerified();
629
630            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
631            final int count = filters.size();
632            for (int n=0; n<count; n++) {
633                PackageParser.ActivityIntentInfo filter = filters.get(n);
634                filter.setVerified(verified);
635
636                Slog.d(TAG, "IntentFilter " + filter.toString() + " verified with result:"
637                        + verified + " and hosts:" + ivs.getHostsString());
638            }
639
640            mIntentFilterVerificationStates.remove(verificationId);
641
642            final String packageName = ivs.getPackageName();
643            IntentFilterVerificationInfo ivi = null;
644
645            synchronized (mPackages) {
646                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
647            }
648            if (ivi == null) {
649                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
650                        + verificationId + " packageName:" + packageName);
651                return;
652            }
653            Slog.d(TAG, "Updating IntentFilterVerificationInfo for verificationId:"
654                    + verificationId);
655
656            synchronized (mPackages) {
657                if (verified) {
658                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
659                } else {
660                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
661                }
662                scheduleWriteSettingsLocked();
663
664                final int userId = ivs.getUserId();
665                if (userId != UserHandle.USER_ALL) {
666                    final int userStatus =
667                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
668
669                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
670                    boolean needUpdate = false;
671
672                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
673                    // already been set by the User thru the Disambiguation dialog
674                    switch (userStatus) {
675                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
676                            if (verified) {
677                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
678                            } else {
679                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
680                            }
681                            needUpdate = true;
682                            break;
683
684                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
685                            if (verified) {
686                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
687                                needUpdate = true;
688                            }
689                            break;
690
691                        default:
692                            // Nothing to do
693                    }
694
695                    if (needUpdate) {
696                        mSettings.updateIntentFilterVerificationStatusLPw(
697                                packageName, updatedStatus, userId);
698                        scheduleWritePackageRestrictionsLocked(userId);
699                    }
700                }
701            }
702        }
703
704        @Override
705        public boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
706                    ActivityIntentInfo filter, String packageName) {
707            if (!(filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
708                    filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
709                Slog.d(TAG, "IntentFilter does not contain HTTP nor HTTPS data scheme");
710                return false;
711            }
712            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
713            if (ivs == null) {
714                ivs = createDomainVerificationState(verifierId, userId, verificationId,
715                        packageName);
716            }
717            if (!hasValidDomains(filter)) {
718                return false;
719            }
720            ivs.addFilter(filter);
721            return true;
722        }
723
724        private IntentFilterVerificationState createDomainVerificationState(int verifierId,
725                int userId, int verificationId, String packageName) {
726            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
727                    verifierId, userId, packageName);
728            ivs.setPendingState();
729            synchronized (mPackages) {
730                mIntentFilterVerificationStates.append(verificationId, ivs);
731                mCurrentIntentFilterVerifications.add(verificationId);
732            }
733            return ivs;
734        }
735    }
736
737    private static boolean hasValidDomains(ActivityIntentInfo filter) {
738        return hasValidDomains(filter, true);
739    }
740
741    private static boolean hasValidDomains(ActivityIntentInfo filter, boolean logging) {
742        boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
743                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS);
744        if (!hasHTTPorHTTPS) {
745            if (logging) {
746                Slog.d(TAG, "IntentFilter does not contain any HTTP or HTTPS data scheme");
747            }
748            return false;
749        }
750        return true;
751    }
752
753    private IntentFilterVerifier mIntentFilterVerifier;
754
755    // Set of pending broadcasts for aggregating enable/disable of components.
756    static class PendingPackageBroadcasts {
757        // for each user id, a map of <package name -> components within that package>
758        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
759
760        public PendingPackageBroadcasts() {
761            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
762        }
763
764        public ArrayList<String> get(int userId, String packageName) {
765            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
766            return packages.get(packageName);
767        }
768
769        public void put(int userId, String packageName, ArrayList<String> components) {
770            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
771            packages.put(packageName, components);
772        }
773
774        public void remove(int userId, String packageName) {
775            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
776            if (packages != null) {
777                packages.remove(packageName);
778            }
779        }
780
781        public void remove(int userId) {
782            mUidMap.remove(userId);
783        }
784
785        public int userIdCount() {
786            return mUidMap.size();
787        }
788
789        public int userIdAt(int n) {
790            return mUidMap.keyAt(n);
791        }
792
793        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
794            return mUidMap.get(userId);
795        }
796
797        public int size() {
798            // total number of pending broadcast entries across all userIds
799            int num = 0;
800            for (int i = 0; i< mUidMap.size(); i++) {
801                num += mUidMap.valueAt(i).size();
802            }
803            return num;
804        }
805
806        public void clear() {
807            mUidMap.clear();
808        }
809
810        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
811            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
812            if (map == null) {
813                map = new ArrayMap<String, ArrayList<String>>();
814                mUidMap.put(userId, map);
815            }
816            return map;
817        }
818    }
819    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
820
821    // Service Connection to remote media container service to copy
822    // package uri's from external media onto secure containers
823    // or internal storage.
824    private IMediaContainerService mContainerService = null;
825
826    static final int SEND_PENDING_BROADCAST = 1;
827    static final int MCS_BOUND = 3;
828    static final int END_COPY = 4;
829    static final int INIT_COPY = 5;
830    static final int MCS_UNBIND = 6;
831    static final int START_CLEANING_PACKAGE = 7;
832    static final int FIND_INSTALL_LOC = 8;
833    static final int POST_INSTALL = 9;
834    static final int MCS_RECONNECT = 10;
835    static final int MCS_GIVE_UP = 11;
836    static final int UPDATED_MEDIA_STATUS = 12;
837    static final int WRITE_SETTINGS = 13;
838    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
839    static final int PACKAGE_VERIFIED = 15;
840    static final int CHECK_PENDING_VERIFICATION = 16;
841    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
842    static final int INTENT_FILTER_VERIFIED = 18;
843
844    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
845
846    // Delay time in millisecs
847    static final int BROADCAST_DELAY = 10 * 1000;
848
849    static UserManagerService sUserManager;
850
851    // Stores a list of users whose package restrictions file needs to be updated
852    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
853
854    final private DefaultContainerConnection mDefContainerConn =
855            new DefaultContainerConnection();
856    class DefaultContainerConnection implements ServiceConnection {
857        public void onServiceConnected(ComponentName name, IBinder service) {
858            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
859            IMediaContainerService imcs =
860                IMediaContainerService.Stub.asInterface(service);
861            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
862        }
863
864        public void onServiceDisconnected(ComponentName name) {
865            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
866        }
867    };
868
869    // Recordkeeping of restore-after-install operations that are currently in flight
870    // between the Package Manager and the Backup Manager
871    class PostInstallData {
872        public InstallArgs args;
873        public PackageInstalledInfo res;
874
875        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
876            args = _a;
877            res = _r;
878        }
879    };
880    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
881    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
882
883    // backup/restore of preferred activity state
884    private static final String TAG_PREFERRED_BACKUP = "pa";
885
886    private final String mRequiredVerifierPackage;
887
888    private final PackageUsage mPackageUsage = new PackageUsage();
889
890    private class PackageUsage {
891        private static final int WRITE_INTERVAL
892            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
893
894        private final Object mFileLock = new Object();
895        private final AtomicLong mLastWritten = new AtomicLong(0);
896        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
897
898        private boolean mIsHistoricalPackageUsageAvailable = true;
899
900        boolean isHistoricalPackageUsageAvailable() {
901            return mIsHistoricalPackageUsageAvailable;
902        }
903
904        void write(boolean force) {
905            if (force) {
906                writeInternal();
907                return;
908            }
909            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
910                && !DEBUG_DEXOPT) {
911                return;
912            }
913            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
914                new Thread("PackageUsage_DiskWriter") {
915                    @Override
916                    public void run() {
917                        try {
918                            writeInternal();
919                        } finally {
920                            mBackgroundWriteRunning.set(false);
921                        }
922                    }
923                }.start();
924            }
925        }
926
927        private void writeInternal() {
928            synchronized (mPackages) {
929                synchronized (mFileLock) {
930                    AtomicFile file = getFile();
931                    FileOutputStream f = null;
932                    try {
933                        f = file.startWrite();
934                        BufferedOutputStream out = new BufferedOutputStream(f);
935                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
936                        StringBuilder sb = new StringBuilder();
937                        for (PackageParser.Package pkg : mPackages.values()) {
938                            if (pkg.mLastPackageUsageTimeInMills == 0) {
939                                continue;
940                            }
941                            sb.setLength(0);
942                            sb.append(pkg.packageName);
943                            sb.append(' ');
944                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
945                            sb.append('\n');
946                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
947                        }
948                        out.flush();
949                        file.finishWrite(f);
950                    } catch (IOException e) {
951                        if (f != null) {
952                            file.failWrite(f);
953                        }
954                        Log.e(TAG, "Failed to write package usage times", e);
955                    }
956                }
957            }
958            mLastWritten.set(SystemClock.elapsedRealtime());
959        }
960
961        void readLP() {
962            synchronized (mFileLock) {
963                AtomicFile file = getFile();
964                BufferedInputStream in = null;
965                try {
966                    in = new BufferedInputStream(file.openRead());
967                    StringBuffer sb = new StringBuffer();
968                    while (true) {
969                        String packageName = readToken(in, sb, ' ');
970                        if (packageName == null) {
971                            break;
972                        }
973                        String timeInMillisString = readToken(in, sb, '\n');
974                        if (timeInMillisString == null) {
975                            throw new IOException("Failed to find last usage time for package "
976                                                  + packageName);
977                        }
978                        PackageParser.Package pkg = mPackages.get(packageName);
979                        if (pkg == null) {
980                            continue;
981                        }
982                        long timeInMillis;
983                        try {
984                            timeInMillis = Long.parseLong(timeInMillisString.toString());
985                        } catch (NumberFormatException e) {
986                            throw new IOException("Failed to parse " + timeInMillisString
987                                                  + " as a long.", e);
988                        }
989                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
990                    }
991                } catch (FileNotFoundException expected) {
992                    mIsHistoricalPackageUsageAvailable = false;
993                } catch (IOException e) {
994                    Log.w(TAG, "Failed to read package usage times", e);
995                } finally {
996                    IoUtils.closeQuietly(in);
997                }
998            }
999            mLastWritten.set(SystemClock.elapsedRealtime());
1000        }
1001
1002        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1003                throws IOException {
1004            sb.setLength(0);
1005            while (true) {
1006                int ch = in.read();
1007                if (ch == -1) {
1008                    if (sb.length() == 0) {
1009                        return null;
1010                    }
1011                    throw new IOException("Unexpected EOF");
1012                }
1013                if (ch == endOfToken) {
1014                    return sb.toString();
1015                }
1016                sb.append((char)ch);
1017            }
1018        }
1019
1020        private AtomicFile getFile() {
1021            File dataDir = Environment.getDataDirectory();
1022            File systemDir = new File(dataDir, "system");
1023            File fname = new File(systemDir, "package-usage.list");
1024            return new AtomicFile(fname);
1025        }
1026    }
1027
1028    class PackageHandler extends Handler {
1029        private boolean mBound = false;
1030        final ArrayList<HandlerParams> mPendingInstalls =
1031            new ArrayList<HandlerParams>();
1032
1033        private boolean connectToService() {
1034            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1035                    " DefaultContainerService");
1036            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1037            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1038            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1039                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1040                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1041                mBound = true;
1042                return true;
1043            }
1044            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1045            return false;
1046        }
1047
1048        private void disconnectService() {
1049            mContainerService = null;
1050            mBound = false;
1051            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1052            mContext.unbindService(mDefContainerConn);
1053            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1054        }
1055
1056        PackageHandler(Looper looper) {
1057            super(looper);
1058        }
1059
1060        public void handleMessage(Message msg) {
1061            try {
1062                doHandleMessage(msg);
1063            } finally {
1064                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1065            }
1066        }
1067
1068        void doHandleMessage(Message msg) {
1069            switch (msg.what) {
1070                case INIT_COPY: {
1071                    HandlerParams params = (HandlerParams) msg.obj;
1072                    int idx = mPendingInstalls.size();
1073                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1074                    // If a bind was already initiated we dont really
1075                    // need to do anything. The pending install
1076                    // will be processed later on.
1077                    if (!mBound) {
1078                        // If this is the only one pending we might
1079                        // have to bind to the service again.
1080                        if (!connectToService()) {
1081                            Slog.e(TAG, "Failed to bind to media container service");
1082                            params.serviceError();
1083                            return;
1084                        } else {
1085                            // Once we bind to the service, the first
1086                            // pending request will be processed.
1087                            mPendingInstalls.add(idx, params);
1088                        }
1089                    } else {
1090                        mPendingInstalls.add(idx, params);
1091                        // Already bound to the service. Just make
1092                        // sure we trigger off processing the first request.
1093                        if (idx == 0) {
1094                            mHandler.sendEmptyMessage(MCS_BOUND);
1095                        }
1096                    }
1097                    break;
1098                }
1099                case MCS_BOUND: {
1100                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1101                    if (msg.obj != null) {
1102                        mContainerService = (IMediaContainerService) msg.obj;
1103                    }
1104                    if (mContainerService == null) {
1105                        // Something seriously wrong. Bail out
1106                        Slog.e(TAG, "Cannot bind to media container service");
1107                        for (HandlerParams params : mPendingInstalls) {
1108                            // Indicate service bind error
1109                            params.serviceError();
1110                        }
1111                        mPendingInstalls.clear();
1112                    } else if (mPendingInstalls.size() > 0) {
1113                        HandlerParams params = mPendingInstalls.get(0);
1114                        if (params != null) {
1115                            if (params.startCopy()) {
1116                                // We are done...  look for more work or to
1117                                // go idle.
1118                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1119                                        "Checking for more work or unbind...");
1120                                // Delete pending install
1121                                if (mPendingInstalls.size() > 0) {
1122                                    mPendingInstalls.remove(0);
1123                                }
1124                                if (mPendingInstalls.size() == 0) {
1125                                    if (mBound) {
1126                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1127                                                "Posting delayed MCS_UNBIND");
1128                                        removeMessages(MCS_UNBIND);
1129                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1130                                        // Unbind after a little delay, to avoid
1131                                        // continual thrashing.
1132                                        sendMessageDelayed(ubmsg, 10000);
1133                                    }
1134                                } else {
1135                                    // There are more pending requests in queue.
1136                                    // Just post MCS_BOUND message to trigger processing
1137                                    // of next pending install.
1138                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1139                                            "Posting MCS_BOUND for next work");
1140                                    mHandler.sendEmptyMessage(MCS_BOUND);
1141                                }
1142                            }
1143                        }
1144                    } else {
1145                        // Should never happen ideally.
1146                        Slog.w(TAG, "Empty queue");
1147                    }
1148                    break;
1149                }
1150                case MCS_RECONNECT: {
1151                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1152                    if (mPendingInstalls.size() > 0) {
1153                        if (mBound) {
1154                            disconnectService();
1155                        }
1156                        if (!connectToService()) {
1157                            Slog.e(TAG, "Failed to bind to media container service");
1158                            for (HandlerParams params : mPendingInstalls) {
1159                                // Indicate service bind error
1160                                params.serviceError();
1161                            }
1162                            mPendingInstalls.clear();
1163                        }
1164                    }
1165                    break;
1166                }
1167                case MCS_UNBIND: {
1168                    // If there is no actual work left, then time to unbind.
1169                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1170
1171                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1172                        if (mBound) {
1173                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1174
1175                            disconnectService();
1176                        }
1177                    } else if (mPendingInstalls.size() > 0) {
1178                        // There are more pending requests in queue.
1179                        // Just post MCS_BOUND message to trigger processing
1180                        // of next pending install.
1181                        mHandler.sendEmptyMessage(MCS_BOUND);
1182                    }
1183
1184                    break;
1185                }
1186                case MCS_GIVE_UP: {
1187                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1188                    mPendingInstalls.remove(0);
1189                    break;
1190                }
1191                case SEND_PENDING_BROADCAST: {
1192                    String packages[];
1193                    ArrayList<String> components[];
1194                    int size = 0;
1195                    int uids[];
1196                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1197                    synchronized (mPackages) {
1198                        if (mPendingBroadcasts == null) {
1199                            return;
1200                        }
1201                        size = mPendingBroadcasts.size();
1202                        if (size <= 0) {
1203                            // Nothing to be done. Just return
1204                            return;
1205                        }
1206                        packages = new String[size];
1207                        components = new ArrayList[size];
1208                        uids = new int[size];
1209                        int i = 0;  // filling out the above arrays
1210
1211                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1212                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1213                            Iterator<Map.Entry<String, ArrayList<String>>> it
1214                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1215                                            .entrySet().iterator();
1216                            while (it.hasNext() && i < size) {
1217                                Map.Entry<String, ArrayList<String>> ent = it.next();
1218                                packages[i] = ent.getKey();
1219                                components[i] = ent.getValue();
1220                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1221                                uids[i] = (ps != null)
1222                                        ? UserHandle.getUid(packageUserId, ps.appId)
1223                                        : -1;
1224                                i++;
1225                            }
1226                        }
1227                        size = i;
1228                        mPendingBroadcasts.clear();
1229                    }
1230                    // Send broadcasts
1231                    for (int i = 0; i < size; i++) {
1232                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1233                    }
1234                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1235                    break;
1236                }
1237                case START_CLEANING_PACKAGE: {
1238                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1239                    final String packageName = (String)msg.obj;
1240                    final int userId = msg.arg1;
1241                    final boolean andCode = msg.arg2 != 0;
1242                    synchronized (mPackages) {
1243                        if (userId == UserHandle.USER_ALL) {
1244                            int[] users = sUserManager.getUserIds();
1245                            for (int user : users) {
1246                                mSettings.addPackageToCleanLPw(
1247                                        new PackageCleanItem(user, packageName, andCode));
1248                            }
1249                        } else {
1250                            mSettings.addPackageToCleanLPw(
1251                                    new PackageCleanItem(userId, packageName, andCode));
1252                        }
1253                    }
1254                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1255                    startCleaningPackages();
1256                } break;
1257                case POST_INSTALL: {
1258                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1259                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1260                    mRunningInstalls.delete(msg.arg1);
1261                    boolean deleteOld = false;
1262
1263                    if (data != null) {
1264                        InstallArgs args = data.args;
1265                        PackageInstalledInfo res = data.res;
1266
1267                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1268                            res.removedInfo.sendBroadcast(false, true, false);
1269                            Bundle extras = new Bundle(1);
1270                            extras.putInt(Intent.EXTRA_UID, res.uid);
1271
1272                            // Now that we successfully installed the package, grant runtime
1273                            // permissions if requested before broadcasting the install.
1274                            if ((args.installFlags
1275                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1276                                grantRequestedRuntimePermissions(res.pkg,
1277                                        args.user.getIdentifier());
1278                            }
1279
1280                            // Determine the set of users who are adding this
1281                            // package for the first time vs. those who are seeing
1282                            // an update.
1283                            int[] firstUsers;
1284                            int[] updateUsers = new int[0];
1285                            if (res.origUsers == null || res.origUsers.length == 0) {
1286                                firstUsers = res.newUsers;
1287                            } else {
1288                                firstUsers = new int[0];
1289                                for (int i=0; i<res.newUsers.length; i++) {
1290                                    int user = res.newUsers[i];
1291                                    boolean isNew = true;
1292                                    for (int j=0; j<res.origUsers.length; j++) {
1293                                        if (res.origUsers[j] == user) {
1294                                            isNew = false;
1295                                            break;
1296                                        }
1297                                    }
1298                                    if (isNew) {
1299                                        int[] newFirst = new int[firstUsers.length+1];
1300                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1301                                                firstUsers.length);
1302                                        newFirst[firstUsers.length] = user;
1303                                        firstUsers = newFirst;
1304                                    } else {
1305                                        int[] newUpdate = new int[updateUsers.length+1];
1306                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1307                                                updateUsers.length);
1308                                        newUpdate[updateUsers.length] = user;
1309                                        updateUsers = newUpdate;
1310                                    }
1311                                }
1312                            }
1313                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1314                                    res.pkg.applicationInfo.packageName,
1315                                    extras, null, null, firstUsers);
1316                            final boolean update = res.removedInfo.removedPackage != null;
1317                            if (update) {
1318                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1319                            }
1320                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1321                                    res.pkg.applicationInfo.packageName,
1322                                    extras, null, null, updateUsers);
1323                            if (update) {
1324                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1325                                        res.pkg.applicationInfo.packageName,
1326                                        extras, null, null, updateUsers);
1327                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1328                                        null, null,
1329                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1330
1331                                // treat asec-hosted packages like removable media on upgrade
1332                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1333                                    if (DEBUG_INSTALL) {
1334                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1335                                                + " is ASEC-hosted -> AVAILABLE");
1336                                    }
1337                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1338                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1339                                    pkgList.add(res.pkg.applicationInfo.packageName);
1340                                    sendResourcesChangedBroadcast(true, true,
1341                                            pkgList,uidArray, null);
1342                                }
1343                            }
1344                            if (res.removedInfo.args != null) {
1345                                // Remove the replaced package's older resources safely now
1346                                deleteOld = true;
1347                            }
1348
1349                            // Log current value of "unknown sources" setting
1350                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1351                                getUnknownSourcesSettings());
1352                        }
1353                        // Force a gc to clear up things
1354                        Runtime.getRuntime().gc();
1355                        // We delete after a gc for applications  on sdcard.
1356                        if (deleteOld) {
1357                            synchronized (mInstallLock) {
1358                                res.removedInfo.args.doPostDeleteLI(true);
1359                            }
1360                        }
1361                        if (args.observer != null) {
1362                            try {
1363                                Bundle extras = extrasForInstallResult(res);
1364                                args.observer.onPackageInstalled(res.name, res.returnCode,
1365                                        res.returnMsg, extras);
1366                            } catch (RemoteException e) {
1367                                Slog.i(TAG, "Observer no longer exists.");
1368                            }
1369                        }
1370                    } else {
1371                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1372                    }
1373                } break;
1374                case UPDATED_MEDIA_STATUS: {
1375                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1376                    boolean reportStatus = msg.arg1 == 1;
1377                    boolean doGc = msg.arg2 == 1;
1378                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1379                    if (doGc) {
1380                        // Force a gc to clear up stale containers.
1381                        Runtime.getRuntime().gc();
1382                    }
1383                    if (msg.obj != null) {
1384                        @SuppressWarnings("unchecked")
1385                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1386                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1387                        // Unload containers
1388                        unloadAllContainers(args);
1389                    }
1390                    if (reportStatus) {
1391                        try {
1392                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1393                            PackageHelper.getMountService().finishMediaUpdate();
1394                        } catch (RemoteException e) {
1395                            Log.e(TAG, "MountService not running?");
1396                        }
1397                    }
1398                } break;
1399                case WRITE_SETTINGS: {
1400                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1401                    synchronized (mPackages) {
1402                        removeMessages(WRITE_SETTINGS);
1403                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1404                        mSettings.writeLPr();
1405                        mDirtyUsers.clear();
1406                    }
1407                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1408                } break;
1409                case WRITE_PACKAGE_RESTRICTIONS: {
1410                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1411                    synchronized (mPackages) {
1412                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1413                        for (int userId : mDirtyUsers) {
1414                            mSettings.writePackageRestrictionsLPr(userId);
1415                        }
1416                        mDirtyUsers.clear();
1417                    }
1418                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1419                } break;
1420                case CHECK_PENDING_VERIFICATION: {
1421                    final int verificationId = msg.arg1;
1422                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1423
1424                    if ((state != null) && !state.timeoutExtended()) {
1425                        final InstallArgs args = state.getInstallArgs();
1426                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1427
1428                        Slog.i(TAG, "Verification timed out for " + originUri);
1429                        mPendingVerification.remove(verificationId);
1430
1431                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1432
1433                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1434                            Slog.i(TAG, "Continuing with installation of " + originUri);
1435                            state.setVerifierResponse(Binder.getCallingUid(),
1436                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1437                            broadcastPackageVerified(verificationId, originUri,
1438                                    PackageManager.VERIFICATION_ALLOW,
1439                                    state.getInstallArgs().getUser());
1440                            try {
1441                                ret = args.copyApk(mContainerService, true);
1442                            } catch (RemoteException e) {
1443                                Slog.e(TAG, "Could not contact the ContainerService");
1444                            }
1445                        } else {
1446                            broadcastPackageVerified(verificationId, originUri,
1447                                    PackageManager.VERIFICATION_REJECT,
1448                                    state.getInstallArgs().getUser());
1449                        }
1450
1451                        processPendingInstall(args, ret);
1452                        mHandler.sendEmptyMessage(MCS_UNBIND);
1453                    }
1454                    break;
1455                }
1456                case PACKAGE_VERIFIED: {
1457                    final int verificationId = msg.arg1;
1458
1459                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1460                    if (state == null) {
1461                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1462                        break;
1463                    }
1464
1465                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1466
1467                    state.setVerifierResponse(response.callerUid, response.code);
1468
1469                    if (state.isVerificationComplete()) {
1470                        mPendingVerification.remove(verificationId);
1471
1472                        final InstallArgs args = state.getInstallArgs();
1473                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1474
1475                        int ret;
1476                        if (state.isInstallAllowed()) {
1477                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1478                            broadcastPackageVerified(verificationId, originUri,
1479                                    response.code, state.getInstallArgs().getUser());
1480                            try {
1481                                ret = args.copyApk(mContainerService, true);
1482                            } catch (RemoteException e) {
1483                                Slog.e(TAG, "Could not contact the ContainerService");
1484                            }
1485                        } else {
1486                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1487                        }
1488
1489                        processPendingInstall(args, ret);
1490
1491                        mHandler.sendEmptyMessage(MCS_UNBIND);
1492                    }
1493
1494                    break;
1495                }
1496                case START_INTENT_FILTER_VERIFICATIONS: {
1497                    int userId = msg.arg1;
1498                    int verifierUid = msg.arg2;
1499                    PackageParser.Package pkg = (PackageParser.Package)msg.obj;
1500
1501                    verifyIntentFiltersIfNeeded(userId, verifierUid, pkg);
1502                    break;
1503                }
1504                case INTENT_FILTER_VERIFIED: {
1505                    final int verificationId = msg.arg1;
1506
1507                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1508                            verificationId);
1509                    if (state == null) {
1510                        Slog.w(TAG, "Invalid IntentFilter verification token "
1511                                + verificationId + " received");
1512                        break;
1513                    }
1514
1515                    final int userId = state.getUserId();
1516
1517                    Slog.d(TAG, "Processing IntentFilter verification with token:"
1518                            + verificationId + " and userId:" + userId);
1519
1520                    final IntentFilterVerificationResponse response =
1521                            (IntentFilterVerificationResponse) msg.obj;
1522
1523                    state.setVerifierResponse(response.callerUid, response.code);
1524
1525                    Slog.d(TAG, "IntentFilter verification with token:" + verificationId
1526                            + " and userId:" + userId
1527                            + " is settings verifier response with response code:"
1528                            + response.code);
1529
1530                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1531                        Slog.d(TAG, "Domains failing verification: "
1532                                + response.getFailedDomainsString());
1533                    }
1534
1535                    if (state.isVerificationComplete()) {
1536                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1537                    } else {
1538                        Slog.d(TAG, "IntentFilter verification with token:" + verificationId
1539                                + " was not said to be complete");
1540                    }
1541
1542                    break;
1543                }
1544            }
1545        }
1546    }
1547
1548    private StorageEventListener mStorageListener = new StorageEventListener() {
1549        @Override
1550        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1551            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1552                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1553                    // TODO: ensure that private directories exist for all active users
1554                    // TODO: remove user data whose serial number doesn't match
1555                    loadPrivatePackages(vol);
1556                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1557                    unloadPrivatePackages(vol);
1558                }
1559            }
1560
1561            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1562                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1563                    updateExternalMediaStatus(true, false);
1564                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1565                    updateExternalMediaStatus(false, false);
1566                }
1567            }
1568        }
1569
1570        @Override
1571        public void onVolumeForgotten(String fsUuid) {
1572            // TODO: remove all packages hosted on this uuid
1573        }
1574    };
1575
1576    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) {
1577        if (userId >= UserHandle.USER_OWNER) {
1578            grantRequestedRuntimePermissionsForUser(pkg, userId);
1579        } else if (userId == UserHandle.USER_ALL) {
1580            for (int someUserId : UserManagerService.getInstance().getUserIds()) {
1581                grantRequestedRuntimePermissionsForUser(pkg, someUserId);
1582            }
1583        }
1584    }
1585
1586    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) {
1587        SettingBase sb = (SettingBase) pkg.mExtras;
1588        if (sb == null) {
1589            return;
1590        }
1591
1592        PermissionsState permissionsState = sb.getPermissionsState();
1593
1594        for (String permission : pkg.requestedPermissions) {
1595            BasePermission bp = mSettings.mPermissions.get(permission);
1596            if (bp != null && bp.isRuntime()) {
1597                permissionsState.grantRuntimePermission(bp, userId);
1598            }
1599        }
1600    }
1601
1602    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1603        Bundle extras = null;
1604        switch (res.returnCode) {
1605            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1606                extras = new Bundle();
1607                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1608                        res.origPermission);
1609                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1610                        res.origPackage);
1611                break;
1612            }
1613            case PackageManager.INSTALL_SUCCEEDED: {
1614                extras = new Bundle();
1615                extras.putBoolean(Intent.EXTRA_REPLACING,
1616                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1617                break;
1618            }
1619        }
1620        return extras;
1621    }
1622
1623    void scheduleWriteSettingsLocked() {
1624        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1625            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1626        }
1627    }
1628
1629    void scheduleWritePackageRestrictionsLocked(int userId) {
1630        if (!sUserManager.exists(userId)) return;
1631        mDirtyUsers.add(userId);
1632        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1633            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1634        }
1635    }
1636
1637    public static PackageManagerService main(Context context, Installer installer,
1638            boolean factoryTest, boolean onlyCore) {
1639        PackageManagerService m = new PackageManagerService(context, installer,
1640                factoryTest, onlyCore);
1641        ServiceManager.addService("package", m);
1642        return m;
1643    }
1644
1645    static String[] splitString(String str, char sep) {
1646        int count = 1;
1647        int i = 0;
1648        while ((i=str.indexOf(sep, i)) >= 0) {
1649            count++;
1650            i++;
1651        }
1652
1653        String[] res = new String[count];
1654        i=0;
1655        count = 0;
1656        int lastI=0;
1657        while ((i=str.indexOf(sep, i)) >= 0) {
1658            res[count] = str.substring(lastI, i);
1659            count++;
1660            i++;
1661            lastI = i;
1662        }
1663        res[count] = str.substring(lastI, str.length());
1664        return res;
1665    }
1666
1667    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1668        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1669                Context.DISPLAY_SERVICE);
1670        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1671    }
1672
1673    public PackageManagerService(Context context, Installer installer,
1674            boolean factoryTest, boolean onlyCore) {
1675        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1676                SystemClock.uptimeMillis());
1677
1678        if (mSdkVersion <= 0) {
1679            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1680        }
1681
1682        mContext = context;
1683        mFactoryTest = factoryTest;
1684        mOnlyCore = onlyCore;
1685        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1686        mMetrics = new DisplayMetrics();
1687        mSettings = new Settings(mPackages);
1688        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1689                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1690        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1691                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1692        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1693                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1694        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1695                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1696        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1697                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1698        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1699                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1700
1701        // TODO: add a property to control this?
1702        long dexOptLRUThresholdInMinutes;
1703        if (mLazyDexOpt) {
1704            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1705        } else {
1706            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1707        }
1708        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1709
1710        String separateProcesses = SystemProperties.get("debug.separate_processes");
1711        if (separateProcesses != null && separateProcesses.length() > 0) {
1712            if ("*".equals(separateProcesses)) {
1713                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1714                mSeparateProcesses = null;
1715                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1716            } else {
1717                mDefParseFlags = 0;
1718                mSeparateProcesses = separateProcesses.split(",");
1719                Slog.w(TAG, "Running with debug.separate_processes: "
1720                        + separateProcesses);
1721            }
1722        } else {
1723            mDefParseFlags = 0;
1724            mSeparateProcesses = null;
1725        }
1726
1727        mInstaller = installer;
1728        mPackageDexOptimizer = new PackageDexOptimizer(this);
1729        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1730
1731        getDefaultDisplayMetrics(context, mMetrics);
1732
1733        SystemConfig systemConfig = SystemConfig.getInstance();
1734        mGlobalGids = systemConfig.getGlobalGids();
1735        mSystemPermissions = systemConfig.getSystemPermissions();
1736        mAvailableFeatures = systemConfig.getAvailableFeatures();
1737
1738        synchronized (mInstallLock) {
1739        // writer
1740        synchronized (mPackages) {
1741            mHandlerThread = new ServiceThread(TAG,
1742                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1743            mHandlerThread.start();
1744            mHandler = new PackageHandler(mHandlerThread.getLooper());
1745            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1746
1747            File dataDir = Environment.getDataDirectory();
1748            mAppDataDir = new File(dataDir, "data");
1749            mAppInstallDir = new File(dataDir, "app");
1750            mAppLib32InstallDir = new File(dataDir, "app-lib");
1751            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1752            mUserAppDataDir = new File(dataDir, "user");
1753            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1754
1755            sUserManager = new UserManagerService(context, this,
1756                    mInstallLock, mPackages);
1757
1758            // Propagate permission configuration in to package manager.
1759            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1760                    = systemConfig.getPermissions();
1761            for (int i=0; i<permConfig.size(); i++) {
1762                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1763                BasePermission bp = mSettings.mPermissions.get(perm.name);
1764                if (bp == null) {
1765                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1766                    mSettings.mPermissions.put(perm.name, bp);
1767                }
1768                if (perm.gids != null) {
1769                    bp.setGids(perm.gids, perm.perUser);
1770                }
1771            }
1772
1773            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1774            for (int i=0; i<libConfig.size(); i++) {
1775                mSharedLibraries.put(libConfig.keyAt(i),
1776                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1777            }
1778
1779            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1780
1781            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1782                    mSdkVersion, mOnlyCore);
1783
1784            String customResolverActivity = Resources.getSystem().getString(
1785                    R.string.config_customResolverActivity);
1786            if (TextUtils.isEmpty(customResolverActivity)) {
1787                customResolverActivity = null;
1788            } else {
1789                mCustomResolverComponentName = ComponentName.unflattenFromString(
1790                        customResolverActivity);
1791            }
1792
1793            long startTime = SystemClock.uptimeMillis();
1794
1795            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1796                    startTime);
1797
1798            // Set flag to monitor and not change apk file paths when
1799            // scanning install directories.
1800            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1801
1802            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1803
1804            /**
1805             * Add everything in the in the boot class path to the
1806             * list of process files because dexopt will have been run
1807             * if necessary during zygote startup.
1808             */
1809            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1810            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1811
1812            if (bootClassPath != null) {
1813                String[] bootClassPathElements = splitString(bootClassPath, ':');
1814                for (String element : bootClassPathElements) {
1815                    alreadyDexOpted.add(element);
1816                }
1817            } else {
1818                Slog.w(TAG, "No BOOTCLASSPATH found!");
1819            }
1820
1821            if (systemServerClassPath != null) {
1822                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1823                for (String element : systemServerClassPathElements) {
1824                    alreadyDexOpted.add(element);
1825                }
1826            } else {
1827                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1828            }
1829
1830            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1831            final String[] dexCodeInstructionSets =
1832                    getDexCodeInstructionSets(
1833                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1834
1835            /**
1836             * Ensure all external libraries have had dexopt run on them.
1837             */
1838            if (mSharedLibraries.size() > 0) {
1839                // NOTE: For now, we're compiling these system "shared libraries"
1840                // (and framework jars) into all available architectures. It's possible
1841                // to compile them only when we come across an app that uses them (there's
1842                // already logic for that in scanPackageLI) but that adds some complexity.
1843                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1844                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1845                        final String lib = libEntry.path;
1846                        if (lib == null) {
1847                            continue;
1848                        }
1849
1850                        try {
1851                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1852                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1853                                alreadyDexOpted.add(lib);
1854                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1855                            }
1856                        } catch (FileNotFoundException e) {
1857                            Slog.w(TAG, "Library not found: " + lib);
1858                        } catch (IOException e) {
1859                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1860                                    + e.getMessage());
1861                        }
1862                    }
1863                }
1864            }
1865
1866            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1867
1868            // Gross hack for now: we know this file doesn't contain any
1869            // code, so don't dexopt it to avoid the resulting log spew.
1870            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1871
1872            // Gross hack for now: we know this file is only part of
1873            // the boot class path for art, so don't dexopt it to
1874            // avoid the resulting log spew.
1875            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1876
1877            /**
1878             * And there are a number of commands implemented in Java, which
1879             * we currently need to do the dexopt on so that they can be
1880             * run from a non-root shell.
1881             */
1882            String[] frameworkFiles = frameworkDir.list();
1883            if (frameworkFiles != null) {
1884                // TODO: We could compile these only for the most preferred ABI. We should
1885                // first double check that the dex files for these commands are not referenced
1886                // by other system apps.
1887                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1888                    for (int i=0; i<frameworkFiles.length; i++) {
1889                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1890                        String path = libPath.getPath();
1891                        // Skip the file if we already did it.
1892                        if (alreadyDexOpted.contains(path)) {
1893                            continue;
1894                        }
1895                        // Skip the file if it is not a type we want to dexopt.
1896                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1897                            continue;
1898                        }
1899                        try {
1900                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
1901                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1902                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1903                            }
1904                        } catch (FileNotFoundException e) {
1905                            Slog.w(TAG, "Jar not found: " + path);
1906                        } catch (IOException e) {
1907                            Slog.w(TAG, "Exception reading jar: " + path, e);
1908                        }
1909                    }
1910                }
1911            }
1912
1913            // Collect vendor overlay packages.
1914            // (Do this before scanning any apps.)
1915            // For security and version matching reason, only consider
1916            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1917            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1918            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1919                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1920
1921            // Find base frameworks (resource packages without code).
1922            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1923                    | PackageParser.PARSE_IS_SYSTEM_DIR
1924                    | PackageParser.PARSE_IS_PRIVILEGED,
1925                    scanFlags | SCAN_NO_DEX, 0);
1926
1927            // Collected privileged system packages.
1928            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1929            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1930                    | PackageParser.PARSE_IS_SYSTEM_DIR
1931                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1932
1933            // Collect ordinary system packages.
1934            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
1935            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1936                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1937
1938            // Collect all vendor packages.
1939            File vendorAppDir = new File("/vendor/app");
1940            try {
1941                vendorAppDir = vendorAppDir.getCanonicalFile();
1942            } catch (IOException e) {
1943                // failed to look up canonical path, continue with original one
1944            }
1945            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1946                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1947
1948            // Collect all OEM packages.
1949            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
1950            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1951                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1952
1953            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1954            mInstaller.moveFiles();
1955
1956            // Prune any system packages that no longer exist.
1957            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1958            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
1959            if (!mOnlyCore) {
1960                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1961                while (psit.hasNext()) {
1962                    PackageSetting ps = psit.next();
1963
1964                    /*
1965                     * If this is not a system app, it can't be a
1966                     * disable system app.
1967                     */
1968                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1969                        continue;
1970                    }
1971
1972                    /*
1973                     * If the package is scanned, it's not erased.
1974                     */
1975                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1976                    if (scannedPkg != null) {
1977                        /*
1978                         * If the system app is both scanned and in the
1979                         * disabled packages list, then it must have been
1980                         * added via OTA. Remove it from the currently
1981                         * scanned package so the previously user-installed
1982                         * application can be scanned.
1983                         */
1984                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1985                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
1986                                    + ps.name + "; removing system app.  Last known codePath="
1987                                    + ps.codePathString + ", installStatus=" + ps.installStatus
1988                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
1989                                    + scannedPkg.mVersionCode);
1990                            removePackageLI(ps, true);
1991                            expectingBetter.put(ps.name, ps.codePath);
1992                        }
1993
1994                        continue;
1995                    }
1996
1997                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1998                        psit.remove();
1999                        logCriticalInfo(Log.WARN, "System package " + ps.name
2000                                + " no longer exists; wiping its data");
2001                        removeDataDirsLI(null, ps.name);
2002                    } else {
2003                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2004                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2005                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2006                        }
2007                    }
2008                }
2009            }
2010
2011            //look for any incomplete package installations
2012            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2013            //clean up list
2014            for(int i = 0; i < deletePkgsList.size(); i++) {
2015                //clean up here
2016                cleanupInstallFailedPackage(deletePkgsList.get(i));
2017            }
2018            //delete tmp files
2019            deleteTempPackageFiles();
2020
2021            // Remove any shared userIDs that have no associated packages
2022            mSettings.pruneSharedUsersLPw();
2023
2024            if (!mOnlyCore) {
2025                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2026                        SystemClock.uptimeMillis());
2027                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2028
2029                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2030                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2031
2032                /**
2033                 * Remove disable package settings for any updated system
2034                 * apps that were removed via an OTA. If they're not a
2035                 * previously-updated app, remove them completely.
2036                 * Otherwise, just revoke their system-level permissions.
2037                 */
2038                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2039                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2040                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2041
2042                    String msg;
2043                    if (deletedPkg == null) {
2044                        msg = "Updated system package " + deletedAppName
2045                                + " no longer exists; wiping its data";
2046                        removeDataDirsLI(null, deletedAppName);
2047                    } else {
2048                        msg = "Updated system app + " + deletedAppName
2049                                + " no longer present; removing system privileges for "
2050                                + deletedAppName;
2051
2052                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2053
2054                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2055                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2056                    }
2057                    logCriticalInfo(Log.WARN, msg);
2058                }
2059
2060                /**
2061                 * Make sure all system apps that we expected to appear on
2062                 * the userdata partition actually showed up. If they never
2063                 * appeared, crawl back and revive the system version.
2064                 */
2065                for (int i = 0; i < expectingBetter.size(); i++) {
2066                    final String packageName = expectingBetter.keyAt(i);
2067                    if (!mPackages.containsKey(packageName)) {
2068                        final File scanFile = expectingBetter.valueAt(i);
2069
2070                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2071                                + " but never showed up; reverting to system");
2072
2073                        final int reparseFlags;
2074                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2075                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2076                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2077                                    | PackageParser.PARSE_IS_PRIVILEGED;
2078                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2079                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2080                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2081                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2082                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2083                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2084                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2085                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2086                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2087                        } else {
2088                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2089                            continue;
2090                        }
2091
2092                        mSettings.enableSystemPackageLPw(packageName);
2093
2094                        try {
2095                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2096                        } catch (PackageManagerException e) {
2097                            Slog.e(TAG, "Failed to parse original system package: "
2098                                    + e.getMessage());
2099                        }
2100                    }
2101                }
2102            }
2103
2104            // Now that we know all of the shared libraries, update all clients to have
2105            // the correct library paths.
2106            updateAllSharedLibrariesLPw();
2107
2108            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2109                // NOTE: We ignore potential failures here during a system scan (like
2110                // the rest of the commands above) because there's precious little we
2111                // can do about it. A settings error is reported, though.
2112                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2113                        false /* force dexopt */, false /* defer dexopt */);
2114            }
2115
2116            // Now that we know all the packages we are keeping,
2117            // read and update their last usage times.
2118            mPackageUsage.readLP();
2119
2120            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2121                    SystemClock.uptimeMillis());
2122            Slog.i(TAG, "Time to scan packages: "
2123                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2124                    + " seconds");
2125
2126            // If the platform SDK has changed since the last time we booted,
2127            // we need to re-grant app permission to catch any new ones that
2128            // appear.  This is really a hack, and means that apps can in some
2129            // cases get permissions that the user didn't initially explicitly
2130            // allow...  it would be nice to have some better way to handle
2131            // this situation.
2132            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
2133                    != mSdkVersion;
2134            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
2135                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
2136                    + "; regranting permissions for internal storage");
2137            mSettings.mInternalSdkPlatform = mSdkVersion;
2138
2139            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
2140                    | (regrantPermissions
2141                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
2142                            : 0));
2143
2144            // If this is the first boot, and it is a normal boot, then
2145            // we need to initialize the default preferred apps.
2146            if (!mRestoredSettings && !onlyCore) {
2147                mSettings.readDefaultPreferredAppsLPw(this, 0);
2148            }
2149
2150            // If this is first boot after an OTA, and a normal boot, then
2151            // we need to clear code cache directories.
2152            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
2153            if (mIsUpgrade && !onlyCore) {
2154                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2155                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2156                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2157                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2158                }
2159                mSettings.mFingerprint = Build.FINGERPRINT;
2160            }
2161
2162            primeDomainVerificationsLPw(false);
2163            checkDefaultBrowser();
2164
2165            // All the changes are done during package scanning.
2166            mSettings.updateInternalDatabaseVersion();
2167
2168            // can downgrade to reader
2169            mSettings.writeLPr();
2170
2171            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2172                    SystemClock.uptimeMillis());
2173
2174            mRequiredVerifierPackage = getRequiredVerifierLPr();
2175
2176            mInstallerService = new PackageInstallerService(context, this);
2177
2178            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2179            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2180                    mIntentFilterVerifierComponent);
2181
2182        } // synchronized (mPackages)
2183        } // synchronized (mInstallLock)
2184
2185        // Now after opening every single application zip, make sure they
2186        // are all flushed.  Not really needed, but keeps things nice and
2187        // tidy.
2188        Runtime.getRuntime().gc();
2189    }
2190
2191    @Override
2192    public boolean isFirstBoot() {
2193        return !mRestoredSettings;
2194    }
2195
2196    @Override
2197    public boolean isOnlyCoreApps() {
2198        return mOnlyCore;
2199    }
2200
2201    @Override
2202    public boolean isUpgrade() {
2203        return mIsUpgrade;
2204    }
2205
2206    private String getRequiredVerifierLPr() {
2207        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2208        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2209                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2210
2211        String requiredVerifier = null;
2212
2213        final int N = receivers.size();
2214        for (int i = 0; i < N; i++) {
2215            final ResolveInfo info = receivers.get(i);
2216
2217            if (info.activityInfo == null) {
2218                continue;
2219            }
2220
2221            final String packageName = info.activityInfo.packageName;
2222
2223            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2224                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2225                continue;
2226            }
2227
2228            if (requiredVerifier != null) {
2229                throw new RuntimeException("There can be only one required verifier");
2230            }
2231
2232            requiredVerifier = packageName;
2233        }
2234
2235        return requiredVerifier;
2236    }
2237
2238    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2239        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2240        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2241                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2242
2243        ComponentName verifierComponentName = null;
2244
2245        int priority = -1000;
2246        final int N = receivers.size();
2247        for (int i = 0; i < N; i++) {
2248            final ResolveInfo info = receivers.get(i);
2249
2250            if (info.activityInfo == null) {
2251                continue;
2252            }
2253
2254            final String packageName = info.activityInfo.packageName;
2255
2256            final PackageSetting ps = mSettings.mPackages.get(packageName);
2257            if (ps == null) {
2258                continue;
2259            }
2260
2261            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2262                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2263                continue;
2264            }
2265
2266            // Select the IntentFilterVerifier with the highest priority
2267            if (priority < info.priority) {
2268                priority = info.priority;
2269                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2270                Slog.d(TAG, "Selecting IntentFilterVerifier: " + verifierComponentName +
2271                        " with priority: " + info.priority);
2272            }
2273        }
2274
2275        return verifierComponentName;
2276    }
2277
2278    private void primeDomainVerificationsLPw(boolean logging) {
2279        Slog.d(TAG, "Start priming domain verifications");
2280        boolean updated = false;
2281        ArraySet<String> allHostsSet = new ArraySet<>();
2282        for (PackageParser.Package pkg : mPackages.values()) {
2283            final String packageName = pkg.packageName;
2284            if (!hasDomainURLs(pkg)) {
2285                if (logging) {
2286                    Slog.d(TAG, "No priming domain verifications for " +
2287                            "package with no domain URLs: " + packageName);
2288                }
2289                continue;
2290            }
2291            if (!pkg.isSystemApp()) {
2292                if (logging) {
2293                    Slog.d(TAG, "No priming domain verifications for a non system package : " +
2294                            packageName);
2295                }
2296                continue;
2297            }
2298            for (PackageParser.Activity a : pkg.activities) {
2299                for (ActivityIntentInfo filter : a.intents) {
2300                    if (hasValidDomains(filter, false)) {
2301                        allHostsSet.addAll(filter.getHostsList());
2302                    }
2303                }
2304            }
2305            if (allHostsSet.size() == 0) {
2306                allHostsSet.add("*");
2307            }
2308            ArrayList<String> allHostsList = new ArrayList<>(allHostsSet);
2309            IntentFilterVerificationInfo ivi =
2310                    mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList);
2311            if (ivi != null) {
2312                // We will always log this
2313                Slog.d(TAG, "Priming domain verifications for package: " + packageName +
2314                        " with hosts:" + ivi.getDomainsString());
2315                ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
2316                updated = true;
2317            }
2318            else {
2319                if (logging) {
2320                    Slog.d(TAG, "No priming domain verifications for package: " + packageName);
2321                }
2322            }
2323            allHostsSet.clear();
2324        }
2325        if (updated) {
2326            if (logging) {
2327                Slog.d(TAG, "Will need to write primed domain verifications");
2328            }
2329        }
2330        Slog.d(TAG, "End priming domain verifications");
2331    }
2332
2333    private void checkDefaultBrowser() {
2334        final int myUserId = UserHandle.myUserId();
2335        final String packageName = getDefaultBrowserPackageName(myUserId);
2336        PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2337        if (info == null) {
2338            Slog.w(TAG, "Clearing default Browser as its package is no more installed: " +
2339                    packageName);
2340            setDefaultBrowserPackageName(null, myUserId);
2341        }
2342    }
2343
2344    @Override
2345    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2346            throws RemoteException {
2347        try {
2348            return super.onTransact(code, data, reply, flags);
2349        } catch (RuntimeException e) {
2350            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2351                Slog.wtf(TAG, "Package Manager Crash", e);
2352            }
2353            throw e;
2354        }
2355    }
2356
2357    void cleanupInstallFailedPackage(PackageSetting ps) {
2358        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2359
2360        removeDataDirsLI(ps.volumeUuid, ps.name);
2361        if (ps.codePath != null) {
2362            if (ps.codePath.isDirectory()) {
2363                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2364            } else {
2365                ps.codePath.delete();
2366            }
2367        }
2368        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2369            if (ps.resourcePath.isDirectory()) {
2370                FileUtils.deleteContents(ps.resourcePath);
2371            }
2372            ps.resourcePath.delete();
2373        }
2374        mSettings.removePackageLPw(ps.name);
2375    }
2376
2377    static int[] appendInts(int[] cur, int[] add) {
2378        if (add == null) return cur;
2379        if (cur == null) return add;
2380        final int N = add.length;
2381        for (int i=0; i<N; i++) {
2382            cur = appendInt(cur, add[i]);
2383        }
2384        return cur;
2385    }
2386
2387    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2388        if (!sUserManager.exists(userId)) return null;
2389        final PackageSetting ps = (PackageSetting) p.mExtras;
2390        if (ps == null) {
2391            return null;
2392        }
2393
2394        final PermissionsState permissionsState = ps.getPermissionsState();
2395
2396        final int[] gids = permissionsState.computeGids(userId);
2397        final Set<String> permissions = permissionsState.getPermissions(userId);
2398        final PackageUserState state = ps.readUserState(userId);
2399
2400        return PackageParser.generatePackageInfo(p, gids, flags,
2401                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2402    }
2403
2404    @Override
2405    public boolean isPackageFrozen(String packageName) {
2406        synchronized (mPackages) {
2407            final PackageSetting ps = mSettings.mPackages.get(packageName);
2408            if (ps != null) {
2409                return ps.frozen;
2410            }
2411        }
2412        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2413        return true;
2414    }
2415
2416    @Override
2417    public boolean isPackageAvailable(String packageName, int userId) {
2418        if (!sUserManager.exists(userId)) return false;
2419        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2420        synchronized (mPackages) {
2421            PackageParser.Package p = mPackages.get(packageName);
2422            if (p != null) {
2423                final PackageSetting ps = (PackageSetting) p.mExtras;
2424                if (ps != null) {
2425                    final PackageUserState state = ps.readUserState(userId);
2426                    if (state != null) {
2427                        return PackageParser.isAvailable(state);
2428                    }
2429                }
2430            }
2431        }
2432        return false;
2433    }
2434
2435    @Override
2436    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2437        if (!sUserManager.exists(userId)) return null;
2438        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2439        // reader
2440        synchronized (mPackages) {
2441            PackageParser.Package p = mPackages.get(packageName);
2442            if (DEBUG_PACKAGE_INFO)
2443                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2444            if (p != null) {
2445                return generatePackageInfo(p, flags, userId);
2446            }
2447            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2448                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2449            }
2450        }
2451        return null;
2452    }
2453
2454    @Override
2455    public String[] currentToCanonicalPackageNames(String[] names) {
2456        String[] out = new String[names.length];
2457        // reader
2458        synchronized (mPackages) {
2459            for (int i=names.length-1; i>=0; i--) {
2460                PackageSetting ps = mSettings.mPackages.get(names[i]);
2461                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2462            }
2463        }
2464        return out;
2465    }
2466
2467    @Override
2468    public String[] canonicalToCurrentPackageNames(String[] names) {
2469        String[] out = new String[names.length];
2470        // reader
2471        synchronized (mPackages) {
2472            for (int i=names.length-1; i>=0; i--) {
2473                String cur = mSettings.mRenamedPackages.get(names[i]);
2474                out[i] = cur != null ? cur : names[i];
2475            }
2476        }
2477        return out;
2478    }
2479
2480    @Override
2481    public int getPackageUid(String packageName, int userId) {
2482        if (!sUserManager.exists(userId)) return -1;
2483        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2484
2485        // reader
2486        synchronized (mPackages) {
2487            PackageParser.Package p = mPackages.get(packageName);
2488            if(p != null) {
2489                return UserHandle.getUid(userId, p.applicationInfo.uid);
2490            }
2491            PackageSetting ps = mSettings.mPackages.get(packageName);
2492            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2493                return -1;
2494            }
2495            p = ps.pkg;
2496            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2497        }
2498    }
2499
2500    @Override
2501    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2502        if (!sUserManager.exists(userId)) {
2503            return null;
2504        }
2505
2506        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2507                "getPackageGids");
2508
2509        // reader
2510        synchronized (mPackages) {
2511            PackageParser.Package p = mPackages.get(packageName);
2512            if (DEBUG_PACKAGE_INFO) {
2513                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2514            }
2515            if (p != null) {
2516                PackageSetting ps = (PackageSetting) p.mExtras;
2517                return ps.getPermissionsState().computeGids(userId);
2518            }
2519        }
2520
2521        return null;
2522    }
2523
2524    static PermissionInfo generatePermissionInfo(
2525            BasePermission bp, int flags) {
2526        if (bp.perm != null) {
2527            return PackageParser.generatePermissionInfo(bp.perm, flags);
2528        }
2529        PermissionInfo pi = new PermissionInfo();
2530        pi.name = bp.name;
2531        pi.packageName = bp.sourcePackage;
2532        pi.nonLocalizedLabel = bp.name;
2533        pi.protectionLevel = bp.protectionLevel;
2534        return pi;
2535    }
2536
2537    @Override
2538    public PermissionInfo getPermissionInfo(String name, int flags) {
2539        // reader
2540        synchronized (mPackages) {
2541            final BasePermission p = mSettings.mPermissions.get(name);
2542            if (p != null) {
2543                return generatePermissionInfo(p, flags);
2544            }
2545            return null;
2546        }
2547    }
2548
2549    @Override
2550    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2551        // reader
2552        synchronized (mPackages) {
2553            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2554            for (BasePermission p : mSettings.mPermissions.values()) {
2555                if (group == null) {
2556                    if (p.perm == null || p.perm.info.group == null) {
2557                        out.add(generatePermissionInfo(p, flags));
2558                    }
2559                } else {
2560                    if (p.perm != null && group.equals(p.perm.info.group)) {
2561                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2562                    }
2563                }
2564            }
2565
2566            if (out.size() > 0) {
2567                return out;
2568            }
2569            return mPermissionGroups.containsKey(group) ? out : null;
2570        }
2571    }
2572
2573    @Override
2574    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2575        // reader
2576        synchronized (mPackages) {
2577            return PackageParser.generatePermissionGroupInfo(
2578                    mPermissionGroups.get(name), flags);
2579        }
2580    }
2581
2582    @Override
2583    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2584        // reader
2585        synchronized (mPackages) {
2586            final int N = mPermissionGroups.size();
2587            ArrayList<PermissionGroupInfo> out
2588                    = new ArrayList<PermissionGroupInfo>(N);
2589            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2590                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2591            }
2592            return out;
2593        }
2594    }
2595
2596    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2597            int userId) {
2598        if (!sUserManager.exists(userId)) return null;
2599        PackageSetting ps = mSettings.mPackages.get(packageName);
2600        if (ps != null) {
2601            if (ps.pkg == null) {
2602                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2603                        flags, userId);
2604                if (pInfo != null) {
2605                    return pInfo.applicationInfo;
2606                }
2607                return null;
2608            }
2609            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2610                    ps.readUserState(userId), userId);
2611        }
2612        return null;
2613    }
2614
2615    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2616            int userId) {
2617        if (!sUserManager.exists(userId)) return null;
2618        PackageSetting ps = mSettings.mPackages.get(packageName);
2619        if (ps != null) {
2620            PackageParser.Package pkg = ps.pkg;
2621            if (pkg == null) {
2622                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2623                    return null;
2624                }
2625                // Only data remains, so we aren't worried about code paths
2626                pkg = new PackageParser.Package(packageName);
2627                pkg.applicationInfo.packageName = packageName;
2628                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2629                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2630                pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid,
2631                        packageName, userId).getAbsolutePath();
2632                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2633                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2634            }
2635            return generatePackageInfo(pkg, flags, userId);
2636        }
2637        return null;
2638    }
2639
2640    @Override
2641    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2642        if (!sUserManager.exists(userId)) return null;
2643        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2644        // writer
2645        synchronized (mPackages) {
2646            PackageParser.Package p = mPackages.get(packageName);
2647            if (DEBUG_PACKAGE_INFO) Log.v(
2648                    TAG, "getApplicationInfo " + packageName
2649                    + ": " + p);
2650            if (p != null) {
2651                PackageSetting ps = mSettings.mPackages.get(packageName);
2652                if (ps == null) return null;
2653                // Note: isEnabledLP() does not apply here - always return info
2654                return PackageParser.generateApplicationInfo(
2655                        p, flags, ps.readUserState(userId), userId);
2656            }
2657            if ("android".equals(packageName)||"system".equals(packageName)) {
2658                return mAndroidApplication;
2659            }
2660            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2661                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2662            }
2663        }
2664        return null;
2665    }
2666
2667    @Override
2668    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2669            final IPackageDataObserver observer) {
2670        mContext.enforceCallingOrSelfPermission(
2671                android.Manifest.permission.CLEAR_APP_CACHE, null);
2672        // Queue up an async operation since clearing cache may take a little while.
2673        mHandler.post(new Runnable() {
2674            public void run() {
2675                mHandler.removeCallbacks(this);
2676                int retCode = -1;
2677                synchronized (mInstallLock) {
2678                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2679                    if (retCode < 0) {
2680                        Slog.w(TAG, "Couldn't clear application caches");
2681                    }
2682                }
2683                if (observer != null) {
2684                    try {
2685                        observer.onRemoveCompleted(null, (retCode >= 0));
2686                    } catch (RemoteException e) {
2687                        Slog.w(TAG, "RemoveException when invoking call back");
2688                    }
2689                }
2690            }
2691        });
2692    }
2693
2694    @Override
2695    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2696            final IntentSender pi) {
2697        mContext.enforceCallingOrSelfPermission(
2698                android.Manifest.permission.CLEAR_APP_CACHE, null);
2699        // Queue up an async operation since clearing cache may take a little while.
2700        mHandler.post(new Runnable() {
2701            public void run() {
2702                mHandler.removeCallbacks(this);
2703                int retCode = -1;
2704                synchronized (mInstallLock) {
2705                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2706                    if (retCode < 0) {
2707                        Slog.w(TAG, "Couldn't clear application caches");
2708                    }
2709                }
2710                if(pi != null) {
2711                    try {
2712                        // Callback via pending intent
2713                        int code = (retCode >= 0) ? 1 : 0;
2714                        pi.sendIntent(null, code, null,
2715                                null, null);
2716                    } catch (SendIntentException e1) {
2717                        Slog.i(TAG, "Failed to send pending intent");
2718                    }
2719                }
2720            }
2721        });
2722    }
2723
2724    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2725        synchronized (mInstallLock) {
2726            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2727                throw new IOException("Failed to free enough space");
2728            }
2729        }
2730    }
2731
2732    @Override
2733    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2734        if (!sUserManager.exists(userId)) return null;
2735        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2736        synchronized (mPackages) {
2737            PackageParser.Activity a = mActivities.mActivities.get(component);
2738
2739            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2740            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2741                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2742                if (ps == null) return null;
2743                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2744                        userId);
2745            }
2746            if (mResolveComponentName.equals(component)) {
2747                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2748                        new PackageUserState(), userId);
2749            }
2750        }
2751        return null;
2752    }
2753
2754    @Override
2755    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2756            String resolvedType) {
2757        synchronized (mPackages) {
2758            PackageParser.Activity a = mActivities.mActivities.get(component);
2759            if (a == null) {
2760                return false;
2761            }
2762            for (int i=0; i<a.intents.size(); i++) {
2763                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2764                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2765                    return true;
2766                }
2767            }
2768            return false;
2769        }
2770    }
2771
2772    @Override
2773    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2774        if (!sUserManager.exists(userId)) return null;
2775        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2776        synchronized (mPackages) {
2777            PackageParser.Activity a = mReceivers.mActivities.get(component);
2778            if (DEBUG_PACKAGE_INFO) Log.v(
2779                TAG, "getReceiverInfo " + component + ": " + a);
2780            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2781                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2782                if (ps == null) return null;
2783                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2784                        userId);
2785            }
2786        }
2787        return null;
2788    }
2789
2790    @Override
2791    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2792        if (!sUserManager.exists(userId)) return null;
2793        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2794        synchronized (mPackages) {
2795            PackageParser.Service s = mServices.mServices.get(component);
2796            if (DEBUG_PACKAGE_INFO) Log.v(
2797                TAG, "getServiceInfo " + component + ": " + s);
2798            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2799                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2800                if (ps == null) return null;
2801                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2802                        userId);
2803            }
2804        }
2805        return null;
2806    }
2807
2808    @Override
2809    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2810        if (!sUserManager.exists(userId)) return null;
2811        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2812        synchronized (mPackages) {
2813            PackageParser.Provider p = mProviders.mProviders.get(component);
2814            if (DEBUG_PACKAGE_INFO) Log.v(
2815                TAG, "getProviderInfo " + component + ": " + p);
2816            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2817                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2818                if (ps == null) return null;
2819                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2820                        userId);
2821            }
2822        }
2823        return null;
2824    }
2825
2826    @Override
2827    public String[] getSystemSharedLibraryNames() {
2828        Set<String> libSet;
2829        synchronized (mPackages) {
2830            libSet = mSharedLibraries.keySet();
2831            int size = libSet.size();
2832            if (size > 0) {
2833                String[] libs = new String[size];
2834                libSet.toArray(libs);
2835                return libs;
2836            }
2837        }
2838        return null;
2839    }
2840
2841    /**
2842     * @hide
2843     */
2844    PackageParser.Package findSharedNonSystemLibrary(String libName) {
2845        synchronized (mPackages) {
2846            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
2847            if (lib != null && lib.apk != null) {
2848                return mPackages.get(lib.apk);
2849            }
2850        }
2851        return null;
2852    }
2853
2854    @Override
2855    public FeatureInfo[] getSystemAvailableFeatures() {
2856        Collection<FeatureInfo> featSet;
2857        synchronized (mPackages) {
2858            featSet = mAvailableFeatures.values();
2859            int size = featSet.size();
2860            if (size > 0) {
2861                FeatureInfo[] features = new FeatureInfo[size+1];
2862                featSet.toArray(features);
2863                FeatureInfo fi = new FeatureInfo();
2864                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2865                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2866                features[size] = fi;
2867                return features;
2868            }
2869        }
2870        return null;
2871    }
2872
2873    @Override
2874    public boolean hasSystemFeature(String name) {
2875        synchronized (mPackages) {
2876            return mAvailableFeatures.containsKey(name);
2877        }
2878    }
2879
2880    private void checkValidCaller(int uid, int userId) {
2881        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2882            return;
2883
2884        throw new SecurityException("Caller uid=" + uid
2885                + " is not privileged to communicate with user=" + userId);
2886    }
2887
2888    @Override
2889    public int checkPermission(String permName, String pkgName, int userId) {
2890        if (!sUserManager.exists(userId)) {
2891            return PackageManager.PERMISSION_DENIED;
2892        }
2893
2894        synchronized (mPackages) {
2895            final PackageParser.Package p = mPackages.get(pkgName);
2896            if (p != null && p.mExtras != null) {
2897                final PackageSetting ps = (PackageSetting) p.mExtras;
2898                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2899                    return PackageManager.PERMISSION_GRANTED;
2900                }
2901            }
2902        }
2903
2904        return PackageManager.PERMISSION_DENIED;
2905    }
2906
2907    @Override
2908    public int checkUidPermission(String permName, int uid) {
2909        final int userId = UserHandle.getUserId(uid);
2910
2911        if (!sUserManager.exists(userId)) {
2912            return PackageManager.PERMISSION_DENIED;
2913        }
2914
2915        synchronized (mPackages) {
2916            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2917            if (obj != null) {
2918                final SettingBase ps = (SettingBase) obj;
2919                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2920                    return PackageManager.PERMISSION_GRANTED;
2921                }
2922            } else {
2923                ArraySet<String> perms = mSystemPermissions.get(uid);
2924                if (perms != null && perms.contains(permName)) {
2925                    return PackageManager.PERMISSION_GRANTED;
2926                }
2927            }
2928        }
2929
2930        return PackageManager.PERMISSION_DENIED;
2931    }
2932
2933    /**
2934     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2935     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2936     * @param checkShell TODO(yamasani):
2937     * @param message the message to log on security exception
2938     */
2939    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2940            boolean checkShell, String message) {
2941        if (userId < 0) {
2942            throw new IllegalArgumentException("Invalid userId " + userId);
2943        }
2944        if (checkShell) {
2945            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
2946        }
2947        if (userId == UserHandle.getUserId(callingUid)) return;
2948        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2949            if (requireFullPermission) {
2950                mContext.enforceCallingOrSelfPermission(
2951                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2952            } else {
2953                try {
2954                    mContext.enforceCallingOrSelfPermission(
2955                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2956                } catch (SecurityException se) {
2957                    mContext.enforceCallingOrSelfPermission(
2958                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2959                }
2960            }
2961        }
2962    }
2963
2964    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
2965        if (callingUid == Process.SHELL_UID) {
2966            if (userHandle >= 0
2967                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
2968                throw new SecurityException("Shell does not have permission to access user "
2969                        + userHandle);
2970            } else if (userHandle < 0) {
2971                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
2972                        + Debug.getCallers(3));
2973            }
2974        }
2975    }
2976
2977    private BasePermission findPermissionTreeLP(String permName) {
2978        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2979            if (permName.startsWith(bp.name) &&
2980                    permName.length() > bp.name.length() &&
2981                    permName.charAt(bp.name.length()) == '.') {
2982                return bp;
2983            }
2984        }
2985        return null;
2986    }
2987
2988    private BasePermission checkPermissionTreeLP(String permName) {
2989        if (permName != null) {
2990            BasePermission bp = findPermissionTreeLP(permName);
2991            if (bp != null) {
2992                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2993                    return bp;
2994                }
2995                throw new SecurityException("Calling uid "
2996                        + Binder.getCallingUid()
2997                        + " is not allowed to add to permission tree "
2998                        + bp.name + " owned by uid " + bp.uid);
2999            }
3000        }
3001        throw new SecurityException("No permission tree found for " + permName);
3002    }
3003
3004    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3005        if (s1 == null) {
3006            return s2 == null;
3007        }
3008        if (s2 == null) {
3009            return false;
3010        }
3011        if (s1.getClass() != s2.getClass()) {
3012            return false;
3013        }
3014        return s1.equals(s2);
3015    }
3016
3017    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3018        if (pi1.icon != pi2.icon) return false;
3019        if (pi1.logo != pi2.logo) return false;
3020        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3021        if (!compareStrings(pi1.name, pi2.name)) return false;
3022        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3023        // We'll take care of setting this one.
3024        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3025        // These are not currently stored in settings.
3026        //if (!compareStrings(pi1.group, pi2.group)) return false;
3027        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3028        //if (pi1.labelRes != pi2.labelRes) return false;
3029        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3030        return true;
3031    }
3032
3033    int permissionInfoFootprint(PermissionInfo info) {
3034        int size = info.name.length();
3035        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3036        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3037        return size;
3038    }
3039
3040    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3041        int size = 0;
3042        for (BasePermission perm : mSettings.mPermissions.values()) {
3043            if (perm.uid == tree.uid) {
3044                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3045            }
3046        }
3047        return size;
3048    }
3049
3050    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3051        // We calculate the max size of permissions defined by this uid and throw
3052        // if that plus the size of 'info' would exceed our stated maximum.
3053        if (tree.uid != Process.SYSTEM_UID) {
3054            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3055            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3056                throw new SecurityException("Permission tree size cap exceeded");
3057            }
3058        }
3059    }
3060
3061    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3062        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3063            throw new SecurityException("Label must be specified in permission");
3064        }
3065        BasePermission tree = checkPermissionTreeLP(info.name);
3066        BasePermission bp = mSettings.mPermissions.get(info.name);
3067        boolean added = bp == null;
3068        boolean changed = true;
3069        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3070        if (added) {
3071            enforcePermissionCapLocked(info, tree);
3072            bp = new BasePermission(info.name, tree.sourcePackage,
3073                    BasePermission.TYPE_DYNAMIC);
3074        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3075            throw new SecurityException(
3076                    "Not allowed to modify non-dynamic permission "
3077                    + info.name);
3078        } else {
3079            if (bp.protectionLevel == fixedLevel
3080                    && bp.perm.owner.equals(tree.perm.owner)
3081                    && bp.uid == tree.uid
3082                    && comparePermissionInfos(bp.perm.info, info)) {
3083                changed = false;
3084            }
3085        }
3086        bp.protectionLevel = fixedLevel;
3087        info = new PermissionInfo(info);
3088        info.protectionLevel = fixedLevel;
3089        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3090        bp.perm.info.packageName = tree.perm.info.packageName;
3091        bp.uid = tree.uid;
3092        if (added) {
3093            mSettings.mPermissions.put(info.name, bp);
3094        }
3095        if (changed) {
3096            if (!async) {
3097                mSettings.writeLPr();
3098            } else {
3099                scheduleWriteSettingsLocked();
3100            }
3101        }
3102        return added;
3103    }
3104
3105    @Override
3106    public boolean addPermission(PermissionInfo info) {
3107        synchronized (mPackages) {
3108            return addPermissionLocked(info, false);
3109        }
3110    }
3111
3112    @Override
3113    public boolean addPermissionAsync(PermissionInfo info) {
3114        synchronized (mPackages) {
3115            return addPermissionLocked(info, true);
3116        }
3117    }
3118
3119    @Override
3120    public void removePermission(String name) {
3121        synchronized (mPackages) {
3122            checkPermissionTreeLP(name);
3123            BasePermission bp = mSettings.mPermissions.get(name);
3124            if (bp != null) {
3125                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3126                    throw new SecurityException(
3127                            "Not allowed to modify non-dynamic permission "
3128                            + name);
3129                }
3130                mSettings.mPermissions.remove(name);
3131                mSettings.writeLPr();
3132            }
3133        }
3134    }
3135
3136    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3137            BasePermission bp) {
3138        int index = pkg.requestedPermissions.indexOf(bp.name);
3139        if (index == -1) {
3140            throw new SecurityException("Package " + pkg.packageName
3141                    + " has not requested permission " + bp.name);
3142        }
3143        if (!bp.isRuntime()) {
3144            throw new SecurityException("Permission " + bp.name
3145                    + " is not a changeable permission type");
3146        }
3147    }
3148
3149    @Override
3150    public void grantRuntimePermission(String packageName, String name, int userId) {
3151        if (!sUserManager.exists(userId)) {
3152            Log.e(TAG, "No such user:" + userId);
3153            return;
3154        }
3155
3156        mContext.enforceCallingOrSelfPermission(
3157                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3158                "grantRuntimePermission");
3159
3160        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3161                "grantRuntimePermission");
3162
3163        boolean gidsChanged = false;
3164        final SettingBase sb;
3165
3166        synchronized (mPackages) {
3167            final PackageParser.Package pkg = mPackages.get(packageName);
3168            if (pkg == null) {
3169                throw new IllegalArgumentException("Unknown package: " + packageName);
3170            }
3171
3172            final BasePermission bp = mSettings.mPermissions.get(name);
3173            if (bp == null) {
3174                throw new IllegalArgumentException("Unknown permission: " + name);
3175            }
3176
3177            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3178
3179            sb = (SettingBase) pkg.mExtras;
3180            if (sb == null) {
3181                throw new IllegalArgumentException("Unknown package: " + packageName);
3182            }
3183
3184            final PermissionsState permissionsState = sb.getPermissionsState();
3185
3186            final int result = permissionsState.grantRuntimePermission(bp, userId);
3187            switch (result) {
3188                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3189                    return;
3190                }
3191
3192                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3193                    gidsChanged = true;
3194                }
3195                break;
3196            }
3197
3198            // Not critical if that is lost - app has to request again.
3199            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3200        }
3201
3202        if (gidsChanged) {
3203            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3204        }
3205    }
3206
3207    @Override
3208    public void revokeRuntimePermission(String packageName, String name, int userId) {
3209        if (!sUserManager.exists(userId)) {
3210            Log.e(TAG, "No such user:" + userId);
3211            return;
3212        }
3213
3214        mContext.enforceCallingOrSelfPermission(
3215                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3216                "revokeRuntimePermission");
3217
3218        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3219                "revokeRuntimePermission");
3220
3221        final SettingBase sb;
3222
3223        synchronized (mPackages) {
3224            final PackageParser.Package pkg = mPackages.get(packageName);
3225            if (pkg == null) {
3226                throw new IllegalArgumentException("Unknown package: " + packageName);
3227            }
3228
3229            final BasePermission bp = mSettings.mPermissions.get(name);
3230            if (bp == null) {
3231                throw new IllegalArgumentException("Unknown permission: " + name);
3232            }
3233
3234            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3235
3236            sb = (SettingBase) pkg.mExtras;
3237            if (sb == null) {
3238                throw new IllegalArgumentException("Unknown package: " + packageName);
3239            }
3240
3241            final PermissionsState permissionsState = sb.getPermissionsState();
3242
3243            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3244                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3245                return;
3246            }
3247
3248            // Critical, after this call app should never have the permission.
3249            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3250        }
3251
3252        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3253    }
3254
3255    @Override
3256    public int getPermissionFlags(String name, String packageName, int userId) {
3257        if (!sUserManager.exists(userId)) {
3258            return 0;
3259        }
3260
3261        mContext.enforceCallingOrSelfPermission(
3262                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3263                "getPermissionFlags");
3264
3265        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3266                "getPermissionFlags");
3267
3268        synchronized (mPackages) {
3269            final PackageParser.Package pkg = mPackages.get(packageName);
3270            if (pkg == null) {
3271                throw new IllegalArgumentException("Unknown package: " + packageName);
3272            }
3273
3274            final BasePermission bp = mSettings.mPermissions.get(name);
3275            if (bp == null) {
3276                throw new IllegalArgumentException("Unknown permission: " + name);
3277            }
3278
3279            SettingBase sb = (SettingBase) pkg.mExtras;
3280            if (sb == null) {
3281                throw new IllegalArgumentException("Unknown package: " + packageName);
3282            }
3283
3284            PermissionsState permissionsState = sb.getPermissionsState();
3285            return permissionsState.getPermissionFlags(name, userId);
3286        }
3287    }
3288
3289    @Override
3290    public void updatePermissionFlags(String name, String packageName, int flagMask,
3291            int flagValues, int userId) {
3292        if (!sUserManager.exists(userId)) {
3293            return;
3294        }
3295
3296        mContext.enforceCallingOrSelfPermission(
3297                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3298                "updatePermissionFlags");
3299
3300        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3301                "updatePermissionFlags");
3302
3303        // Only the system can change policy flags.
3304        if (getCallingUid() != Process.SYSTEM_UID) {
3305            flagMask &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED;
3306            flagValues &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED;
3307        }
3308
3309        // Only the package manager can change system flags.
3310        flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3311        flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3312
3313        synchronized (mPackages) {
3314            final PackageParser.Package pkg = mPackages.get(packageName);
3315            if (pkg == null) {
3316                throw new IllegalArgumentException("Unknown package: " + packageName);
3317            }
3318
3319            final BasePermission bp = mSettings.mPermissions.get(name);
3320            if (bp == null) {
3321                throw new IllegalArgumentException("Unknown permission: " + name);
3322            }
3323
3324            SettingBase sb = (SettingBase) pkg.mExtras;
3325            if (sb == null) {
3326                throw new IllegalArgumentException("Unknown package: " + packageName);
3327            }
3328
3329            PermissionsState permissionsState = sb.getPermissionsState();
3330
3331            // Only the package manager can change flags for system component permissions.
3332            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3333            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3334                return;
3335            }
3336
3337            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3338                // Install and runtime permissions are stored in different places,
3339                // so figure out what permission changed and persist the change.
3340                if (permissionsState.getInstallPermissionState(name) != null) {
3341                    scheduleWriteSettingsLocked();
3342                } else if (permissionsState.getRuntimePermissionState(name, userId) != null) {
3343                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3344                }
3345            }
3346        }
3347    }
3348
3349    @Override
3350    public boolean isProtectedBroadcast(String actionName) {
3351        synchronized (mPackages) {
3352            return mProtectedBroadcasts.contains(actionName);
3353        }
3354    }
3355
3356    @Override
3357    public int checkSignatures(String pkg1, String pkg2) {
3358        synchronized (mPackages) {
3359            final PackageParser.Package p1 = mPackages.get(pkg1);
3360            final PackageParser.Package p2 = mPackages.get(pkg2);
3361            if (p1 == null || p1.mExtras == null
3362                    || p2 == null || p2.mExtras == null) {
3363                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3364            }
3365            return compareSignatures(p1.mSignatures, p2.mSignatures);
3366        }
3367    }
3368
3369    @Override
3370    public int checkUidSignatures(int uid1, int uid2) {
3371        // Map to base uids.
3372        uid1 = UserHandle.getAppId(uid1);
3373        uid2 = UserHandle.getAppId(uid2);
3374        // reader
3375        synchronized (mPackages) {
3376            Signature[] s1;
3377            Signature[] s2;
3378            Object obj = mSettings.getUserIdLPr(uid1);
3379            if (obj != null) {
3380                if (obj instanceof SharedUserSetting) {
3381                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3382                } else if (obj instanceof PackageSetting) {
3383                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3384                } else {
3385                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3386                }
3387            } else {
3388                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3389            }
3390            obj = mSettings.getUserIdLPr(uid2);
3391            if (obj != null) {
3392                if (obj instanceof SharedUserSetting) {
3393                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3394                } else if (obj instanceof PackageSetting) {
3395                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3396                } else {
3397                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3398                }
3399            } else {
3400                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3401            }
3402            return compareSignatures(s1, s2);
3403        }
3404    }
3405
3406    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3407        final long identity = Binder.clearCallingIdentity();
3408        try {
3409            if (sb instanceof SharedUserSetting) {
3410                SharedUserSetting sus = (SharedUserSetting) sb;
3411                final int packageCount = sus.packages.size();
3412                for (int i = 0; i < packageCount; i++) {
3413                    PackageSetting susPs = sus.packages.valueAt(i);
3414                    if (userId == UserHandle.USER_ALL) {
3415                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3416                    } else {
3417                        final int uid = UserHandle.getUid(userId, susPs.appId);
3418                        killUid(uid, reason);
3419                    }
3420                }
3421            } else if (sb instanceof PackageSetting) {
3422                PackageSetting ps = (PackageSetting) sb;
3423                if (userId == UserHandle.USER_ALL) {
3424                    killApplication(ps.pkg.packageName, ps.appId, reason);
3425                } else {
3426                    final int uid = UserHandle.getUid(userId, ps.appId);
3427                    killUid(uid, reason);
3428                }
3429            }
3430        } finally {
3431            Binder.restoreCallingIdentity(identity);
3432        }
3433    }
3434
3435    private static void killUid(int uid, String reason) {
3436        IActivityManager am = ActivityManagerNative.getDefault();
3437        if (am != null) {
3438            try {
3439                am.killUid(uid, reason);
3440            } catch (RemoteException e) {
3441                /* ignore - same process */
3442            }
3443        }
3444    }
3445
3446    /**
3447     * Compares two sets of signatures. Returns:
3448     * <br />
3449     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3450     * <br />
3451     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3452     * <br />
3453     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3454     * <br />
3455     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3456     * <br />
3457     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3458     */
3459    static int compareSignatures(Signature[] s1, Signature[] s2) {
3460        if (s1 == null) {
3461            return s2 == null
3462                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3463                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3464        }
3465
3466        if (s2 == null) {
3467            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3468        }
3469
3470        if (s1.length != s2.length) {
3471            return PackageManager.SIGNATURE_NO_MATCH;
3472        }
3473
3474        // Since both signature sets are of size 1, we can compare without HashSets.
3475        if (s1.length == 1) {
3476            return s1[0].equals(s2[0]) ?
3477                    PackageManager.SIGNATURE_MATCH :
3478                    PackageManager.SIGNATURE_NO_MATCH;
3479        }
3480
3481        ArraySet<Signature> set1 = new ArraySet<Signature>();
3482        for (Signature sig : s1) {
3483            set1.add(sig);
3484        }
3485        ArraySet<Signature> set2 = new ArraySet<Signature>();
3486        for (Signature sig : s2) {
3487            set2.add(sig);
3488        }
3489        // Make sure s2 contains all signatures in s1.
3490        if (set1.equals(set2)) {
3491            return PackageManager.SIGNATURE_MATCH;
3492        }
3493        return PackageManager.SIGNATURE_NO_MATCH;
3494    }
3495
3496    /**
3497     * If the database version for this type of package (internal storage or
3498     * external storage) is less than the version where package signatures
3499     * were updated, return true.
3500     */
3501    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3502        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3503                DatabaseVersion.SIGNATURE_END_ENTITY))
3504                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3505                        DatabaseVersion.SIGNATURE_END_ENTITY));
3506    }
3507
3508    /**
3509     * Used for backward compatibility to make sure any packages with
3510     * certificate chains get upgraded to the new style. {@code existingSigs}
3511     * will be in the old format (since they were stored on disk from before the
3512     * system upgrade) and {@code scannedSigs} will be in the newer format.
3513     */
3514    private int compareSignaturesCompat(PackageSignatures existingSigs,
3515            PackageParser.Package scannedPkg) {
3516        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3517            return PackageManager.SIGNATURE_NO_MATCH;
3518        }
3519
3520        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3521        for (Signature sig : existingSigs.mSignatures) {
3522            existingSet.add(sig);
3523        }
3524        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3525        for (Signature sig : scannedPkg.mSignatures) {
3526            try {
3527                Signature[] chainSignatures = sig.getChainSignatures();
3528                for (Signature chainSig : chainSignatures) {
3529                    scannedCompatSet.add(chainSig);
3530                }
3531            } catch (CertificateEncodingException e) {
3532                scannedCompatSet.add(sig);
3533            }
3534        }
3535        /*
3536         * Make sure the expanded scanned set contains all signatures in the
3537         * existing one.
3538         */
3539        if (scannedCompatSet.equals(existingSet)) {
3540            // Migrate the old signatures to the new scheme.
3541            existingSigs.assignSignatures(scannedPkg.mSignatures);
3542            // The new KeySets will be re-added later in the scanning process.
3543            synchronized (mPackages) {
3544                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3545            }
3546            return PackageManager.SIGNATURE_MATCH;
3547        }
3548        return PackageManager.SIGNATURE_NO_MATCH;
3549    }
3550
3551    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3552        if (isExternal(scannedPkg)) {
3553            return mSettings.isExternalDatabaseVersionOlderThan(
3554                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3555        } else {
3556            return mSettings.isInternalDatabaseVersionOlderThan(
3557                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3558        }
3559    }
3560
3561    private int compareSignaturesRecover(PackageSignatures existingSigs,
3562            PackageParser.Package scannedPkg) {
3563        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3564            return PackageManager.SIGNATURE_NO_MATCH;
3565        }
3566
3567        String msg = null;
3568        try {
3569            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3570                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3571                        + scannedPkg.packageName);
3572                return PackageManager.SIGNATURE_MATCH;
3573            }
3574        } catch (CertificateException e) {
3575            msg = e.getMessage();
3576        }
3577
3578        logCriticalInfo(Log.INFO,
3579                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3580        return PackageManager.SIGNATURE_NO_MATCH;
3581    }
3582
3583    @Override
3584    public String[] getPackagesForUid(int uid) {
3585        uid = UserHandle.getAppId(uid);
3586        // reader
3587        synchronized (mPackages) {
3588            Object obj = mSettings.getUserIdLPr(uid);
3589            if (obj instanceof SharedUserSetting) {
3590                final SharedUserSetting sus = (SharedUserSetting) obj;
3591                final int N = sus.packages.size();
3592                final String[] res = new String[N];
3593                final Iterator<PackageSetting> it = sus.packages.iterator();
3594                int i = 0;
3595                while (it.hasNext()) {
3596                    res[i++] = it.next().name;
3597                }
3598                return res;
3599            } else if (obj instanceof PackageSetting) {
3600                final PackageSetting ps = (PackageSetting) obj;
3601                return new String[] { ps.name };
3602            }
3603        }
3604        return null;
3605    }
3606
3607    @Override
3608    public String getNameForUid(int uid) {
3609        // reader
3610        synchronized (mPackages) {
3611            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3612            if (obj instanceof SharedUserSetting) {
3613                final SharedUserSetting sus = (SharedUserSetting) obj;
3614                return sus.name + ":" + sus.userId;
3615            } else if (obj instanceof PackageSetting) {
3616                final PackageSetting ps = (PackageSetting) obj;
3617                return ps.name;
3618            }
3619        }
3620        return null;
3621    }
3622
3623    @Override
3624    public int getUidForSharedUser(String sharedUserName) {
3625        if(sharedUserName == null) {
3626            return -1;
3627        }
3628        // reader
3629        synchronized (mPackages) {
3630            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
3631            if (suid == null) {
3632                return -1;
3633            }
3634            return suid.userId;
3635        }
3636    }
3637
3638    @Override
3639    public int getFlagsForUid(int uid) {
3640        synchronized (mPackages) {
3641            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3642            if (obj instanceof SharedUserSetting) {
3643                final SharedUserSetting sus = (SharedUserSetting) obj;
3644                return sus.pkgFlags;
3645            } else if (obj instanceof PackageSetting) {
3646                final PackageSetting ps = (PackageSetting) obj;
3647                return ps.pkgFlags;
3648            }
3649        }
3650        return 0;
3651    }
3652
3653    @Override
3654    public int getPrivateFlagsForUid(int uid) {
3655        synchronized (mPackages) {
3656            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3657            if (obj instanceof SharedUserSetting) {
3658                final SharedUserSetting sus = (SharedUserSetting) obj;
3659                return sus.pkgPrivateFlags;
3660            } else if (obj instanceof PackageSetting) {
3661                final PackageSetting ps = (PackageSetting) obj;
3662                return ps.pkgPrivateFlags;
3663            }
3664        }
3665        return 0;
3666    }
3667
3668    @Override
3669    public boolean isUidPrivileged(int uid) {
3670        uid = UserHandle.getAppId(uid);
3671        // reader
3672        synchronized (mPackages) {
3673            Object obj = mSettings.getUserIdLPr(uid);
3674            if (obj instanceof SharedUserSetting) {
3675                final SharedUserSetting sus = (SharedUserSetting) obj;
3676                final Iterator<PackageSetting> it = sus.packages.iterator();
3677                while (it.hasNext()) {
3678                    if (it.next().isPrivileged()) {
3679                        return true;
3680                    }
3681                }
3682            } else if (obj instanceof PackageSetting) {
3683                final PackageSetting ps = (PackageSetting) obj;
3684                return ps.isPrivileged();
3685            }
3686        }
3687        return false;
3688    }
3689
3690    @Override
3691    public String[] getAppOpPermissionPackages(String permissionName) {
3692        synchronized (mPackages) {
3693            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
3694            if (pkgs == null) {
3695                return null;
3696            }
3697            return pkgs.toArray(new String[pkgs.size()]);
3698        }
3699    }
3700
3701    @Override
3702    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3703            int flags, int userId) {
3704        if (!sUserManager.exists(userId)) return null;
3705        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
3706        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3707        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3708    }
3709
3710    @Override
3711    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3712            IntentFilter filter, int match, ComponentName activity) {
3713        final int userId = UserHandle.getCallingUserId();
3714        if (DEBUG_PREFERRED) {
3715            Log.v(TAG, "setLastChosenActivity intent=" + intent
3716                + " resolvedType=" + resolvedType
3717                + " flags=" + flags
3718                + " filter=" + filter
3719                + " match=" + match
3720                + " activity=" + activity);
3721            filter.dump(new PrintStreamPrinter(System.out), "    ");
3722        }
3723        intent.setComponent(null);
3724        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3725        // Find any earlier preferred or last chosen entries and nuke them
3726        findPreferredActivity(intent, resolvedType,
3727                flags, query, 0, false, true, false, userId);
3728        // Add the new activity as the last chosen for this filter
3729        addPreferredActivityInternal(filter, match, null, activity, false, userId,
3730                "Setting last chosen");
3731    }
3732
3733    @Override
3734    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
3735        final int userId = UserHandle.getCallingUserId();
3736        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
3737        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3738        return findPreferredActivity(intent, resolvedType, flags, query, 0,
3739                false, false, false, userId);
3740    }
3741
3742    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
3743            int flags, List<ResolveInfo> query, int userId) {
3744        if (query != null) {
3745            final int N = query.size();
3746            if (N == 1) {
3747                return query.get(0);
3748            } else if (N > 1) {
3749                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3750                // If there is more than one activity with the same priority,
3751                // then let the user decide between them.
3752                ResolveInfo r0 = query.get(0);
3753                ResolveInfo r1 = query.get(1);
3754                if (DEBUG_INTENT_MATCHING || debug) {
3755                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
3756                            + r1.activityInfo.name + "=" + r1.priority);
3757                }
3758                // If the first activity has a higher priority, or a different
3759                // default, then it is always desireable to pick it.
3760                if (r0.priority != r1.priority
3761                        || r0.preferredOrder != r1.preferredOrder
3762                        || r0.isDefault != r1.isDefault) {
3763                    return query.get(0);
3764                }
3765                // If we have saved a preference for a preferred activity for
3766                // this Intent, use that.
3767                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3768                        flags, query, r0.priority, true, false, debug, userId);
3769                if (ri != null) {
3770                    return ri;
3771                }
3772                if (userId != 0) {
3773                    ri = new ResolveInfo(mResolveInfo);
3774                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3775                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3776                            ri.activityInfo.applicationInfo);
3777                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3778                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3779                    return ri;
3780                }
3781                return mResolveInfo;
3782            }
3783        }
3784        return null;
3785    }
3786
3787    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3788            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3789        final int N = query.size();
3790        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3791                .get(userId);
3792        // Get the list of persistent preferred activities that handle the intent
3793        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3794        List<PersistentPreferredActivity> pprefs = ppir != null
3795                ? ppir.queryIntent(intent, resolvedType,
3796                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3797                : null;
3798        if (pprefs != null && pprefs.size() > 0) {
3799            final int M = pprefs.size();
3800            for (int i=0; i<M; i++) {
3801                final PersistentPreferredActivity ppa = pprefs.get(i);
3802                if (DEBUG_PREFERRED || debug) {
3803                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3804                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3805                            + "\n  component=" + ppa.mComponent);
3806                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3807                }
3808                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3809                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3810                if (DEBUG_PREFERRED || debug) {
3811                    Slog.v(TAG, "Found persistent preferred activity:");
3812                    if (ai != null) {
3813                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3814                    } else {
3815                        Slog.v(TAG, "  null");
3816                    }
3817                }
3818                if (ai == null) {
3819                    // This previously registered persistent preferred activity
3820                    // component is no longer known. Ignore it and do NOT remove it.
3821                    continue;
3822                }
3823                for (int j=0; j<N; j++) {
3824                    final ResolveInfo ri = query.get(j);
3825                    if (!ri.activityInfo.applicationInfo.packageName
3826                            .equals(ai.applicationInfo.packageName)) {
3827                        continue;
3828                    }
3829                    if (!ri.activityInfo.name.equals(ai.name)) {
3830                        continue;
3831                    }
3832                    //  Found a persistent preference that can handle the intent.
3833                    if (DEBUG_PREFERRED || debug) {
3834                        Slog.v(TAG, "Returning persistent preferred activity: " +
3835                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3836                    }
3837                    return ri;
3838                }
3839            }
3840        }
3841        return null;
3842    }
3843
3844    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3845            List<ResolveInfo> query, int priority, boolean always,
3846            boolean removeMatches, boolean debug, int userId) {
3847        if (!sUserManager.exists(userId)) return null;
3848        // writer
3849        synchronized (mPackages) {
3850            if (intent.getSelector() != null) {
3851                intent = intent.getSelector();
3852            }
3853            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3854
3855            // Try to find a matching persistent preferred activity.
3856            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3857                    debug, userId);
3858
3859            // If a persistent preferred activity matched, use it.
3860            if (pri != null) {
3861                return pri;
3862            }
3863
3864            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3865            // Get the list of preferred activities that handle the intent
3866            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3867            List<PreferredActivity> prefs = pir != null
3868                    ? pir.queryIntent(intent, resolvedType,
3869                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3870                    : null;
3871            if (prefs != null && prefs.size() > 0) {
3872                boolean changed = false;
3873                try {
3874                    // First figure out how good the original match set is.
3875                    // We will only allow preferred activities that came
3876                    // from the same match quality.
3877                    int match = 0;
3878
3879                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3880
3881                    final int N = query.size();
3882                    for (int j=0; j<N; j++) {
3883                        final ResolveInfo ri = query.get(j);
3884                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3885                                + ": 0x" + Integer.toHexString(match));
3886                        if (ri.match > match) {
3887                            match = ri.match;
3888                        }
3889                    }
3890
3891                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3892                            + Integer.toHexString(match));
3893
3894                    match &= IntentFilter.MATCH_CATEGORY_MASK;
3895                    final int M = prefs.size();
3896                    for (int i=0; i<M; i++) {
3897                        final PreferredActivity pa = prefs.get(i);
3898                        if (DEBUG_PREFERRED || debug) {
3899                            Slog.v(TAG, "Checking PreferredActivity ds="
3900                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3901                                    + "\n  component=" + pa.mPref.mComponent);
3902                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3903                        }
3904                        if (pa.mPref.mMatch != match) {
3905                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3906                                    + Integer.toHexString(pa.mPref.mMatch));
3907                            continue;
3908                        }
3909                        // If it's not an "always" type preferred activity and that's what we're
3910                        // looking for, skip it.
3911                        if (always && !pa.mPref.mAlways) {
3912                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3913                            continue;
3914                        }
3915                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3916                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3917                        if (DEBUG_PREFERRED || debug) {
3918                            Slog.v(TAG, "Found preferred activity:");
3919                            if (ai != null) {
3920                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3921                            } else {
3922                                Slog.v(TAG, "  null");
3923                            }
3924                        }
3925                        if (ai == null) {
3926                            // This previously registered preferred activity
3927                            // component is no longer known.  Most likely an update
3928                            // to the app was installed and in the new version this
3929                            // component no longer exists.  Clean it up by removing
3930                            // it from the preferred activities list, and skip it.
3931                            Slog.w(TAG, "Removing dangling preferred activity: "
3932                                    + pa.mPref.mComponent);
3933                            pir.removeFilter(pa);
3934                            changed = true;
3935                            continue;
3936                        }
3937                        for (int j=0; j<N; j++) {
3938                            final ResolveInfo ri = query.get(j);
3939                            if (!ri.activityInfo.applicationInfo.packageName
3940                                    .equals(ai.applicationInfo.packageName)) {
3941                                continue;
3942                            }
3943                            if (!ri.activityInfo.name.equals(ai.name)) {
3944                                continue;
3945                            }
3946
3947                            if (removeMatches) {
3948                                pir.removeFilter(pa);
3949                                changed = true;
3950                                if (DEBUG_PREFERRED) {
3951                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3952                                }
3953                                break;
3954                            }
3955
3956                            // Okay we found a previously set preferred or last chosen app.
3957                            // If the result set is different from when this
3958                            // was created, we need to clear it and re-ask the
3959                            // user their preference, if we're looking for an "always" type entry.
3960                            if (always && !pa.mPref.sameSet(query)) {
3961                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
3962                                        + intent + " type " + resolvedType);
3963                                if (DEBUG_PREFERRED) {
3964                                    Slog.v(TAG, "Removing preferred activity since set changed "
3965                                            + pa.mPref.mComponent);
3966                                }
3967                                pir.removeFilter(pa);
3968                                // Re-add the filter as a "last chosen" entry (!always)
3969                                PreferredActivity lastChosen = new PreferredActivity(
3970                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3971                                pir.addFilter(lastChosen);
3972                                changed = true;
3973                                return null;
3974                            }
3975
3976                            // Yay! Either the set matched or we're looking for the last chosen
3977                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3978                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3979                            return ri;
3980                        }
3981                    }
3982                } finally {
3983                    if (changed) {
3984                        if (DEBUG_PREFERRED) {
3985                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
3986                        }
3987                        scheduleWritePackageRestrictionsLocked(userId);
3988                    }
3989                }
3990            }
3991        }
3992        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3993        return null;
3994    }
3995
3996    /*
3997     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3998     */
3999    @Override
4000    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4001            int targetUserId) {
4002        mContext.enforceCallingOrSelfPermission(
4003                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4004        List<CrossProfileIntentFilter> matches =
4005                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4006        if (matches != null) {
4007            int size = matches.size();
4008            for (int i = 0; i < size; i++) {
4009                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4010            }
4011        }
4012        return false;
4013    }
4014
4015    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4016            String resolvedType, int userId) {
4017        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4018        if (resolver != null) {
4019            return resolver.queryIntent(intent, resolvedType, false, userId);
4020        }
4021        return null;
4022    }
4023
4024    @Override
4025    public List<ResolveInfo> queryIntentActivities(Intent intent,
4026            String resolvedType, int flags, int userId) {
4027        if (!sUserManager.exists(userId)) return Collections.emptyList();
4028        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4029        ComponentName comp = intent.getComponent();
4030        if (comp == null) {
4031            if (intent.getSelector() != null) {
4032                intent = intent.getSelector();
4033                comp = intent.getComponent();
4034            }
4035        }
4036
4037        if (comp != null) {
4038            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4039            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4040            if (ai != null) {
4041                final ResolveInfo ri = new ResolveInfo();
4042                ri.activityInfo = ai;
4043                list.add(ri);
4044            }
4045            return list;
4046        }
4047
4048        // reader
4049        synchronized (mPackages) {
4050            final String pkgName = intent.getPackage();
4051            if (pkgName == null) {
4052                List<CrossProfileIntentFilter> matchingFilters =
4053                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4054                // Check for results that need to skip the current profile.
4055                ResolveInfo resolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4056                        resolvedType, flags, userId);
4057                if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) {
4058                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4059                    result.add(resolveInfo);
4060                    return filterIfNotPrimaryUser(result, userId);
4061                }
4062
4063                // Check for results in the current profile.
4064                List<ResolveInfo> result = mActivities.queryIntent(
4065                        intent, resolvedType, flags, userId);
4066
4067                // Check for cross profile results.
4068                resolveInfo = queryCrossProfileIntents(
4069                        matchingFilters, intent, resolvedType, flags, userId);
4070                if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) {
4071                    result.add(resolveInfo);
4072                    Collections.sort(result, mResolvePrioritySorter);
4073                }
4074                result = filterIfNotPrimaryUser(result, userId);
4075                if (result.size() > 1 && hasWebURI(intent)) {
4076                    return filterCandidatesWithDomainPreferedActivitiesLPr(flags, result);
4077                }
4078                return result;
4079            }
4080            final PackageParser.Package pkg = mPackages.get(pkgName);
4081            if (pkg != null) {
4082                return filterIfNotPrimaryUser(
4083                        mActivities.queryIntentForPackage(
4084                                intent, resolvedType, flags, pkg.activities, userId),
4085                        userId);
4086            }
4087            return new ArrayList<ResolveInfo>();
4088        }
4089    }
4090
4091    private boolean isUserEnabled(int userId) {
4092        long callingId = Binder.clearCallingIdentity();
4093        try {
4094            UserInfo userInfo = sUserManager.getUserInfo(userId);
4095            return userInfo != null && userInfo.isEnabled();
4096        } finally {
4097            Binder.restoreCallingIdentity(callingId);
4098        }
4099    }
4100
4101    /**
4102     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4103     *
4104     * @return filtered list
4105     */
4106    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4107        if (userId == UserHandle.USER_OWNER) {
4108            return resolveInfos;
4109        }
4110        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4111            ResolveInfo info = resolveInfos.get(i);
4112            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4113                resolveInfos.remove(i);
4114            }
4115        }
4116        return resolveInfos;
4117    }
4118
4119    private static boolean hasWebURI(Intent intent) {
4120        if (intent.getData() == null) {
4121            return false;
4122        }
4123        final String scheme = intent.getScheme();
4124        if (TextUtils.isEmpty(scheme)) {
4125            return false;
4126        }
4127        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4128    }
4129
4130    private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPr(
4131            int flags, List<ResolveInfo> candidates) {
4132        if (DEBUG_PREFERRED) {
4133            Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " +
4134                    candidates.size());
4135        }
4136
4137        final int userId = UserHandle.getCallingUserId();
4138        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4139        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4140        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4141        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4142        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4143
4144        synchronized (mPackages) {
4145            final int count = candidates.size();
4146            // First, try to use the domain prefered App. Partition the candidates into four lists:
4147            // one for the final results, one for the "do not use ever", one for "undefined status"
4148            // and finally one for "Browser App type".
4149            for (int n=0; n<count; n++) {
4150                ResolveInfo info = candidates.get(n);
4151                String packageName = info.activityInfo.packageName;
4152                PackageSetting ps = mSettings.mPackages.get(packageName);
4153                if (ps != null) {
4154                    // Add to the special match all list (Browser use case)
4155                    if (info.handleAllWebDataURI) {
4156                        matchAllList.add(info);
4157                        continue;
4158                    }
4159                    // Try to get the status from User settings first
4160                    int status = getDomainVerificationStatusLPr(ps, userId);
4161                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4162                        alwaysList.add(info);
4163                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4164                        neverList.add(info);
4165                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4166                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4167                        undefinedList.add(info);
4168                    }
4169                }
4170            }
4171            // First try to add the "always" if there is any
4172            if (alwaysList.size() > 0) {
4173                result.addAll(alwaysList);
4174            } else {
4175                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4176                result.addAll(undefinedList);
4177                // Also add Browsers (all of them or only the default one)
4178                if ((flags & MATCH_ALL) != 0) {
4179                    result.addAll(matchAllList);
4180                } else {
4181                    // Try to add the Default Browser if we can
4182                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(
4183                            UserHandle.myUserId());
4184                    if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
4185                        boolean defaultBrowserFound = false;
4186                        final int browserCount = matchAllList.size();
4187                        for (int n=0; n<browserCount; n++) {
4188                            ResolveInfo browser = matchAllList.get(n);
4189                            if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4190                                result.add(browser);
4191                                defaultBrowserFound = true;
4192                                break;
4193                            }
4194                        }
4195                        if (!defaultBrowserFound) {
4196                            result.addAll(matchAllList);
4197                        }
4198                    } else {
4199                        result.addAll(matchAllList);
4200                    }
4201                }
4202
4203                // If there is nothing selected, add all candidates and remove the ones that the User
4204                // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4205                if (result.size() == 0) {
4206                    result.addAll(candidates);
4207                    result.removeAll(neverList);
4208                }
4209            }
4210        }
4211        if (DEBUG_PREFERRED) {
4212            Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " +
4213                    result.size());
4214        }
4215        return result;
4216    }
4217
4218    private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4219        int status = ps.getDomainVerificationStatusForUser(userId);
4220        // if none available, get the master status
4221        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4222            if (ps.getIntentFilterVerificationInfo() != null) {
4223                status = ps.getIntentFilterVerificationInfo().getStatus();
4224            }
4225        }
4226        return status;
4227    }
4228
4229    private ResolveInfo querySkipCurrentProfileIntents(
4230            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4231            int flags, int sourceUserId) {
4232        if (matchingFilters != null) {
4233            int size = matchingFilters.size();
4234            for (int i = 0; i < size; i ++) {
4235                CrossProfileIntentFilter filter = matchingFilters.get(i);
4236                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4237                    // Checking if there are activities in the target user that can handle the
4238                    // intent.
4239                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4240                            flags, sourceUserId);
4241                    if (resolveInfo != null) {
4242                        return resolveInfo;
4243                    }
4244                }
4245            }
4246        }
4247        return null;
4248    }
4249
4250    // Return matching ResolveInfo if any for skip current profile intent filters.
4251    private ResolveInfo queryCrossProfileIntents(
4252            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4253            int flags, int sourceUserId) {
4254        if (matchingFilters != null) {
4255            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4256            // match the same intent. For performance reasons, it is better not to
4257            // run queryIntent twice for the same userId
4258            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4259            int size = matchingFilters.size();
4260            for (int i = 0; i < size; i++) {
4261                CrossProfileIntentFilter filter = matchingFilters.get(i);
4262                int targetUserId = filter.getTargetUserId();
4263                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4264                        && !alreadyTriedUserIds.get(targetUserId)) {
4265                    // Checking if there are activities in the target user that can handle the
4266                    // intent.
4267                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4268                            flags, sourceUserId);
4269                    if (resolveInfo != null) return resolveInfo;
4270                    alreadyTriedUserIds.put(targetUserId, true);
4271                }
4272            }
4273        }
4274        return null;
4275    }
4276
4277    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4278            String resolvedType, int flags, int sourceUserId) {
4279        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4280                resolvedType, flags, filter.getTargetUserId());
4281        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4282            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4283        }
4284        return null;
4285    }
4286
4287    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4288            int sourceUserId, int targetUserId) {
4289        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4290        String className;
4291        if (targetUserId == UserHandle.USER_OWNER) {
4292            className = FORWARD_INTENT_TO_USER_OWNER;
4293        } else {
4294            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4295        }
4296        ComponentName forwardingActivityComponentName = new ComponentName(
4297                mAndroidApplication.packageName, className);
4298        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4299                sourceUserId);
4300        if (targetUserId == UserHandle.USER_OWNER) {
4301            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4302            forwardingResolveInfo.noResourceId = true;
4303        }
4304        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4305        forwardingResolveInfo.priority = 0;
4306        forwardingResolveInfo.preferredOrder = 0;
4307        forwardingResolveInfo.match = 0;
4308        forwardingResolveInfo.isDefault = true;
4309        forwardingResolveInfo.filter = filter;
4310        forwardingResolveInfo.targetUserId = targetUserId;
4311        return forwardingResolveInfo;
4312    }
4313
4314    @Override
4315    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4316            Intent[] specifics, String[] specificTypes, Intent intent,
4317            String resolvedType, int flags, int userId) {
4318        if (!sUserManager.exists(userId)) return Collections.emptyList();
4319        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4320                false, "query intent activity options");
4321        final String resultsAction = intent.getAction();
4322
4323        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4324                | PackageManager.GET_RESOLVED_FILTER, userId);
4325
4326        if (DEBUG_INTENT_MATCHING) {
4327            Log.v(TAG, "Query " + intent + ": " + results);
4328        }
4329
4330        int specificsPos = 0;
4331        int N;
4332
4333        // todo: note that the algorithm used here is O(N^2).  This
4334        // isn't a problem in our current environment, but if we start running
4335        // into situations where we have more than 5 or 10 matches then this
4336        // should probably be changed to something smarter...
4337
4338        // First we go through and resolve each of the specific items
4339        // that were supplied, taking care of removing any corresponding
4340        // duplicate items in the generic resolve list.
4341        if (specifics != null) {
4342            for (int i=0; i<specifics.length; i++) {
4343                final Intent sintent = specifics[i];
4344                if (sintent == null) {
4345                    continue;
4346                }
4347
4348                if (DEBUG_INTENT_MATCHING) {
4349                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4350                }
4351
4352                String action = sintent.getAction();
4353                if (resultsAction != null && resultsAction.equals(action)) {
4354                    // If this action was explicitly requested, then don't
4355                    // remove things that have it.
4356                    action = null;
4357                }
4358
4359                ResolveInfo ri = null;
4360                ActivityInfo ai = null;
4361
4362                ComponentName comp = sintent.getComponent();
4363                if (comp == null) {
4364                    ri = resolveIntent(
4365                        sintent,
4366                        specificTypes != null ? specificTypes[i] : null,
4367                            flags, userId);
4368                    if (ri == null) {
4369                        continue;
4370                    }
4371                    if (ri == mResolveInfo) {
4372                        // ACK!  Must do something better with this.
4373                    }
4374                    ai = ri.activityInfo;
4375                    comp = new ComponentName(ai.applicationInfo.packageName,
4376                            ai.name);
4377                } else {
4378                    ai = getActivityInfo(comp, flags, userId);
4379                    if (ai == null) {
4380                        continue;
4381                    }
4382                }
4383
4384                // Look for any generic query activities that are duplicates
4385                // of this specific one, and remove them from the results.
4386                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4387                N = results.size();
4388                int j;
4389                for (j=specificsPos; j<N; j++) {
4390                    ResolveInfo sri = results.get(j);
4391                    if ((sri.activityInfo.name.equals(comp.getClassName())
4392                            && sri.activityInfo.applicationInfo.packageName.equals(
4393                                    comp.getPackageName()))
4394                        || (action != null && sri.filter.matchAction(action))) {
4395                        results.remove(j);
4396                        if (DEBUG_INTENT_MATCHING) Log.v(
4397                            TAG, "Removing duplicate item from " + j
4398                            + " due to specific " + specificsPos);
4399                        if (ri == null) {
4400                            ri = sri;
4401                        }
4402                        j--;
4403                        N--;
4404                    }
4405                }
4406
4407                // Add this specific item to its proper place.
4408                if (ri == null) {
4409                    ri = new ResolveInfo();
4410                    ri.activityInfo = ai;
4411                }
4412                results.add(specificsPos, ri);
4413                ri.specificIndex = i;
4414                specificsPos++;
4415            }
4416        }
4417
4418        // Now we go through the remaining generic results and remove any
4419        // duplicate actions that are found here.
4420        N = results.size();
4421        for (int i=specificsPos; i<N-1; i++) {
4422            final ResolveInfo rii = results.get(i);
4423            if (rii.filter == null) {
4424                continue;
4425            }
4426
4427            // Iterate over all of the actions of this result's intent
4428            // filter...  typically this should be just one.
4429            final Iterator<String> it = rii.filter.actionsIterator();
4430            if (it == null) {
4431                continue;
4432            }
4433            while (it.hasNext()) {
4434                final String action = it.next();
4435                if (resultsAction != null && resultsAction.equals(action)) {
4436                    // If this action was explicitly requested, then don't
4437                    // remove things that have it.
4438                    continue;
4439                }
4440                for (int j=i+1; j<N; j++) {
4441                    final ResolveInfo rij = results.get(j);
4442                    if (rij.filter != null && rij.filter.hasAction(action)) {
4443                        results.remove(j);
4444                        if (DEBUG_INTENT_MATCHING) Log.v(
4445                            TAG, "Removing duplicate item from " + j
4446                            + " due to action " + action + " at " + i);
4447                        j--;
4448                        N--;
4449                    }
4450                }
4451            }
4452
4453            // If the caller didn't request filter information, drop it now
4454            // so we don't have to marshall/unmarshall it.
4455            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4456                rii.filter = null;
4457            }
4458        }
4459
4460        // Filter out the caller activity if so requested.
4461        if (caller != null) {
4462            N = results.size();
4463            for (int i=0; i<N; i++) {
4464                ActivityInfo ainfo = results.get(i).activityInfo;
4465                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
4466                        && caller.getClassName().equals(ainfo.name)) {
4467                    results.remove(i);
4468                    break;
4469                }
4470            }
4471        }
4472
4473        // If the caller didn't request filter information,
4474        // drop them now so we don't have to
4475        // marshall/unmarshall it.
4476        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4477            N = results.size();
4478            for (int i=0; i<N; i++) {
4479                results.get(i).filter = null;
4480            }
4481        }
4482
4483        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
4484        return results;
4485    }
4486
4487    @Override
4488    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
4489            int userId) {
4490        if (!sUserManager.exists(userId)) return Collections.emptyList();
4491        ComponentName comp = intent.getComponent();
4492        if (comp == null) {
4493            if (intent.getSelector() != null) {
4494                intent = intent.getSelector();
4495                comp = intent.getComponent();
4496            }
4497        }
4498        if (comp != null) {
4499            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4500            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
4501            if (ai != null) {
4502                ResolveInfo ri = new ResolveInfo();
4503                ri.activityInfo = ai;
4504                list.add(ri);
4505            }
4506            return list;
4507        }
4508
4509        // reader
4510        synchronized (mPackages) {
4511            String pkgName = intent.getPackage();
4512            if (pkgName == null) {
4513                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
4514            }
4515            final PackageParser.Package pkg = mPackages.get(pkgName);
4516            if (pkg != null) {
4517                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
4518                        userId);
4519            }
4520            return null;
4521        }
4522    }
4523
4524    @Override
4525    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
4526        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
4527        if (!sUserManager.exists(userId)) return null;
4528        if (query != null) {
4529            if (query.size() >= 1) {
4530                // If there is more than one service with the same priority,
4531                // just arbitrarily pick the first one.
4532                return query.get(0);
4533            }
4534        }
4535        return null;
4536    }
4537
4538    @Override
4539    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
4540            int userId) {
4541        if (!sUserManager.exists(userId)) return Collections.emptyList();
4542        ComponentName comp = intent.getComponent();
4543        if (comp == null) {
4544            if (intent.getSelector() != null) {
4545                intent = intent.getSelector();
4546                comp = intent.getComponent();
4547            }
4548        }
4549        if (comp != null) {
4550            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4551            final ServiceInfo si = getServiceInfo(comp, flags, userId);
4552            if (si != null) {
4553                final ResolveInfo ri = new ResolveInfo();
4554                ri.serviceInfo = si;
4555                list.add(ri);
4556            }
4557            return list;
4558        }
4559
4560        // reader
4561        synchronized (mPackages) {
4562            String pkgName = intent.getPackage();
4563            if (pkgName == null) {
4564                return mServices.queryIntent(intent, resolvedType, flags, userId);
4565            }
4566            final PackageParser.Package pkg = mPackages.get(pkgName);
4567            if (pkg != null) {
4568                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
4569                        userId);
4570            }
4571            return null;
4572        }
4573    }
4574
4575    @Override
4576    public List<ResolveInfo> queryIntentContentProviders(
4577            Intent intent, String resolvedType, int flags, int userId) {
4578        if (!sUserManager.exists(userId)) return Collections.emptyList();
4579        ComponentName comp = intent.getComponent();
4580        if (comp == null) {
4581            if (intent.getSelector() != null) {
4582                intent = intent.getSelector();
4583                comp = intent.getComponent();
4584            }
4585        }
4586        if (comp != null) {
4587            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4588            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
4589            if (pi != null) {
4590                final ResolveInfo ri = new ResolveInfo();
4591                ri.providerInfo = pi;
4592                list.add(ri);
4593            }
4594            return list;
4595        }
4596
4597        // reader
4598        synchronized (mPackages) {
4599            String pkgName = intent.getPackage();
4600            if (pkgName == null) {
4601                return mProviders.queryIntent(intent, resolvedType, flags, userId);
4602            }
4603            final PackageParser.Package pkg = mPackages.get(pkgName);
4604            if (pkg != null) {
4605                return mProviders.queryIntentForPackage(
4606                        intent, resolvedType, flags, pkg.providers, userId);
4607            }
4608            return null;
4609        }
4610    }
4611
4612    @Override
4613    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
4614        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4615
4616        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
4617
4618        // writer
4619        synchronized (mPackages) {
4620            ArrayList<PackageInfo> list;
4621            if (listUninstalled) {
4622                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
4623                for (PackageSetting ps : mSettings.mPackages.values()) {
4624                    PackageInfo pi;
4625                    if (ps.pkg != null) {
4626                        pi = generatePackageInfo(ps.pkg, flags, userId);
4627                    } else {
4628                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4629                    }
4630                    if (pi != null) {
4631                        list.add(pi);
4632                    }
4633                }
4634            } else {
4635                list = new ArrayList<PackageInfo>(mPackages.size());
4636                for (PackageParser.Package p : mPackages.values()) {
4637                    PackageInfo pi = generatePackageInfo(p, flags, userId);
4638                    if (pi != null) {
4639                        list.add(pi);
4640                    }
4641                }
4642            }
4643
4644            return new ParceledListSlice<PackageInfo>(list);
4645        }
4646    }
4647
4648    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
4649            String[] permissions, boolean[] tmp, int flags, int userId) {
4650        int numMatch = 0;
4651        final PermissionsState permissionsState = ps.getPermissionsState();
4652        for (int i=0; i<permissions.length; i++) {
4653            final String permission = permissions[i];
4654            if (permissionsState.hasPermission(permission, userId)) {
4655                tmp[i] = true;
4656                numMatch++;
4657            } else {
4658                tmp[i] = false;
4659            }
4660        }
4661        if (numMatch == 0) {
4662            return;
4663        }
4664        PackageInfo pi;
4665        if (ps.pkg != null) {
4666            pi = generatePackageInfo(ps.pkg, flags, userId);
4667        } else {
4668            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4669        }
4670        // The above might return null in cases of uninstalled apps or install-state
4671        // skew across users/profiles.
4672        if (pi != null) {
4673            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
4674                if (numMatch == permissions.length) {
4675                    pi.requestedPermissions = permissions;
4676                } else {
4677                    pi.requestedPermissions = new String[numMatch];
4678                    numMatch = 0;
4679                    for (int i=0; i<permissions.length; i++) {
4680                        if (tmp[i]) {
4681                            pi.requestedPermissions[numMatch] = permissions[i];
4682                            numMatch++;
4683                        }
4684                    }
4685                }
4686            }
4687            list.add(pi);
4688        }
4689    }
4690
4691    @Override
4692    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
4693            String[] permissions, int flags, int userId) {
4694        if (!sUserManager.exists(userId)) return null;
4695        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4696
4697        // writer
4698        synchronized (mPackages) {
4699            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
4700            boolean[] tmpBools = new boolean[permissions.length];
4701            if (listUninstalled) {
4702                for (PackageSetting ps : mSettings.mPackages.values()) {
4703                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
4704                }
4705            } else {
4706                for (PackageParser.Package pkg : mPackages.values()) {
4707                    PackageSetting ps = (PackageSetting)pkg.mExtras;
4708                    if (ps != null) {
4709                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
4710                                userId);
4711                    }
4712                }
4713            }
4714
4715            return new ParceledListSlice<PackageInfo>(list);
4716        }
4717    }
4718
4719    @Override
4720    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
4721        if (!sUserManager.exists(userId)) return null;
4722        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4723
4724        // writer
4725        synchronized (mPackages) {
4726            ArrayList<ApplicationInfo> list;
4727            if (listUninstalled) {
4728                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
4729                for (PackageSetting ps : mSettings.mPackages.values()) {
4730                    ApplicationInfo ai;
4731                    if (ps.pkg != null) {
4732                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4733                                ps.readUserState(userId), userId);
4734                    } else {
4735                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
4736                    }
4737                    if (ai != null) {
4738                        list.add(ai);
4739                    }
4740                }
4741            } else {
4742                list = new ArrayList<ApplicationInfo>(mPackages.size());
4743                for (PackageParser.Package p : mPackages.values()) {
4744                    if (p.mExtras != null) {
4745                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4746                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
4747                        if (ai != null) {
4748                            list.add(ai);
4749                        }
4750                    }
4751                }
4752            }
4753
4754            return new ParceledListSlice<ApplicationInfo>(list);
4755        }
4756    }
4757
4758    public List<ApplicationInfo> getPersistentApplications(int flags) {
4759        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
4760
4761        // reader
4762        synchronized (mPackages) {
4763            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
4764            final int userId = UserHandle.getCallingUserId();
4765            while (i.hasNext()) {
4766                final PackageParser.Package p = i.next();
4767                if (p.applicationInfo != null
4768                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
4769                        && (!mSafeMode || isSystemApp(p))) {
4770                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
4771                    if (ps != null) {
4772                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4773                                ps.readUserState(userId), userId);
4774                        if (ai != null) {
4775                            finalList.add(ai);
4776                        }
4777                    }
4778                }
4779            }
4780        }
4781
4782        return finalList;
4783    }
4784
4785    @Override
4786    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
4787        if (!sUserManager.exists(userId)) return null;
4788        // reader
4789        synchronized (mPackages) {
4790            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
4791            PackageSetting ps = provider != null
4792                    ? mSettings.mPackages.get(provider.owner.packageName)
4793                    : null;
4794            return ps != null
4795                    && mSettings.isEnabledLPr(provider.info, flags, userId)
4796                    && (!mSafeMode || (provider.info.applicationInfo.flags
4797                            &ApplicationInfo.FLAG_SYSTEM) != 0)
4798                    ? PackageParser.generateProviderInfo(provider, flags,
4799                            ps.readUserState(userId), userId)
4800                    : null;
4801        }
4802    }
4803
4804    /**
4805     * @deprecated
4806     */
4807    @Deprecated
4808    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
4809        // reader
4810        synchronized (mPackages) {
4811            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
4812                    .entrySet().iterator();
4813            final int userId = UserHandle.getCallingUserId();
4814            while (i.hasNext()) {
4815                Map.Entry<String, PackageParser.Provider> entry = i.next();
4816                PackageParser.Provider p = entry.getValue();
4817                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4818
4819                if (ps != null && p.syncable
4820                        && (!mSafeMode || (p.info.applicationInfo.flags
4821                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
4822                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
4823                            ps.readUserState(userId), userId);
4824                    if (info != null) {
4825                        outNames.add(entry.getKey());
4826                        outInfo.add(info);
4827                    }
4828                }
4829            }
4830        }
4831    }
4832
4833    @Override
4834    public List<ProviderInfo> queryContentProviders(String processName,
4835            int uid, int flags) {
4836        ArrayList<ProviderInfo> finalList = null;
4837        // reader
4838        synchronized (mPackages) {
4839            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
4840            final int userId = processName != null ?
4841                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
4842            while (i.hasNext()) {
4843                final PackageParser.Provider p = i.next();
4844                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4845                if (ps != null && p.info.authority != null
4846                        && (processName == null
4847                                || (p.info.processName.equals(processName)
4848                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
4849                        && mSettings.isEnabledLPr(p.info, flags, userId)
4850                        && (!mSafeMode
4851                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
4852                    if (finalList == null) {
4853                        finalList = new ArrayList<ProviderInfo>(3);
4854                    }
4855                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
4856                            ps.readUserState(userId), userId);
4857                    if (info != null) {
4858                        finalList.add(info);
4859                    }
4860                }
4861            }
4862        }
4863
4864        if (finalList != null) {
4865            Collections.sort(finalList, mProviderInitOrderSorter);
4866        }
4867
4868        return finalList;
4869    }
4870
4871    @Override
4872    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
4873            int flags) {
4874        // reader
4875        synchronized (mPackages) {
4876            final PackageParser.Instrumentation i = mInstrumentation.get(name);
4877            return PackageParser.generateInstrumentationInfo(i, flags);
4878        }
4879    }
4880
4881    @Override
4882    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4883            int flags) {
4884        ArrayList<InstrumentationInfo> finalList =
4885            new ArrayList<InstrumentationInfo>();
4886
4887        // reader
4888        synchronized (mPackages) {
4889            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4890            while (i.hasNext()) {
4891                final PackageParser.Instrumentation p = i.next();
4892                if (targetPackage == null
4893                        || targetPackage.equals(p.info.targetPackage)) {
4894                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4895                            flags);
4896                    if (ii != null) {
4897                        finalList.add(ii);
4898                    }
4899                }
4900            }
4901        }
4902
4903        return finalList;
4904    }
4905
4906    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4907        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4908        if (overlays == null) {
4909            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4910            return;
4911        }
4912        for (PackageParser.Package opkg : overlays.values()) {
4913            // Not much to do if idmap fails: we already logged the error
4914            // and we certainly don't want to abort installation of pkg simply
4915            // because an overlay didn't fit properly. For these reasons,
4916            // ignore the return value of createIdmapForPackagePairLI.
4917            createIdmapForPackagePairLI(pkg, opkg);
4918        }
4919    }
4920
4921    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4922            PackageParser.Package opkg) {
4923        if (!opkg.mTrustedOverlay) {
4924            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
4925                    opkg.baseCodePath + ": overlay not trusted");
4926            return false;
4927        }
4928        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4929        if (overlaySet == null) {
4930            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
4931                    opkg.baseCodePath + " but target package has no known overlays");
4932            return false;
4933        }
4934        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4935        // TODO: generate idmap for split APKs
4936        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
4937            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
4938                    + opkg.baseCodePath);
4939            return false;
4940        }
4941        PackageParser.Package[] overlayArray =
4942            overlaySet.values().toArray(new PackageParser.Package[0]);
4943        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4944            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4945                return p1.mOverlayPriority - p2.mOverlayPriority;
4946            }
4947        };
4948        Arrays.sort(overlayArray, cmp);
4949
4950        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4951        int i = 0;
4952        for (PackageParser.Package p : overlayArray) {
4953            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
4954        }
4955        return true;
4956    }
4957
4958    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
4959        final File[] files = dir.listFiles();
4960        if (ArrayUtils.isEmpty(files)) {
4961            Log.d(TAG, "No files in app dir " + dir);
4962            return;
4963        }
4964
4965        if (DEBUG_PACKAGE_SCANNING) {
4966            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
4967                    + " flags=0x" + Integer.toHexString(parseFlags));
4968        }
4969
4970        for (File file : files) {
4971            final boolean isPackage = (isApkFile(file) || file.isDirectory())
4972                    && !PackageInstallerService.isStageName(file.getName());
4973            if (!isPackage) {
4974                // Ignore entries which are not packages
4975                continue;
4976            }
4977            try {
4978                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
4979                        scanFlags, currentTime, null);
4980            } catch (PackageManagerException e) {
4981                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
4982
4983                // Delete invalid userdata apps
4984                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4985                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
4986                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
4987                    if (file.isDirectory()) {
4988                        mInstaller.rmPackageDir(file.getAbsolutePath());
4989                    } else {
4990                        file.delete();
4991                    }
4992                }
4993            }
4994        }
4995    }
4996
4997    private static File getSettingsProblemFile() {
4998        File dataDir = Environment.getDataDirectory();
4999        File systemDir = new File(dataDir, "system");
5000        File fname = new File(systemDir, "uiderrors.txt");
5001        return fname;
5002    }
5003
5004    static void reportSettingsProblem(int priority, String msg) {
5005        logCriticalInfo(priority, msg);
5006    }
5007
5008    static void logCriticalInfo(int priority, String msg) {
5009        Slog.println(priority, TAG, msg);
5010        EventLogTags.writePmCriticalInfo(msg);
5011        try {
5012            File fname = getSettingsProblemFile();
5013            FileOutputStream out = new FileOutputStream(fname, true);
5014            PrintWriter pw = new FastPrintWriter(out);
5015            SimpleDateFormat formatter = new SimpleDateFormat();
5016            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5017            pw.println(dateString + ": " + msg);
5018            pw.close();
5019            FileUtils.setPermissions(
5020                    fname.toString(),
5021                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5022                    -1, -1);
5023        } catch (java.io.IOException e) {
5024        }
5025    }
5026
5027    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5028            PackageParser.Package pkg, File srcFile, int parseFlags)
5029            throws PackageManagerException {
5030        if (ps != null
5031                && ps.codePath.equals(srcFile)
5032                && ps.timeStamp == srcFile.lastModified()
5033                && !isCompatSignatureUpdateNeeded(pkg)
5034                && !isRecoverSignatureUpdateNeeded(pkg)) {
5035            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5036            if (ps.signatures.mSignatures != null
5037                    && ps.signatures.mSignatures.length != 0
5038                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
5039                // Optimization: reuse the existing cached certificates
5040                // if the package appears to be unchanged.
5041                pkg.mSignatures = ps.signatures.mSignatures;
5042                KeySetManagerService ksms = mSettings.mKeySetManagerService;
5043                synchronized (mPackages) {
5044                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5045                }
5046                return;
5047            }
5048
5049            Slog.w(TAG, "PackageSetting for " + ps.name
5050                    + " is missing signatures.  Collecting certs again to recover them.");
5051        } else {
5052            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5053        }
5054
5055        try {
5056            pp.collectCertificates(pkg, parseFlags);
5057            pp.collectManifestDigest(pkg);
5058        } catch (PackageParserException e) {
5059            throw PackageManagerException.from(e);
5060        }
5061    }
5062
5063    /*
5064     *  Scan a package and return the newly parsed package.
5065     *  Returns null in case of errors and the error code is stored in mLastScanError
5066     */
5067    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5068            long currentTime, UserHandle user) throws PackageManagerException {
5069        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5070        parseFlags |= mDefParseFlags;
5071        PackageParser pp = new PackageParser();
5072        pp.setSeparateProcesses(mSeparateProcesses);
5073        pp.setOnlyCoreApps(mOnlyCore);
5074        pp.setDisplayMetrics(mMetrics);
5075
5076        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5077            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5078        }
5079
5080        final PackageParser.Package pkg;
5081        try {
5082            pkg = pp.parsePackage(scanFile, parseFlags);
5083        } catch (PackageParserException e) {
5084            throw PackageManagerException.from(e);
5085        }
5086
5087        PackageSetting ps = null;
5088        PackageSetting updatedPkg;
5089        // reader
5090        synchronized (mPackages) {
5091            // Look to see if we already know about this package.
5092            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5093            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5094                // This package has been renamed to its original name.  Let's
5095                // use that.
5096                ps = mSettings.peekPackageLPr(oldName);
5097            }
5098            // If there was no original package, see one for the real package name.
5099            if (ps == null) {
5100                ps = mSettings.peekPackageLPr(pkg.packageName);
5101            }
5102            // Check to see if this package could be hiding/updating a system
5103            // package.  Must look for it either under the original or real
5104            // package name depending on our state.
5105            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5106            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5107        }
5108        boolean updatedPkgBetter = false;
5109        // First check if this is a system package that may involve an update
5110        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5111            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5112            // it needs to drop FLAG_PRIVILEGED.
5113            if (locationIsPrivileged(scanFile)) {
5114                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5115            } else {
5116                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5117            }
5118
5119            if (ps != null && !ps.codePath.equals(scanFile)) {
5120                // The path has changed from what was last scanned...  check the
5121                // version of the new path against what we have stored to determine
5122                // what to do.
5123                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5124                if (pkg.mVersionCode <= ps.versionCode) {
5125                    // The system package has been updated and the code path does not match
5126                    // Ignore entry. Skip it.
5127                    Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5128                            + " ignored: updated version " + ps.versionCode
5129                            + " better than this " + pkg.mVersionCode);
5130                    if (!updatedPkg.codePath.equals(scanFile)) {
5131                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5132                                + ps.name + " changing from " + updatedPkg.codePathString
5133                                + " to " + scanFile);
5134                        updatedPkg.codePath = scanFile;
5135                        updatedPkg.codePathString = scanFile.toString();
5136                        updatedPkg.resourcePath = scanFile;
5137                        updatedPkg.resourcePathString = scanFile.toString();
5138                    }
5139                    updatedPkg.pkg = pkg;
5140                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
5141                } else {
5142                    // The current app on the system partition is better than
5143                    // what we have updated to on the data partition; switch
5144                    // back to the system partition version.
5145                    // At this point, its safely assumed that package installation for
5146                    // apps in system partition will go through. If not there won't be a working
5147                    // version of the app
5148                    // writer
5149                    synchronized (mPackages) {
5150                        // Just remove the loaded entries from package lists.
5151                        mPackages.remove(ps.name);
5152                    }
5153
5154                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5155                            + " reverting from " + ps.codePathString
5156                            + ": new version " + pkg.mVersionCode
5157                            + " better than installed " + ps.versionCode);
5158
5159                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5160                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5161                    synchronized (mInstallLock) {
5162                        args.cleanUpResourcesLI();
5163                    }
5164                    synchronized (mPackages) {
5165                        mSettings.enableSystemPackageLPw(ps.name);
5166                    }
5167                    updatedPkgBetter = true;
5168                }
5169            }
5170        }
5171
5172        if (updatedPkg != null) {
5173            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5174            // initially
5175            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5176
5177            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5178            // flag set initially
5179            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5180                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5181            }
5182        }
5183
5184        // Verify certificates against what was last scanned
5185        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5186
5187        /*
5188         * A new system app appeared, but we already had a non-system one of the
5189         * same name installed earlier.
5190         */
5191        boolean shouldHideSystemApp = false;
5192        if (updatedPkg == null && ps != null
5193                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5194            /*
5195             * Check to make sure the signatures match first. If they don't,
5196             * wipe the installed application and its data.
5197             */
5198            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5199                    != PackageManager.SIGNATURE_MATCH) {
5200                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5201                        + " signatures don't match existing userdata copy; removing");
5202                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5203                ps = null;
5204            } else {
5205                /*
5206                 * If the newly-added system app is an older version than the
5207                 * already installed version, hide it. It will be scanned later
5208                 * and re-added like an update.
5209                 */
5210                if (pkg.mVersionCode <= ps.versionCode) {
5211                    shouldHideSystemApp = true;
5212                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5213                            + " but new version " + pkg.mVersionCode + " better than installed "
5214                            + ps.versionCode + "; hiding system");
5215                } else {
5216                    /*
5217                     * The newly found system app is a newer version that the
5218                     * one previously installed. Simply remove the
5219                     * already-installed application and replace it with our own
5220                     * while keeping the application data.
5221                     */
5222                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5223                            + " reverting from " + ps.codePathString + ": new version "
5224                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5225                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5226                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5227                    synchronized (mInstallLock) {
5228                        args.cleanUpResourcesLI();
5229                    }
5230                }
5231            }
5232        }
5233
5234        // The apk is forward locked (not public) if its code and resources
5235        // are kept in different files. (except for app in either system or
5236        // vendor path).
5237        // TODO grab this value from PackageSettings
5238        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5239            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5240                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5241            }
5242        }
5243
5244        // TODO: extend to support forward-locked splits
5245        String resourcePath = null;
5246        String baseResourcePath = null;
5247        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5248            if (ps != null && ps.resourcePathString != null) {
5249                resourcePath = ps.resourcePathString;
5250                baseResourcePath = ps.resourcePathString;
5251            } else {
5252                // Should not happen at all. Just log an error.
5253                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5254            }
5255        } else {
5256            resourcePath = pkg.codePath;
5257            baseResourcePath = pkg.baseCodePath;
5258        }
5259
5260        // Set application objects path explicitly.
5261        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5262        pkg.applicationInfo.setCodePath(pkg.codePath);
5263        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5264        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5265        pkg.applicationInfo.setResourcePath(resourcePath);
5266        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5267        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5268
5269        // Note that we invoke the following method only if we are about to unpack an application
5270        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5271                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5272
5273        /*
5274         * If the system app should be overridden by a previously installed
5275         * data, hide the system app now and let the /data/app scan pick it up
5276         * again.
5277         */
5278        if (shouldHideSystemApp) {
5279            synchronized (mPackages) {
5280                /*
5281                 * We have to grant systems permissions before we hide, because
5282                 * grantPermissions will assume the package update is trying to
5283                 * expand its permissions.
5284                 */
5285                grantPermissionsLPw(pkg, true, pkg.packageName);
5286                mSettings.disableSystemPackageLPw(pkg.packageName);
5287            }
5288        }
5289
5290        return scannedPkg;
5291    }
5292
5293    private static String fixProcessName(String defProcessName,
5294            String processName, int uid) {
5295        if (processName == null) {
5296            return defProcessName;
5297        }
5298        return processName;
5299    }
5300
5301    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5302            throws PackageManagerException {
5303        if (pkgSetting.signatures.mSignatures != null) {
5304            // Already existing package. Make sure signatures match
5305            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5306                    == PackageManager.SIGNATURE_MATCH;
5307            if (!match) {
5308                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5309                        == PackageManager.SIGNATURE_MATCH;
5310            }
5311            if (!match) {
5312                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5313                        == PackageManager.SIGNATURE_MATCH;
5314            }
5315            if (!match) {
5316                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5317                        + pkg.packageName + " signatures do not match the "
5318                        + "previously installed version; ignoring!");
5319            }
5320        }
5321
5322        // Check for shared user signatures
5323        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5324            // Already existing package. Make sure signatures match
5325            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5326                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5327            if (!match) {
5328                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5329                        == PackageManager.SIGNATURE_MATCH;
5330            }
5331            if (!match) {
5332                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5333                        == PackageManager.SIGNATURE_MATCH;
5334            }
5335            if (!match) {
5336                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5337                        "Package " + pkg.packageName
5338                        + " has no signatures that match those in shared user "
5339                        + pkgSetting.sharedUser.name + "; ignoring!");
5340            }
5341        }
5342    }
5343
5344    /**
5345     * Enforces that only the system UID or root's UID can call a method exposed
5346     * via Binder.
5347     *
5348     * @param message used as message if SecurityException is thrown
5349     * @throws SecurityException if the caller is not system or root
5350     */
5351    private static final void enforceSystemOrRoot(String message) {
5352        final int uid = Binder.getCallingUid();
5353        if (uid != Process.SYSTEM_UID && uid != 0) {
5354            throw new SecurityException(message);
5355        }
5356    }
5357
5358    @Override
5359    public void performBootDexOpt() {
5360        enforceSystemOrRoot("Only the system can request dexopt be performed");
5361
5362        // Before everything else, see whether we need to fstrim.
5363        try {
5364            IMountService ms = PackageHelper.getMountService();
5365            if (ms != null) {
5366                final boolean isUpgrade = isUpgrade();
5367                boolean doTrim = isUpgrade;
5368                if (doTrim) {
5369                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5370                } else {
5371                    final long interval = android.provider.Settings.Global.getLong(
5372                            mContext.getContentResolver(),
5373                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5374                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5375                    if (interval > 0) {
5376                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5377                        if (timeSinceLast > interval) {
5378                            doTrim = true;
5379                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5380                                    + "; running immediately");
5381                        }
5382                    }
5383                }
5384                if (doTrim) {
5385                    if (!isFirstBoot()) {
5386                        try {
5387                            ActivityManagerNative.getDefault().showBootMessage(
5388                                    mContext.getResources().getString(
5389                                            R.string.android_upgrading_fstrim), true);
5390                        } catch (RemoteException e) {
5391                        }
5392                    }
5393                    ms.runMaintenance();
5394                }
5395            } else {
5396                Slog.e(TAG, "Mount service unavailable!");
5397            }
5398        } catch (RemoteException e) {
5399            // Can't happen; MountService is local
5400        }
5401
5402        final ArraySet<PackageParser.Package> pkgs;
5403        synchronized (mPackages) {
5404            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5405        }
5406
5407        if (pkgs != null) {
5408            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5409            // in case the device runs out of space.
5410            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5411            // Give priority to core apps.
5412            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5413                PackageParser.Package pkg = it.next();
5414                if (pkg.coreApp) {
5415                    if (DEBUG_DEXOPT) {
5416                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5417                    }
5418                    sortedPkgs.add(pkg);
5419                    it.remove();
5420                }
5421            }
5422            // Give priority to system apps that listen for pre boot complete.
5423            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5424            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
5425            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5426                PackageParser.Package pkg = it.next();
5427                if (pkgNames.contains(pkg.packageName)) {
5428                    if (DEBUG_DEXOPT) {
5429                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
5430                    }
5431                    sortedPkgs.add(pkg);
5432                    it.remove();
5433                }
5434            }
5435            // Give priority to system apps.
5436            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5437                PackageParser.Package pkg = it.next();
5438                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
5439                    if (DEBUG_DEXOPT) {
5440                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
5441                    }
5442                    sortedPkgs.add(pkg);
5443                    it.remove();
5444                }
5445            }
5446            // Give priority to updated system apps.
5447            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5448                PackageParser.Package pkg = it.next();
5449                if (pkg.isUpdatedSystemApp()) {
5450                    if (DEBUG_DEXOPT) {
5451                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
5452                    }
5453                    sortedPkgs.add(pkg);
5454                    it.remove();
5455                }
5456            }
5457            // Give priority to apps that listen for boot complete.
5458            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
5459            pkgNames = getPackageNamesForIntent(intent);
5460            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5461                PackageParser.Package pkg = it.next();
5462                if (pkgNames.contains(pkg.packageName)) {
5463                    if (DEBUG_DEXOPT) {
5464                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
5465                    }
5466                    sortedPkgs.add(pkg);
5467                    it.remove();
5468                }
5469            }
5470            // Filter out packages that aren't recently used.
5471            filterRecentlyUsedApps(pkgs);
5472            // Add all remaining apps.
5473            for (PackageParser.Package pkg : pkgs) {
5474                if (DEBUG_DEXOPT) {
5475                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
5476                }
5477                sortedPkgs.add(pkg);
5478            }
5479
5480            // If we want to be lazy, filter everything that wasn't recently used.
5481            if (mLazyDexOpt) {
5482                filterRecentlyUsedApps(sortedPkgs);
5483            }
5484
5485            int i = 0;
5486            int total = sortedPkgs.size();
5487            File dataDir = Environment.getDataDirectory();
5488            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
5489            if (lowThreshold == 0) {
5490                throw new IllegalStateException("Invalid low memory threshold");
5491            }
5492            for (PackageParser.Package pkg : sortedPkgs) {
5493                long usableSpace = dataDir.getUsableSpace();
5494                if (usableSpace < lowThreshold) {
5495                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
5496                    break;
5497                }
5498                performBootDexOpt(pkg, ++i, total);
5499            }
5500        }
5501    }
5502
5503    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
5504        // Filter out packages that aren't recently used.
5505        //
5506        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
5507        // should do a full dexopt.
5508        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
5509            int total = pkgs.size();
5510            int skipped = 0;
5511            long now = System.currentTimeMillis();
5512            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
5513                PackageParser.Package pkg = i.next();
5514                long then = pkg.mLastPackageUsageTimeInMills;
5515                if (then + mDexOptLRUThresholdInMills < now) {
5516                    if (DEBUG_DEXOPT) {
5517                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
5518                              ((then == 0) ? "never" : new Date(then)));
5519                    }
5520                    i.remove();
5521                    skipped++;
5522                }
5523            }
5524            if (DEBUG_DEXOPT) {
5525                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
5526            }
5527        }
5528    }
5529
5530    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
5531        List<ResolveInfo> ris = null;
5532        try {
5533            ris = AppGlobals.getPackageManager().queryIntentReceivers(
5534                    intent, null, 0, UserHandle.USER_OWNER);
5535        } catch (RemoteException e) {
5536        }
5537        ArraySet<String> pkgNames = new ArraySet<String>();
5538        if (ris != null) {
5539            for (ResolveInfo ri : ris) {
5540                pkgNames.add(ri.activityInfo.packageName);
5541            }
5542        }
5543        return pkgNames;
5544    }
5545
5546    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
5547        if (DEBUG_DEXOPT) {
5548            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
5549        }
5550        if (!isFirstBoot()) {
5551            try {
5552                ActivityManagerNative.getDefault().showBootMessage(
5553                        mContext.getResources().getString(R.string.android_upgrading_apk,
5554                                curr, total), true);
5555            } catch (RemoteException e) {
5556            }
5557        }
5558        PackageParser.Package p = pkg;
5559        synchronized (mInstallLock) {
5560            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
5561                    false /* force dex */, false /* defer */, true /* include dependencies */);
5562        }
5563    }
5564
5565    @Override
5566    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
5567        return performDexOpt(packageName, instructionSet, false);
5568    }
5569
5570    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
5571        boolean dexopt = mLazyDexOpt || backgroundDexopt;
5572        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
5573        if (!dexopt && !updateUsage) {
5574            // We aren't going to dexopt or update usage, so bail early.
5575            return false;
5576        }
5577        PackageParser.Package p;
5578        final String targetInstructionSet;
5579        synchronized (mPackages) {
5580            p = mPackages.get(packageName);
5581            if (p == null) {
5582                return false;
5583            }
5584            if (updateUsage) {
5585                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
5586            }
5587            mPackageUsage.write(false);
5588            if (!dexopt) {
5589                // We aren't going to dexopt, so bail early.
5590                return false;
5591            }
5592
5593            targetInstructionSet = instructionSet != null ? instructionSet :
5594                    getPrimaryInstructionSet(p.applicationInfo);
5595            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
5596                return false;
5597            }
5598        }
5599
5600        synchronized (mInstallLock) {
5601            final String[] instructionSets = new String[] { targetInstructionSet };
5602            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
5603                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
5604            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
5605        }
5606    }
5607
5608    public ArraySet<String> getPackagesThatNeedDexOpt() {
5609        ArraySet<String> pkgs = null;
5610        synchronized (mPackages) {
5611            for (PackageParser.Package p : mPackages.values()) {
5612                if (DEBUG_DEXOPT) {
5613                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
5614                }
5615                if (!p.mDexOptPerformed.isEmpty()) {
5616                    continue;
5617                }
5618                if (pkgs == null) {
5619                    pkgs = new ArraySet<String>();
5620                }
5621                pkgs.add(p.packageName);
5622            }
5623        }
5624        return pkgs;
5625    }
5626
5627    public void shutdown() {
5628        mPackageUsage.write(true);
5629    }
5630
5631    @Override
5632    public void forceDexOpt(String packageName) {
5633        enforceSystemOrRoot("forceDexOpt");
5634
5635        PackageParser.Package pkg;
5636        synchronized (mPackages) {
5637            pkg = mPackages.get(packageName);
5638            if (pkg == null) {
5639                throw new IllegalArgumentException("Missing package: " + packageName);
5640            }
5641        }
5642
5643        synchronized (mInstallLock) {
5644            final String[] instructionSets = new String[] {
5645                    getPrimaryInstructionSet(pkg.applicationInfo) };
5646            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
5647                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
5648            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
5649                throw new IllegalStateException("Failed to dexopt: " + res);
5650            }
5651        }
5652    }
5653
5654    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
5655        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
5656            Slog.w(TAG, "Unable to update from " + oldPkg.name
5657                    + " to " + newPkg.packageName
5658                    + ": old package not in system partition");
5659            return false;
5660        } else if (mPackages.get(oldPkg.name) != null) {
5661            Slog.w(TAG, "Unable to update from " + oldPkg.name
5662                    + " to " + newPkg.packageName
5663                    + ": old package still exists");
5664            return false;
5665        }
5666        return true;
5667    }
5668
5669    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
5670        int[] users = sUserManager.getUserIds();
5671        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
5672        if (res < 0) {
5673            return res;
5674        }
5675        for (int user : users) {
5676            if (user != 0) {
5677                res = mInstaller.createUserData(volumeUuid, packageName,
5678                        UserHandle.getUid(user, uid), user, seinfo);
5679                if (res < 0) {
5680                    return res;
5681                }
5682            }
5683        }
5684        return res;
5685    }
5686
5687    private int removeDataDirsLI(String volumeUuid, String packageName) {
5688        int[] users = sUserManager.getUserIds();
5689        int res = 0;
5690        for (int user : users) {
5691            int resInner = mInstaller.remove(volumeUuid, packageName, user);
5692            if (resInner < 0) {
5693                res = resInner;
5694            }
5695        }
5696
5697        return res;
5698    }
5699
5700    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
5701        int[] users = sUserManager.getUserIds();
5702        int res = 0;
5703        for (int user : users) {
5704            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
5705            if (resInner < 0) {
5706                res = resInner;
5707            }
5708        }
5709        return res;
5710    }
5711
5712    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
5713            PackageParser.Package changingLib) {
5714        if (file.path != null) {
5715            usesLibraryFiles.add(file.path);
5716            return;
5717        }
5718        PackageParser.Package p = mPackages.get(file.apk);
5719        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
5720            // If we are doing this while in the middle of updating a library apk,
5721            // then we need to make sure to use that new apk for determining the
5722            // dependencies here.  (We haven't yet finished committing the new apk
5723            // to the package manager state.)
5724            if (p == null || p.packageName.equals(changingLib.packageName)) {
5725                p = changingLib;
5726            }
5727        }
5728        if (p != null) {
5729            usesLibraryFiles.addAll(p.getAllCodePaths());
5730        }
5731    }
5732
5733    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
5734            PackageParser.Package changingLib) throws PackageManagerException {
5735        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
5736            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
5737            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
5738            for (int i=0; i<N; i++) {
5739                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
5740                if (file == null) {
5741                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
5742                            "Package " + pkg.packageName + " requires unavailable shared library "
5743                            + pkg.usesLibraries.get(i) + "; failing!");
5744                }
5745                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5746            }
5747            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
5748            for (int i=0; i<N; i++) {
5749                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
5750                if (file == null) {
5751                    Slog.w(TAG, "Package " + pkg.packageName
5752                            + " desires unavailable shared library "
5753                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
5754                } else {
5755                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5756                }
5757            }
5758            N = usesLibraryFiles.size();
5759            if (N > 0) {
5760                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
5761            } else {
5762                pkg.usesLibraryFiles = null;
5763            }
5764        }
5765    }
5766
5767    private static boolean hasString(List<String> list, List<String> which) {
5768        if (list == null) {
5769            return false;
5770        }
5771        for (int i=list.size()-1; i>=0; i--) {
5772            for (int j=which.size()-1; j>=0; j--) {
5773                if (which.get(j).equals(list.get(i))) {
5774                    return true;
5775                }
5776            }
5777        }
5778        return false;
5779    }
5780
5781    private void updateAllSharedLibrariesLPw() {
5782        for (PackageParser.Package pkg : mPackages.values()) {
5783            try {
5784                updateSharedLibrariesLPw(pkg, null);
5785            } catch (PackageManagerException e) {
5786                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5787            }
5788        }
5789    }
5790
5791    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
5792            PackageParser.Package changingPkg) {
5793        ArrayList<PackageParser.Package> res = null;
5794        for (PackageParser.Package pkg : mPackages.values()) {
5795            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
5796                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
5797                if (res == null) {
5798                    res = new ArrayList<PackageParser.Package>();
5799                }
5800                res.add(pkg);
5801                try {
5802                    updateSharedLibrariesLPw(pkg, changingPkg);
5803                } catch (PackageManagerException e) {
5804                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5805                }
5806            }
5807        }
5808        return res;
5809    }
5810
5811    /**
5812     * Derive the value of the {@code cpuAbiOverride} based on the provided
5813     * value and an optional stored value from the package settings.
5814     */
5815    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
5816        String cpuAbiOverride = null;
5817
5818        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
5819            cpuAbiOverride = null;
5820        } else if (abiOverride != null) {
5821            cpuAbiOverride = abiOverride;
5822        } else if (settings != null) {
5823            cpuAbiOverride = settings.cpuAbiOverrideString;
5824        }
5825
5826        return cpuAbiOverride;
5827    }
5828
5829    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
5830            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5831        boolean success = false;
5832        try {
5833            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
5834                    currentTime, user);
5835            success = true;
5836            return res;
5837        } finally {
5838            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5839                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
5840            }
5841        }
5842    }
5843
5844    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
5845            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5846        final File scanFile = new File(pkg.codePath);
5847        if (pkg.applicationInfo.getCodePath() == null ||
5848                pkg.applicationInfo.getResourcePath() == null) {
5849            // Bail out. The resource and code paths haven't been set.
5850            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
5851                    "Code and resource paths haven't been set correctly");
5852        }
5853
5854        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5855            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
5856        } else {
5857            // Only allow system apps to be flagged as core apps.
5858            pkg.coreApp = false;
5859        }
5860
5861        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5862            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5863        }
5864
5865        if (mCustomResolverComponentName != null &&
5866                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5867            setUpCustomResolverActivity(pkg);
5868        }
5869
5870        if (pkg.packageName.equals("android")) {
5871            synchronized (mPackages) {
5872                if (mAndroidApplication != null) {
5873                    Slog.w(TAG, "*************************************************");
5874                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5875                    Slog.w(TAG, " file=" + scanFile);
5876                    Slog.w(TAG, "*************************************************");
5877                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5878                            "Core android package being redefined.  Skipping.");
5879                }
5880
5881                // Set up information for our fall-back user intent resolution activity.
5882                mPlatformPackage = pkg;
5883                pkg.mVersionCode = mSdkVersion;
5884                mAndroidApplication = pkg.applicationInfo;
5885
5886                if (!mResolverReplaced) {
5887                    mResolveActivity.applicationInfo = mAndroidApplication;
5888                    mResolveActivity.name = ResolverActivity.class.getName();
5889                    mResolveActivity.packageName = mAndroidApplication.packageName;
5890                    mResolveActivity.processName = "system:ui";
5891                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5892                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5893                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5894                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5895                    mResolveActivity.exported = true;
5896                    mResolveActivity.enabled = true;
5897                    mResolveInfo.activityInfo = mResolveActivity;
5898                    mResolveInfo.priority = 0;
5899                    mResolveInfo.preferredOrder = 0;
5900                    mResolveInfo.match = 0;
5901                    mResolveComponentName = new ComponentName(
5902                            mAndroidApplication.packageName, mResolveActivity.name);
5903                }
5904            }
5905        }
5906
5907        if (DEBUG_PACKAGE_SCANNING) {
5908            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5909                Log.d(TAG, "Scanning package " + pkg.packageName);
5910        }
5911
5912        if (mPackages.containsKey(pkg.packageName)
5913                || mSharedLibraries.containsKey(pkg.packageName)) {
5914            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5915                    "Application package " + pkg.packageName
5916                    + " already installed.  Skipping duplicate.");
5917        }
5918
5919        // If we're only installing presumed-existing packages, require that the
5920        // scanned APK is both already known and at the path previously established
5921        // for it.  Previously unknown packages we pick up normally, but if we have an
5922        // a priori expectation about this package's install presence, enforce it.
5923        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
5924            PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
5925            if (known != null) {
5926                if (DEBUG_PACKAGE_SCANNING) {
5927                    Log.d(TAG, "Examining " + pkg.codePath
5928                            + " and requiring known paths " + known.codePathString
5929                            + " & " + known.resourcePathString);
5930                }
5931                if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
5932                        || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
5933                    throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
5934                            "Application package " + pkg.packageName
5935                            + " found at " + pkg.applicationInfo.getCodePath()
5936                            + " but expected at " + known.codePathString + "; ignoring.");
5937                }
5938            }
5939        }
5940
5941        // Initialize package source and resource directories
5942        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5943        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5944
5945        SharedUserSetting suid = null;
5946        PackageSetting pkgSetting = null;
5947
5948        if (!isSystemApp(pkg)) {
5949            // Only system apps can use these features.
5950            pkg.mOriginalPackages = null;
5951            pkg.mRealPackage = null;
5952            pkg.mAdoptPermissions = null;
5953        }
5954
5955        // writer
5956        synchronized (mPackages) {
5957            if (pkg.mSharedUserId != null) {
5958                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
5959                if (suid == null) {
5960                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5961                            "Creating application package " + pkg.packageName
5962                            + " for shared user failed");
5963                }
5964                if (DEBUG_PACKAGE_SCANNING) {
5965                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5966                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5967                                + "): packages=" + suid.packages);
5968                }
5969            }
5970
5971            // Check if we are renaming from an original package name.
5972            PackageSetting origPackage = null;
5973            String realName = null;
5974            if (pkg.mOriginalPackages != null) {
5975                // This package may need to be renamed to a previously
5976                // installed name.  Let's check on that...
5977                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5978                if (pkg.mOriginalPackages.contains(renamed)) {
5979                    // This package had originally been installed as the
5980                    // original name, and we have already taken care of
5981                    // transitioning to the new one.  Just update the new
5982                    // one to continue using the old name.
5983                    realName = pkg.mRealPackage;
5984                    if (!pkg.packageName.equals(renamed)) {
5985                        // Callers into this function may have already taken
5986                        // care of renaming the package; only do it here if
5987                        // it is not already done.
5988                        pkg.setPackageName(renamed);
5989                    }
5990
5991                } else {
5992                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5993                        if ((origPackage = mSettings.peekPackageLPr(
5994                                pkg.mOriginalPackages.get(i))) != null) {
5995                            // We do have the package already installed under its
5996                            // original name...  should we use it?
5997                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5998                                // New package is not compatible with original.
5999                                origPackage = null;
6000                                continue;
6001                            } else if (origPackage.sharedUser != null) {
6002                                // Make sure uid is compatible between packages.
6003                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6004                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6005                                            + " to " + pkg.packageName + ": old uid "
6006                                            + origPackage.sharedUser.name
6007                                            + " differs from " + pkg.mSharedUserId);
6008                                    origPackage = null;
6009                                    continue;
6010                                }
6011                            } else {
6012                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6013                                        + pkg.packageName + " to old name " + origPackage.name);
6014                            }
6015                            break;
6016                        }
6017                    }
6018                }
6019            }
6020
6021            if (mTransferedPackages.contains(pkg.packageName)) {
6022                Slog.w(TAG, "Package " + pkg.packageName
6023                        + " was transferred to another, but its .apk remains");
6024            }
6025
6026            // Just create the setting, don't add it yet. For already existing packages
6027            // the PkgSetting exists already and doesn't have to be created.
6028            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6029                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6030                    pkg.applicationInfo.primaryCpuAbi,
6031                    pkg.applicationInfo.secondaryCpuAbi,
6032                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6033                    user, false);
6034            if (pkgSetting == null) {
6035                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6036                        "Creating application package " + pkg.packageName + " failed");
6037            }
6038
6039            if (pkgSetting.origPackage != null) {
6040                // If we are first transitioning from an original package,
6041                // fix up the new package's name now.  We need to do this after
6042                // looking up the package under its new name, so getPackageLP
6043                // can take care of fiddling things correctly.
6044                pkg.setPackageName(origPackage.name);
6045
6046                // File a report about this.
6047                String msg = "New package " + pkgSetting.realName
6048                        + " renamed to replace old package " + pkgSetting.name;
6049                reportSettingsProblem(Log.WARN, msg);
6050
6051                // Make a note of it.
6052                mTransferedPackages.add(origPackage.name);
6053
6054                // No longer need to retain this.
6055                pkgSetting.origPackage = null;
6056            }
6057
6058            if (realName != null) {
6059                // Make a note of it.
6060                mTransferedPackages.add(pkg.packageName);
6061            }
6062
6063            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6064                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6065            }
6066
6067            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6068                // Check all shared libraries and map to their actual file path.
6069                // We only do this here for apps not on a system dir, because those
6070                // are the only ones that can fail an install due to this.  We
6071                // will take care of the system apps by updating all of their
6072                // library paths after the scan is done.
6073                updateSharedLibrariesLPw(pkg, null);
6074            }
6075
6076            if (mFoundPolicyFile) {
6077                SELinuxMMAC.assignSeinfoValue(pkg);
6078            }
6079
6080            pkg.applicationInfo.uid = pkgSetting.appId;
6081            pkg.mExtras = pkgSetting;
6082            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
6083                try {
6084                    verifySignaturesLP(pkgSetting, pkg);
6085                    // We just determined the app is signed correctly, so bring
6086                    // over the latest parsed certs.
6087                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6088                } catch (PackageManagerException e) {
6089                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6090                        throw e;
6091                    }
6092                    // The signature has changed, but this package is in the system
6093                    // image...  let's recover!
6094                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6095                    // However...  if this package is part of a shared user, but it
6096                    // doesn't match the signature of the shared user, let's fail.
6097                    // What this means is that you can't change the signatures
6098                    // associated with an overall shared user, which doesn't seem all
6099                    // that unreasonable.
6100                    if (pkgSetting.sharedUser != null) {
6101                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6102                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6103                            throw new PackageManagerException(
6104                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6105                                            "Signature mismatch for shared user : "
6106                                            + pkgSetting.sharedUser);
6107                        }
6108                    }
6109                    // File a report about this.
6110                    String msg = "System package " + pkg.packageName
6111                        + " signature changed; retaining data.";
6112                    reportSettingsProblem(Log.WARN, msg);
6113                }
6114            } else {
6115                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
6116                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6117                            + pkg.packageName + " upgrade keys do not match the "
6118                            + "previously installed version");
6119                } else {
6120                    // We just determined the app is signed correctly, so bring
6121                    // over the latest parsed certs.
6122                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6123                }
6124            }
6125            // Verify that this new package doesn't have any content providers
6126            // that conflict with existing packages.  Only do this if the
6127            // package isn't already installed, since we don't want to break
6128            // things that are installed.
6129            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6130                final int N = pkg.providers.size();
6131                int i;
6132                for (i=0; i<N; i++) {
6133                    PackageParser.Provider p = pkg.providers.get(i);
6134                    if (p.info.authority != null) {
6135                        String names[] = p.info.authority.split(";");
6136                        for (int j = 0; j < names.length; j++) {
6137                            if (mProvidersByAuthority.containsKey(names[j])) {
6138                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6139                                final String otherPackageName =
6140                                        ((other != null && other.getComponentName() != null) ?
6141                                                other.getComponentName().getPackageName() : "?");
6142                                throw new PackageManagerException(
6143                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6144                                                "Can't install because provider name " + names[j]
6145                                                + " (in package " + pkg.applicationInfo.packageName
6146                                                + ") is already used by " + otherPackageName);
6147                            }
6148                        }
6149                    }
6150                }
6151            }
6152
6153            if (pkg.mAdoptPermissions != null) {
6154                // This package wants to adopt ownership of permissions from
6155                // another package.
6156                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6157                    final String origName = pkg.mAdoptPermissions.get(i);
6158                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6159                    if (orig != null) {
6160                        if (verifyPackageUpdateLPr(orig, pkg)) {
6161                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6162                                    + pkg.packageName);
6163                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6164                        }
6165                    }
6166                }
6167            }
6168        }
6169
6170        final String pkgName = pkg.packageName;
6171
6172        final long scanFileTime = scanFile.lastModified();
6173        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6174        pkg.applicationInfo.processName = fixProcessName(
6175                pkg.applicationInfo.packageName,
6176                pkg.applicationInfo.processName,
6177                pkg.applicationInfo.uid);
6178
6179        File dataPath;
6180        if (mPlatformPackage == pkg) {
6181            // The system package is special.
6182            dataPath = new File(Environment.getDataDirectory(), "system");
6183
6184            pkg.applicationInfo.dataDir = dataPath.getPath();
6185
6186        } else {
6187            // This is a normal package, need to make its data directory.
6188            dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName,
6189                    UserHandle.USER_OWNER);
6190
6191            boolean uidError = false;
6192            if (dataPath.exists()) {
6193                int currentUid = 0;
6194                try {
6195                    StructStat stat = Os.stat(dataPath.getPath());
6196                    currentUid = stat.st_uid;
6197                } catch (ErrnoException e) {
6198                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6199                }
6200
6201                // If we have mismatched owners for the data path, we have a problem.
6202                if (currentUid != pkg.applicationInfo.uid) {
6203                    boolean recovered = false;
6204                    if (currentUid == 0) {
6205                        // The directory somehow became owned by root.  Wow.
6206                        // This is probably because the system was stopped while
6207                        // installd was in the middle of messing with its libs
6208                        // directory.  Ask installd to fix that.
6209                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6210                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6211                        if (ret >= 0) {
6212                            recovered = true;
6213                            String msg = "Package " + pkg.packageName
6214                                    + " unexpectedly changed to uid 0; recovered to " +
6215                                    + pkg.applicationInfo.uid;
6216                            reportSettingsProblem(Log.WARN, msg);
6217                        }
6218                    }
6219                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6220                            || (scanFlags&SCAN_BOOTING) != 0)) {
6221                        // If this is a system app, we can at least delete its
6222                        // current data so the application will still work.
6223                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6224                        if (ret >= 0) {
6225                            // TODO: Kill the processes first
6226                            // Old data gone!
6227                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6228                                    ? "System package " : "Third party package ";
6229                            String msg = prefix + pkg.packageName
6230                                    + " has changed from uid: "
6231                                    + currentUid + " to "
6232                                    + pkg.applicationInfo.uid + "; old data erased";
6233                            reportSettingsProblem(Log.WARN, msg);
6234                            recovered = true;
6235
6236                            // And now re-install the app.
6237                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6238                                    pkg.applicationInfo.seinfo);
6239                            if (ret == -1) {
6240                                // Ack should not happen!
6241                                msg = prefix + pkg.packageName
6242                                        + " could not have data directory re-created after delete.";
6243                                reportSettingsProblem(Log.WARN, msg);
6244                                throw new PackageManagerException(
6245                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6246                            }
6247                        }
6248                        if (!recovered) {
6249                            mHasSystemUidErrors = true;
6250                        }
6251                    } else if (!recovered) {
6252                        // If we allow this install to proceed, we will be broken.
6253                        // Abort, abort!
6254                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6255                                "scanPackageLI");
6256                    }
6257                    if (!recovered) {
6258                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6259                            + pkg.applicationInfo.uid + "/fs_"
6260                            + currentUid;
6261                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6262                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6263                        String msg = "Package " + pkg.packageName
6264                                + " has mismatched uid: "
6265                                + currentUid + " on disk, "
6266                                + pkg.applicationInfo.uid + " in settings";
6267                        // writer
6268                        synchronized (mPackages) {
6269                            mSettings.mReadMessages.append(msg);
6270                            mSettings.mReadMessages.append('\n');
6271                            uidError = true;
6272                            if (!pkgSetting.uidError) {
6273                                reportSettingsProblem(Log.ERROR, msg);
6274                            }
6275                        }
6276                    }
6277                }
6278                pkg.applicationInfo.dataDir = dataPath.getPath();
6279                if (mShouldRestoreconData) {
6280                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6281                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6282                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6283                }
6284            } else {
6285                if (DEBUG_PACKAGE_SCANNING) {
6286                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6287                        Log.v(TAG, "Want this data dir: " + dataPath);
6288                }
6289                //invoke installer to do the actual installation
6290                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6291                        pkg.applicationInfo.seinfo);
6292                if (ret < 0) {
6293                    // Error from installer
6294                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6295                            "Unable to create data dirs [errorCode=" + ret + "]");
6296                }
6297
6298                if (dataPath.exists()) {
6299                    pkg.applicationInfo.dataDir = dataPath.getPath();
6300                } else {
6301                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6302                    pkg.applicationInfo.dataDir = null;
6303                }
6304            }
6305
6306            pkgSetting.uidError = uidError;
6307        }
6308
6309        final String path = scanFile.getPath();
6310        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6311        if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
6312            setBundledAppAbisAndRoots(pkg, pkgSetting);
6313
6314            // If we haven't found any native libraries for the app, check if it has
6315            // renderscript code. We'll need to force the app to 32 bit if it has
6316            // renderscript bitcode.
6317            if (pkg.applicationInfo.primaryCpuAbi == null
6318                    && pkg.applicationInfo.secondaryCpuAbi == null
6319                    && Build.SUPPORTED_64_BIT_ABIS.length >  0) {
6320                NativeLibraryHelper.Handle handle = null;
6321                try {
6322                    handle = NativeLibraryHelper.Handle.create(scanFile);
6323                    if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
6324                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6325                    }
6326                } catch (IOException ioe) {
6327                    Slog.w(TAG, "Error scanning system app : " + ioe);
6328                } finally {
6329                    IoUtils.closeQuietly(handle);
6330                }
6331            }
6332
6333            setNativeLibraryPaths(pkg);
6334        } else {
6335            if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6336                deriveNonSystemPackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6337            } else {
6338                // Verify the ABIs haven't changed since we last deduced them.
6339                String oldPrimaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
6340                String oldSecondaryCpuAbi = pkg.applicationInfo.secondaryCpuAbi;
6341
6342                // TODO: The only purpose of this code is to update the native library paths
6343                // based on the final install location. We can simplify this and avoid having
6344                // to scan the package again.
6345                deriveNonSystemPackageAbi(pkg, scanFile, cpuAbiOverride, false /* extract libs */);
6346                if (!TextUtils.equals(oldPrimaryCpuAbi, pkg.applicationInfo.primaryCpuAbi)) {
6347                    throw new IllegalStateException("unexpected abi change for " + pkg.packageName + " ("
6348                            + oldPrimaryCpuAbi + "-> " + pkg.applicationInfo.primaryCpuAbi);
6349                }
6350
6351                if (!TextUtils.equals(oldSecondaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi)) {
6352                    throw new IllegalStateException("unexpected abi change for " + pkg.packageName + " ("
6353                            + oldSecondaryCpuAbi + "-> " + pkg.applicationInfo.secondaryCpuAbi);
6354                }
6355            }
6356
6357            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6358            final int[] userIds = sUserManager.getUserIds();
6359            synchronized (mInstallLock) {
6360                // Create a native library symlink only if we have native libraries
6361                // and if the native libraries are 32 bit libraries. We do not provide
6362                // this symlink for 64 bit libraries.
6363                if (pkg.applicationInfo.primaryCpuAbi != null &&
6364                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6365                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6366                    for (int userId : userIds) {
6367                        if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6368                                nativeLibPath, userId) < 0) {
6369                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6370                                    "Failed linking native library dir (user=" + userId + ")");
6371                        }
6372                    }
6373                }
6374            }
6375        }
6376
6377        // This is a special case for the "system" package, where the ABI is
6378        // dictated by the zygote configuration (and init.rc). We should keep track
6379        // of this ABI so that we can deal with "normal" applications that run under
6380        // the same UID correctly.
6381        if (mPlatformPackage == pkg) {
6382            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6383                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6384        }
6385
6386        // If there's a mismatch between the abi-override in the package setting
6387        // and the abiOverride specified for the install. Warn about this because we
6388        // would've already compiled the app without taking the package setting into
6389        // account.
6390        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
6391            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
6392                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
6393                        " for package: " + pkg.packageName);
6394            }
6395        }
6396
6397        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6398        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6399        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6400
6401        // Copy the derived override back to the parsed package, so that we can
6402        // update the package settings accordingly.
6403        pkg.cpuAbiOverride = cpuAbiOverride;
6404
6405        if (DEBUG_ABI_SELECTION) {
6406            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6407                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6408                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6409        }
6410
6411        // Push the derived path down into PackageSettings so we know what to
6412        // clean up at uninstall time.
6413        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6414
6415        if (DEBUG_ABI_SELECTION) {
6416            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6417                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6418                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6419        }
6420
6421        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6422            // We don't do this here during boot because we can do it all
6423            // at once after scanning all existing packages.
6424            //
6425            // We also do this *before* we perform dexopt on this package, so that
6426            // we can avoid redundant dexopts, and also to make sure we've got the
6427            // code and package path correct.
6428            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
6429                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
6430        }
6431
6432        if ((scanFlags & SCAN_NO_DEX) == 0) {
6433            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
6434                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
6435            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6436                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
6437            }
6438        }
6439        if (mFactoryTest && pkg.requestedPermissions.contains(
6440                android.Manifest.permission.FACTORY_TEST)) {
6441            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
6442        }
6443
6444        ArrayList<PackageParser.Package> clientLibPkgs = null;
6445
6446        // writer
6447        synchronized (mPackages) {
6448            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6449                // Only system apps can add new shared libraries.
6450                if (pkg.libraryNames != null) {
6451                    for (int i=0; i<pkg.libraryNames.size(); i++) {
6452                        String name = pkg.libraryNames.get(i);
6453                        boolean allowed = false;
6454                        if (pkg.isUpdatedSystemApp()) {
6455                            // New library entries can only be added through the
6456                            // system image.  This is important to get rid of a lot
6457                            // of nasty edge cases: for example if we allowed a non-
6458                            // system update of the app to add a library, then uninstalling
6459                            // the update would make the library go away, and assumptions
6460                            // we made such as through app install filtering would now
6461                            // have allowed apps on the device which aren't compatible
6462                            // with it.  Better to just have the restriction here, be
6463                            // conservative, and create many fewer cases that can negatively
6464                            // impact the user experience.
6465                            final PackageSetting sysPs = mSettings
6466                                    .getDisabledSystemPkgLPr(pkg.packageName);
6467                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
6468                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
6469                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
6470                                        allowed = true;
6471                                        allowed = true;
6472                                        break;
6473                                    }
6474                                }
6475                            }
6476                        } else {
6477                            allowed = true;
6478                        }
6479                        if (allowed) {
6480                            if (!mSharedLibraries.containsKey(name)) {
6481                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
6482                            } else if (!name.equals(pkg.packageName)) {
6483                                Slog.w(TAG, "Package " + pkg.packageName + " library "
6484                                        + name + " already exists; skipping");
6485                            }
6486                        } else {
6487                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
6488                                    + name + " that is not declared on system image; skipping");
6489                        }
6490                    }
6491                    if ((scanFlags&SCAN_BOOTING) == 0) {
6492                        // If we are not booting, we need to update any applications
6493                        // that are clients of our shared library.  If we are booting,
6494                        // this will all be done once the scan is complete.
6495                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
6496                    }
6497                }
6498            }
6499        }
6500
6501        // We also need to dexopt any apps that are dependent on this library.  Note that
6502        // if these fail, we should abort the install since installing the library will
6503        // result in some apps being broken.
6504        if (clientLibPkgs != null) {
6505            if ((scanFlags & SCAN_NO_DEX) == 0) {
6506                for (int i = 0; i < clientLibPkgs.size(); i++) {
6507                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
6508                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
6509                            null /* instruction sets */, forceDex,
6510                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
6511                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6512                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
6513                                "scanPackageLI failed to dexopt clientLibPkgs");
6514                    }
6515                }
6516            }
6517        }
6518
6519        // Also need to kill any apps that are dependent on the library.
6520        if (clientLibPkgs != null) {
6521            for (int i=0; i<clientLibPkgs.size(); i++) {
6522                PackageParser.Package clientPkg = clientLibPkgs.get(i);
6523                killApplication(clientPkg.applicationInfo.packageName,
6524                        clientPkg.applicationInfo.uid, "update lib");
6525            }
6526        }
6527
6528        // writer
6529        synchronized (mPackages) {
6530            // We don't expect installation to fail beyond this point
6531
6532            // Add the new setting to mSettings
6533            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
6534            // Add the new setting to mPackages
6535            mPackages.put(pkg.applicationInfo.packageName, pkg);
6536            // Make sure we don't accidentally delete its data.
6537            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
6538            while (iter.hasNext()) {
6539                PackageCleanItem item = iter.next();
6540                if (pkgName.equals(item.packageName)) {
6541                    iter.remove();
6542                }
6543            }
6544
6545            // Take care of first install / last update times.
6546            if (currentTime != 0) {
6547                if (pkgSetting.firstInstallTime == 0) {
6548                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
6549                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
6550                    pkgSetting.lastUpdateTime = currentTime;
6551                }
6552            } else if (pkgSetting.firstInstallTime == 0) {
6553                // We need *something*.  Take time time stamp of the file.
6554                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
6555            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
6556                if (scanFileTime != pkgSetting.timeStamp) {
6557                    // A package on the system image has changed; consider this
6558                    // to be an update.
6559                    pkgSetting.lastUpdateTime = scanFileTime;
6560                }
6561            }
6562
6563            // Add the package's KeySets to the global KeySetManagerService
6564            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6565            try {
6566                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
6567                if (pkg.mKeySetMapping != null) {
6568                    ksms.addDefinedKeySetsToPackageLPw(pkg.packageName, pkg.mKeySetMapping);
6569                    if (pkg.mUpgradeKeySets != null) {
6570                        ksms.addUpgradeKeySetsToPackageLPw(pkg.packageName, pkg.mUpgradeKeySets);
6571                    }
6572                }
6573            } catch (NullPointerException e) {
6574                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
6575            } catch (IllegalArgumentException e) {
6576                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
6577            }
6578
6579            int N = pkg.providers.size();
6580            StringBuilder r = null;
6581            int i;
6582            for (i=0; i<N; i++) {
6583                PackageParser.Provider p = pkg.providers.get(i);
6584                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
6585                        p.info.processName, pkg.applicationInfo.uid);
6586                mProviders.addProvider(p);
6587                p.syncable = p.info.isSyncable;
6588                if (p.info.authority != null) {
6589                    String names[] = p.info.authority.split(";");
6590                    p.info.authority = null;
6591                    for (int j = 0; j < names.length; j++) {
6592                        if (j == 1 && p.syncable) {
6593                            // We only want the first authority for a provider to possibly be
6594                            // syncable, so if we already added this provider using a different
6595                            // authority clear the syncable flag. We copy the provider before
6596                            // changing it because the mProviders object contains a reference
6597                            // to a provider that we don't want to change.
6598                            // Only do this for the second authority since the resulting provider
6599                            // object can be the same for all future authorities for this provider.
6600                            p = new PackageParser.Provider(p);
6601                            p.syncable = false;
6602                        }
6603                        if (!mProvidersByAuthority.containsKey(names[j])) {
6604                            mProvidersByAuthority.put(names[j], p);
6605                            if (p.info.authority == null) {
6606                                p.info.authority = names[j];
6607                            } else {
6608                                p.info.authority = p.info.authority + ";" + names[j];
6609                            }
6610                            if (DEBUG_PACKAGE_SCANNING) {
6611                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6612                                    Log.d(TAG, "Registered content provider: " + names[j]
6613                                            + ", className = " + p.info.name + ", isSyncable = "
6614                                            + p.info.isSyncable);
6615                            }
6616                        } else {
6617                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6618                            Slog.w(TAG, "Skipping provider name " + names[j] +
6619                                    " (in package " + pkg.applicationInfo.packageName +
6620                                    "): name already used by "
6621                                    + ((other != null && other.getComponentName() != null)
6622                                            ? other.getComponentName().getPackageName() : "?"));
6623                        }
6624                    }
6625                }
6626                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6627                    if (r == null) {
6628                        r = new StringBuilder(256);
6629                    } else {
6630                        r.append(' ');
6631                    }
6632                    r.append(p.info.name);
6633                }
6634            }
6635            if (r != null) {
6636                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
6637            }
6638
6639            N = pkg.services.size();
6640            r = null;
6641            for (i=0; i<N; i++) {
6642                PackageParser.Service s = pkg.services.get(i);
6643                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
6644                        s.info.processName, pkg.applicationInfo.uid);
6645                mServices.addService(s);
6646                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6647                    if (r == null) {
6648                        r = new StringBuilder(256);
6649                    } else {
6650                        r.append(' ');
6651                    }
6652                    r.append(s.info.name);
6653                }
6654            }
6655            if (r != null) {
6656                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
6657            }
6658
6659            N = pkg.receivers.size();
6660            r = null;
6661            for (i=0; i<N; i++) {
6662                PackageParser.Activity a = pkg.receivers.get(i);
6663                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6664                        a.info.processName, pkg.applicationInfo.uid);
6665                mReceivers.addActivity(a, "receiver");
6666                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6667                    if (r == null) {
6668                        r = new StringBuilder(256);
6669                    } else {
6670                        r.append(' ');
6671                    }
6672                    r.append(a.info.name);
6673                }
6674            }
6675            if (r != null) {
6676                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
6677            }
6678
6679            N = pkg.activities.size();
6680            r = null;
6681            for (i=0; i<N; i++) {
6682                PackageParser.Activity a = pkg.activities.get(i);
6683                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6684                        a.info.processName, pkg.applicationInfo.uid);
6685                mActivities.addActivity(a, "activity");
6686                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6687                    if (r == null) {
6688                        r = new StringBuilder(256);
6689                    } else {
6690                        r.append(' ');
6691                    }
6692                    r.append(a.info.name);
6693                }
6694            }
6695            if (r != null) {
6696                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
6697            }
6698
6699            N = pkg.permissionGroups.size();
6700            r = null;
6701            for (i=0; i<N; i++) {
6702                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
6703                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
6704                if (cur == null) {
6705                    mPermissionGroups.put(pg.info.name, pg);
6706                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6707                        if (r == null) {
6708                            r = new StringBuilder(256);
6709                        } else {
6710                            r.append(' ');
6711                        }
6712                        r.append(pg.info.name);
6713                    }
6714                } else {
6715                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
6716                            + pg.info.packageName + " ignored: original from "
6717                            + cur.info.packageName);
6718                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6719                        if (r == null) {
6720                            r = new StringBuilder(256);
6721                        } else {
6722                            r.append(' ');
6723                        }
6724                        r.append("DUP:");
6725                        r.append(pg.info.name);
6726                    }
6727                }
6728            }
6729            if (r != null) {
6730                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6731            }
6732
6733            N = pkg.permissions.size();
6734            r = null;
6735            for (i=0; i<N; i++) {
6736                PackageParser.Permission p = pkg.permissions.get(i);
6737
6738                // Now that permission groups have a special meaning, we ignore permission
6739                // groups for legacy apps to prevent unexpected behavior. In particular,
6740                // permissions for one app being granted to someone just becuase they happen
6741                // to be in a group defined by another app (before this had no implications).
6742                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
6743                    p.group = mPermissionGroups.get(p.info.group);
6744                    // Warn for a permission in an unknown group.
6745                    if (p.info.group != null && p.group == null) {
6746                        Slog.w(TAG, "Permission " + p.info.name + " from package "
6747                                + p.info.packageName + " in an unknown group " + p.info.group);
6748                    }
6749                }
6750
6751                ArrayMap<String, BasePermission> permissionMap =
6752                        p.tree ? mSettings.mPermissionTrees
6753                                : mSettings.mPermissions;
6754                BasePermission bp = permissionMap.get(p.info.name);
6755
6756                // Allow system apps to redefine non-system permissions
6757                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
6758                    final boolean currentOwnerIsSystem = (bp.perm != null
6759                            && isSystemApp(bp.perm.owner));
6760                    if (isSystemApp(p.owner)) {
6761                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
6762                            // It's a built-in permission and no owner, take ownership now
6763                            bp.packageSetting = pkgSetting;
6764                            bp.perm = p;
6765                            bp.uid = pkg.applicationInfo.uid;
6766                            bp.sourcePackage = p.info.packageName;
6767                        } else if (!currentOwnerIsSystem) {
6768                            String msg = "New decl " + p.owner + " of permission  "
6769                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
6770                            reportSettingsProblem(Log.WARN, msg);
6771                            bp = null;
6772                        }
6773                    }
6774                }
6775
6776                if (bp == null) {
6777                    bp = new BasePermission(p.info.name, p.info.packageName,
6778                            BasePermission.TYPE_NORMAL);
6779                    permissionMap.put(p.info.name, bp);
6780                }
6781
6782                if (bp.perm == null) {
6783                    if (bp.sourcePackage == null
6784                            || bp.sourcePackage.equals(p.info.packageName)) {
6785                        BasePermission tree = findPermissionTreeLP(p.info.name);
6786                        if (tree == null
6787                                || tree.sourcePackage.equals(p.info.packageName)) {
6788                            bp.packageSetting = pkgSetting;
6789                            bp.perm = p;
6790                            bp.uid = pkg.applicationInfo.uid;
6791                            bp.sourcePackage = p.info.packageName;
6792                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6793                                if (r == null) {
6794                                    r = new StringBuilder(256);
6795                                } else {
6796                                    r.append(' ');
6797                                }
6798                                r.append(p.info.name);
6799                            }
6800                        } else {
6801                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6802                                    + p.info.packageName + " ignored: base tree "
6803                                    + tree.name + " is from package "
6804                                    + tree.sourcePackage);
6805                        }
6806                    } else {
6807                        Slog.w(TAG, "Permission " + p.info.name + " from package "
6808                                + p.info.packageName + " ignored: original from "
6809                                + bp.sourcePackage);
6810                    }
6811                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6812                    if (r == null) {
6813                        r = new StringBuilder(256);
6814                    } else {
6815                        r.append(' ');
6816                    }
6817                    r.append("DUP:");
6818                    r.append(p.info.name);
6819                }
6820                if (bp.perm == p) {
6821                    bp.protectionLevel = p.info.protectionLevel;
6822                }
6823            }
6824
6825            if (r != null) {
6826                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6827            }
6828
6829            N = pkg.instrumentation.size();
6830            r = null;
6831            for (i=0; i<N; i++) {
6832                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6833                a.info.packageName = pkg.applicationInfo.packageName;
6834                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6835                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6836                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6837                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6838                a.info.dataDir = pkg.applicationInfo.dataDir;
6839
6840                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6841                // need other information about the application, like the ABI and what not ?
6842                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6843                mInstrumentation.put(a.getComponentName(), a);
6844                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6845                    if (r == null) {
6846                        r = new StringBuilder(256);
6847                    } else {
6848                        r.append(' ');
6849                    }
6850                    r.append(a.info.name);
6851                }
6852            }
6853            if (r != null) {
6854                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6855            }
6856
6857            if (pkg.protectedBroadcasts != null) {
6858                N = pkg.protectedBroadcasts.size();
6859                for (i=0; i<N; i++) {
6860                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6861                }
6862            }
6863
6864            pkgSetting.setTimeStamp(scanFileTime);
6865
6866            // Create idmap files for pairs of (packages, overlay packages).
6867            // Note: "android", ie framework-res.apk, is handled by native layers.
6868            if (pkg.mOverlayTarget != null) {
6869                // This is an overlay package.
6870                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6871                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6872                        mOverlays.put(pkg.mOverlayTarget,
6873                                new ArrayMap<String, PackageParser.Package>());
6874                    }
6875                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6876                    map.put(pkg.packageName, pkg);
6877                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6878                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6879                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6880                                "scanPackageLI failed to createIdmap");
6881                    }
6882                }
6883            } else if (mOverlays.containsKey(pkg.packageName) &&
6884                    !pkg.packageName.equals("android")) {
6885                // This is a regular package, with one or more known overlay packages.
6886                createIdmapsForPackageLI(pkg);
6887            }
6888        }
6889
6890        return pkg;
6891    }
6892
6893    /**
6894     * Derive the ABI of a non-system package located at {@code scanFile}. This information
6895     * is derived purely on the basis of the contents of {@code scanFile} and
6896     * {@code cpuAbiOverride}.
6897     *
6898     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
6899     */
6900    public void deriveNonSystemPackageAbi(PackageParser.Package pkg, File scanFile,
6901                                          String cpuAbiOverride, boolean extractLibs)
6902            throws PackageManagerException {
6903        // TODO: We can probably be smarter about this stuff. For installed apps,
6904        // we can calculate this information at install time once and for all. For
6905        // system apps, we can probably assume that this information doesn't change
6906        // after the first boot scan. As things stand, we do lots of unnecessary work.
6907
6908        // Give ourselves some initial paths; we'll come back for another
6909        // pass once we've determined ABI below.
6910        setNativeLibraryPaths(pkg);
6911
6912        // We would never need to extract libs for forward-locked and external packages,
6913        // since the container service will do it for us.
6914        if (pkg.isForwardLocked() || isExternal(pkg)) {
6915            extractLibs = false;
6916        }
6917
6918        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
6919        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
6920
6921        NativeLibraryHelper.Handle handle = null;
6922        try {
6923            handle = NativeLibraryHelper.Handle.create(scanFile);
6924            // TODO(multiArch): This can be null for apps that didn't go through the
6925            // usual installation process. We can calculate it again, like we
6926            // do during install time.
6927            //
6928            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
6929            // unnecessary.
6930            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
6931
6932            // Null out the abis so that they can be recalculated.
6933            pkg.applicationInfo.primaryCpuAbi = null;
6934            pkg.applicationInfo.secondaryCpuAbi = null;
6935            if (isMultiArch(pkg.applicationInfo)) {
6936                // Warn if we've set an abiOverride for multi-lib packages..
6937                // By definition, we need to copy both 32 and 64 bit libraries for
6938                // such packages.
6939                if (pkg.cpuAbiOverride != null
6940                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
6941                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
6942                }
6943
6944                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
6945                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
6946                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
6947                    if (extractLibs) {
6948                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
6949                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
6950                                useIsaSpecificSubdirs);
6951                    } else {
6952                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
6953                    }
6954                }
6955
6956                maybeThrowExceptionForMultiArchCopy(
6957                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
6958
6959                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
6960                    if (extractLibs) {
6961                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
6962                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
6963                                useIsaSpecificSubdirs);
6964                    } else {
6965                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
6966                    }
6967                }
6968
6969                maybeThrowExceptionForMultiArchCopy(
6970                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
6971
6972                if (abi64 >= 0) {
6973                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
6974                }
6975
6976                if (abi32 >= 0) {
6977                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
6978                    if (abi64 >= 0) {
6979                        pkg.applicationInfo.secondaryCpuAbi = abi;
6980                    } else {
6981                        pkg.applicationInfo.primaryCpuAbi = abi;
6982                    }
6983                }
6984            } else {
6985                String[] abiList = (cpuAbiOverride != null) ?
6986                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
6987
6988                // Enable gross and lame hacks for apps that are built with old
6989                // SDK tools. We must scan their APKs for renderscript bitcode and
6990                // not launch them if it's present. Don't bother checking on devices
6991                // that don't have 64 bit support.
6992                boolean needsRenderScriptOverride = false;
6993                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
6994                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
6995                    abiList = Build.SUPPORTED_32_BIT_ABIS;
6996                    needsRenderScriptOverride = true;
6997                }
6998
6999                final int copyRet;
7000                if (extractLibs) {
7001                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7002                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7003                } else {
7004                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7005                }
7006
7007                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7008                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7009                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7010                }
7011
7012                if (copyRet >= 0) {
7013                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7014                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7015                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7016                } else if (needsRenderScriptOverride) {
7017                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7018                }
7019            }
7020        } catch (IOException ioe) {
7021            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7022        } finally {
7023            IoUtils.closeQuietly(handle);
7024        }
7025
7026        // Now that we've calculated the ABIs and determined if it's an internal app,
7027        // we will go ahead and populate the nativeLibraryPath.
7028        setNativeLibraryPaths(pkg);
7029    }
7030
7031    /**
7032     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7033     * i.e, so that all packages can be run inside a single process if required.
7034     *
7035     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7036     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7037     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7038     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7039     * updating a package that belongs to a shared user.
7040     *
7041     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7042     * adds unnecessary complexity.
7043     */
7044    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7045            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7046        String requiredInstructionSet = null;
7047        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7048            requiredInstructionSet = VMRuntime.getInstructionSet(
7049                     scannedPackage.applicationInfo.primaryCpuAbi);
7050        }
7051
7052        PackageSetting requirer = null;
7053        for (PackageSetting ps : packagesForUser) {
7054            // If packagesForUser contains scannedPackage, we skip it. This will happen
7055            // when scannedPackage is an update of an existing package. Without this check,
7056            // we will never be able to change the ABI of any package belonging to a shared
7057            // user, even if it's compatible with other packages.
7058            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7059                if (ps.primaryCpuAbiString == null) {
7060                    continue;
7061                }
7062
7063                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7064                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7065                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7066                    // this but there's not much we can do.
7067                    String errorMessage = "Instruction set mismatch, "
7068                            + ((requirer == null) ? "[caller]" : requirer)
7069                            + " requires " + requiredInstructionSet + " whereas " + ps
7070                            + " requires " + instructionSet;
7071                    Slog.w(TAG, errorMessage);
7072                }
7073
7074                if (requiredInstructionSet == null) {
7075                    requiredInstructionSet = instructionSet;
7076                    requirer = ps;
7077                }
7078            }
7079        }
7080
7081        if (requiredInstructionSet != null) {
7082            String adjustedAbi;
7083            if (requirer != null) {
7084                // requirer != null implies that either scannedPackage was null or that scannedPackage
7085                // did not require an ABI, in which case we have to adjust scannedPackage to match
7086                // the ABI of the set (which is the same as requirer's ABI)
7087                adjustedAbi = requirer.primaryCpuAbiString;
7088                if (scannedPackage != null) {
7089                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7090                }
7091            } else {
7092                // requirer == null implies that we're updating all ABIs in the set to
7093                // match scannedPackage.
7094                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7095            }
7096
7097            for (PackageSetting ps : packagesForUser) {
7098                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7099                    if (ps.primaryCpuAbiString != null) {
7100                        continue;
7101                    }
7102
7103                    ps.primaryCpuAbiString = adjustedAbi;
7104                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7105                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7106                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7107
7108                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7109                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7110                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7111                            ps.primaryCpuAbiString = null;
7112                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7113                            return;
7114                        } else {
7115                            mInstaller.rmdex(ps.codePathString,
7116                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7117                        }
7118                    }
7119                }
7120            }
7121        }
7122    }
7123
7124    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7125        synchronized (mPackages) {
7126            mResolverReplaced = true;
7127            // Set up information for custom user intent resolution activity.
7128            mResolveActivity.applicationInfo = pkg.applicationInfo;
7129            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7130            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7131            mResolveActivity.processName = pkg.applicationInfo.packageName;
7132            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7133            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7134                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7135            mResolveActivity.theme = 0;
7136            mResolveActivity.exported = true;
7137            mResolveActivity.enabled = true;
7138            mResolveInfo.activityInfo = mResolveActivity;
7139            mResolveInfo.priority = 0;
7140            mResolveInfo.preferredOrder = 0;
7141            mResolveInfo.match = 0;
7142            mResolveComponentName = mCustomResolverComponentName;
7143            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7144                    mResolveComponentName);
7145        }
7146    }
7147
7148    private static String calculateBundledApkRoot(final String codePathString) {
7149        final File codePath = new File(codePathString);
7150        final File codeRoot;
7151        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7152            codeRoot = Environment.getRootDirectory();
7153        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7154            codeRoot = Environment.getOemDirectory();
7155        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7156            codeRoot = Environment.getVendorDirectory();
7157        } else {
7158            // Unrecognized code path; take its top real segment as the apk root:
7159            // e.g. /something/app/blah.apk => /something
7160            try {
7161                File f = codePath.getCanonicalFile();
7162                File parent = f.getParentFile();    // non-null because codePath is a file
7163                File tmp;
7164                while ((tmp = parent.getParentFile()) != null) {
7165                    f = parent;
7166                    parent = tmp;
7167                }
7168                codeRoot = f;
7169                Slog.w(TAG, "Unrecognized code path "
7170                        + codePath + " - using " + codeRoot);
7171            } catch (IOException e) {
7172                // Can't canonicalize the code path -- shenanigans?
7173                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7174                return Environment.getRootDirectory().getPath();
7175            }
7176        }
7177        return codeRoot.getPath();
7178    }
7179
7180    /**
7181     * Derive and set the location of native libraries for the given package,
7182     * which varies depending on where and how the package was installed.
7183     */
7184    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7185        final ApplicationInfo info = pkg.applicationInfo;
7186        final String codePath = pkg.codePath;
7187        final File codeFile = new File(codePath);
7188        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7189        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7190
7191        info.nativeLibraryRootDir = null;
7192        info.nativeLibraryRootRequiresIsa = false;
7193        info.nativeLibraryDir = null;
7194        info.secondaryNativeLibraryDir = null;
7195
7196        if (isApkFile(codeFile)) {
7197            // Monolithic install
7198            if (bundledApp) {
7199                // If "/system/lib64/apkname" exists, assume that is the per-package
7200                // native library directory to use; otherwise use "/system/lib/apkname".
7201                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7202                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7203                        getPrimaryInstructionSet(info));
7204
7205                // This is a bundled system app so choose the path based on the ABI.
7206                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7207                // is just the default path.
7208                final String apkName = deriveCodePathName(codePath);
7209                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7210                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7211                        apkName).getAbsolutePath();
7212
7213                if (info.secondaryCpuAbi != null) {
7214                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7215                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7216                            secondaryLibDir, apkName).getAbsolutePath();
7217                }
7218            } else if (asecApp) {
7219                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7220                        .getAbsolutePath();
7221            } else {
7222                final String apkName = deriveCodePathName(codePath);
7223                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7224                        .getAbsolutePath();
7225            }
7226
7227            info.nativeLibraryRootRequiresIsa = false;
7228            info.nativeLibraryDir = info.nativeLibraryRootDir;
7229        } else {
7230            // Cluster install
7231            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7232            info.nativeLibraryRootRequiresIsa = true;
7233
7234            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7235                    getPrimaryInstructionSet(info)).getAbsolutePath();
7236
7237            if (info.secondaryCpuAbi != null) {
7238                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7239                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7240            }
7241        }
7242    }
7243
7244    /**
7245     * Calculate the abis and roots for a bundled app. These can uniquely
7246     * be determined from the contents of the system partition, i.e whether
7247     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7248     * of this information, and instead assume that the system was built
7249     * sensibly.
7250     */
7251    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7252                                           PackageSetting pkgSetting) {
7253        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7254
7255        // If "/system/lib64/apkname" exists, assume that is the per-package
7256        // native library directory to use; otherwise use "/system/lib/apkname".
7257        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7258        setBundledAppAbi(pkg, apkRoot, apkName);
7259        // pkgSetting might be null during rescan following uninstall of updates
7260        // to a bundled app, so accommodate that possibility.  The settings in
7261        // that case will be established later from the parsed package.
7262        //
7263        // If the settings aren't null, sync them up with what we've just derived.
7264        // note that apkRoot isn't stored in the package settings.
7265        if (pkgSetting != null) {
7266            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7267            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7268        }
7269    }
7270
7271    /**
7272     * Deduces the ABI of a bundled app and sets the relevant fields on the
7273     * parsed pkg object.
7274     *
7275     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7276     *        under which system libraries are installed.
7277     * @param apkName the name of the installed package.
7278     */
7279    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7280        final File codeFile = new File(pkg.codePath);
7281
7282        final boolean has64BitLibs;
7283        final boolean has32BitLibs;
7284        if (isApkFile(codeFile)) {
7285            // Monolithic install
7286            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7287            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7288        } else {
7289            // Cluster install
7290            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7291            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7292                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7293                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7294                has64BitLibs = (new File(rootDir, isa)).exists();
7295            } else {
7296                has64BitLibs = false;
7297            }
7298            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7299                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7300                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7301                has32BitLibs = (new File(rootDir, isa)).exists();
7302            } else {
7303                has32BitLibs = false;
7304            }
7305        }
7306
7307        if (has64BitLibs && !has32BitLibs) {
7308            // The package has 64 bit libs, but not 32 bit libs. Its primary
7309            // ABI should be 64 bit. We can safely assume here that the bundled
7310            // native libraries correspond to the most preferred ABI in the list.
7311
7312            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7313            pkg.applicationInfo.secondaryCpuAbi = null;
7314        } else if (has32BitLibs && !has64BitLibs) {
7315            // The package has 32 bit libs but not 64 bit libs. Its primary
7316            // ABI should be 32 bit.
7317
7318            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7319            pkg.applicationInfo.secondaryCpuAbi = null;
7320        } else if (has32BitLibs && has64BitLibs) {
7321            // The application has both 64 and 32 bit bundled libraries. We check
7322            // here that the app declares multiArch support, and warn if it doesn't.
7323            //
7324            // We will be lenient here and record both ABIs. The primary will be the
7325            // ABI that's higher on the list, i.e, a device that's configured to prefer
7326            // 64 bit apps will see a 64 bit primary ABI,
7327
7328            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7329                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7330            }
7331
7332            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7333                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7334                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7335            } else {
7336                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7337                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7338            }
7339        } else {
7340            pkg.applicationInfo.primaryCpuAbi = null;
7341            pkg.applicationInfo.secondaryCpuAbi = null;
7342        }
7343    }
7344
7345    private void killApplication(String pkgName, int appId, String reason) {
7346        // Request the ActivityManager to kill the process(only for existing packages)
7347        // so that we do not end up in a confused state while the user is still using the older
7348        // version of the application while the new one gets installed.
7349        IActivityManager am = ActivityManagerNative.getDefault();
7350        if (am != null) {
7351            try {
7352                am.killApplicationWithAppId(pkgName, appId, reason);
7353            } catch (RemoteException e) {
7354            }
7355        }
7356    }
7357
7358    void removePackageLI(PackageSetting ps, boolean chatty) {
7359        if (DEBUG_INSTALL) {
7360            if (chatty)
7361                Log.d(TAG, "Removing package " + ps.name);
7362        }
7363
7364        // writer
7365        synchronized (mPackages) {
7366            mPackages.remove(ps.name);
7367            final PackageParser.Package pkg = ps.pkg;
7368            if (pkg != null) {
7369                cleanPackageDataStructuresLILPw(pkg, chatty);
7370            }
7371        }
7372    }
7373
7374    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7375        if (DEBUG_INSTALL) {
7376            if (chatty)
7377                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7378        }
7379
7380        // writer
7381        synchronized (mPackages) {
7382            mPackages.remove(pkg.applicationInfo.packageName);
7383            cleanPackageDataStructuresLILPw(pkg, chatty);
7384        }
7385    }
7386
7387    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7388        int N = pkg.providers.size();
7389        StringBuilder r = null;
7390        int i;
7391        for (i=0; i<N; i++) {
7392            PackageParser.Provider p = pkg.providers.get(i);
7393            mProviders.removeProvider(p);
7394            if (p.info.authority == null) {
7395
7396                /* There was another ContentProvider with this authority when
7397                 * this app was installed so this authority is null,
7398                 * Ignore it as we don't have to unregister the provider.
7399                 */
7400                continue;
7401            }
7402            String names[] = p.info.authority.split(";");
7403            for (int j = 0; j < names.length; j++) {
7404                if (mProvidersByAuthority.get(names[j]) == p) {
7405                    mProvidersByAuthority.remove(names[j]);
7406                    if (DEBUG_REMOVE) {
7407                        if (chatty)
7408                            Log.d(TAG, "Unregistered content provider: " + names[j]
7409                                    + ", className = " + p.info.name + ", isSyncable = "
7410                                    + p.info.isSyncable);
7411                    }
7412                }
7413            }
7414            if (DEBUG_REMOVE && chatty) {
7415                if (r == null) {
7416                    r = new StringBuilder(256);
7417                } else {
7418                    r.append(' ');
7419                }
7420                r.append(p.info.name);
7421            }
7422        }
7423        if (r != null) {
7424            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7425        }
7426
7427        N = pkg.services.size();
7428        r = null;
7429        for (i=0; i<N; i++) {
7430            PackageParser.Service s = pkg.services.get(i);
7431            mServices.removeService(s);
7432            if (chatty) {
7433                if (r == null) {
7434                    r = new StringBuilder(256);
7435                } else {
7436                    r.append(' ');
7437                }
7438                r.append(s.info.name);
7439            }
7440        }
7441        if (r != null) {
7442            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
7443        }
7444
7445        N = pkg.receivers.size();
7446        r = null;
7447        for (i=0; i<N; i++) {
7448            PackageParser.Activity a = pkg.receivers.get(i);
7449            mReceivers.removeActivity(a, "receiver");
7450            if (DEBUG_REMOVE && chatty) {
7451                if (r == null) {
7452                    r = new StringBuilder(256);
7453                } else {
7454                    r.append(' ');
7455                }
7456                r.append(a.info.name);
7457            }
7458        }
7459        if (r != null) {
7460            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
7461        }
7462
7463        N = pkg.activities.size();
7464        r = null;
7465        for (i=0; i<N; i++) {
7466            PackageParser.Activity a = pkg.activities.get(i);
7467            mActivities.removeActivity(a, "activity");
7468            if (DEBUG_REMOVE && chatty) {
7469                if (r == null) {
7470                    r = new StringBuilder(256);
7471                } else {
7472                    r.append(' ');
7473                }
7474                r.append(a.info.name);
7475            }
7476        }
7477        if (r != null) {
7478            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
7479        }
7480
7481        N = pkg.permissions.size();
7482        r = null;
7483        for (i=0; i<N; i++) {
7484            PackageParser.Permission p = pkg.permissions.get(i);
7485            BasePermission bp = mSettings.mPermissions.get(p.info.name);
7486            if (bp == null) {
7487                bp = mSettings.mPermissionTrees.get(p.info.name);
7488            }
7489            if (bp != null && bp.perm == p) {
7490                bp.perm = null;
7491                if (DEBUG_REMOVE && chatty) {
7492                    if (r == null) {
7493                        r = new StringBuilder(256);
7494                    } else {
7495                        r.append(' ');
7496                    }
7497                    r.append(p.info.name);
7498                }
7499            }
7500            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7501                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
7502                if (appOpPerms != null) {
7503                    appOpPerms.remove(pkg.packageName);
7504                }
7505            }
7506        }
7507        if (r != null) {
7508            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7509        }
7510
7511        N = pkg.requestedPermissions.size();
7512        r = null;
7513        for (i=0; i<N; i++) {
7514            String perm = pkg.requestedPermissions.get(i);
7515            BasePermission bp = mSettings.mPermissions.get(perm);
7516            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7517                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
7518                if (appOpPerms != null) {
7519                    appOpPerms.remove(pkg.packageName);
7520                    if (appOpPerms.isEmpty()) {
7521                        mAppOpPermissionPackages.remove(perm);
7522                    }
7523                }
7524            }
7525        }
7526        if (r != null) {
7527            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7528        }
7529
7530        N = pkg.instrumentation.size();
7531        r = null;
7532        for (i=0; i<N; i++) {
7533            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7534            mInstrumentation.remove(a.getComponentName());
7535            if (DEBUG_REMOVE && chatty) {
7536                if (r == null) {
7537                    r = new StringBuilder(256);
7538                } else {
7539                    r.append(' ');
7540                }
7541                r.append(a.info.name);
7542            }
7543        }
7544        if (r != null) {
7545            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
7546        }
7547
7548        r = null;
7549        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7550            // Only system apps can hold shared libraries.
7551            if (pkg.libraryNames != null) {
7552                for (i=0; i<pkg.libraryNames.size(); i++) {
7553                    String name = pkg.libraryNames.get(i);
7554                    SharedLibraryEntry cur = mSharedLibraries.get(name);
7555                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
7556                        mSharedLibraries.remove(name);
7557                        if (DEBUG_REMOVE && chatty) {
7558                            if (r == null) {
7559                                r = new StringBuilder(256);
7560                            } else {
7561                                r.append(' ');
7562                            }
7563                            r.append(name);
7564                        }
7565                    }
7566                }
7567            }
7568        }
7569        if (r != null) {
7570            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
7571        }
7572    }
7573
7574    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
7575        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
7576            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
7577                return true;
7578            }
7579        }
7580        return false;
7581    }
7582
7583    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
7584    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
7585    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
7586
7587    private void updatePermissionsLPw(String changingPkg,
7588            PackageParser.Package pkgInfo, int flags) {
7589        // Make sure there are no dangling permission trees.
7590        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
7591        while (it.hasNext()) {
7592            final BasePermission bp = it.next();
7593            if (bp.packageSetting == null) {
7594                // We may not yet have parsed the package, so just see if
7595                // we still know about its settings.
7596                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7597            }
7598            if (bp.packageSetting == null) {
7599                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
7600                        + " from package " + bp.sourcePackage);
7601                it.remove();
7602            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7603                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7604                    Slog.i(TAG, "Removing old permission tree: " + bp.name
7605                            + " from package " + bp.sourcePackage);
7606                    flags |= UPDATE_PERMISSIONS_ALL;
7607                    it.remove();
7608                }
7609            }
7610        }
7611
7612        // Make sure all dynamic permissions have been assigned to a package,
7613        // and make sure there are no dangling permissions.
7614        it = mSettings.mPermissions.values().iterator();
7615        while (it.hasNext()) {
7616            final BasePermission bp = it.next();
7617            if (bp.type == BasePermission.TYPE_DYNAMIC) {
7618                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
7619                        + bp.name + " pkg=" + bp.sourcePackage
7620                        + " info=" + bp.pendingInfo);
7621                if (bp.packageSetting == null && bp.pendingInfo != null) {
7622                    final BasePermission tree = findPermissionTreeLP(bp.name);
7623                    if (tree != null && tree.perm != null) {
7624                        bp.packageSetting = tree.packageSetting;
7625                        bp.perm = new PackageParser.Permission(tree.perm.owner,
7626                                new PermissionInfo(bp.pendingInfo));
7627                        bp.perm.info.packageName = tree.perm.info.packageName;
7628                        bp.perm.info.name = bp.name;
7629                        bp.uid = tree.uid;
7630                    }
7631                }
7632            }
7633            if (bp.packageSetting == null) {
7634                // We may not yet have parsed the package, so just see if
7635                // we still know about its settings.
7636                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7637            }
7638            if (bp.packageSetting == null) {
7639                Slog.w(TAG, "Removing dangling permission: " + bp.name
7640                        + " from package " + bp.sourcePackage);
7641                it.remove();
7642            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7643                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7644                    Slog.i(TAG, "Removing old permission: " + bp.name
7645                            + " from package " + bp.sourcePackage);
7646                    flags |= UPDATE_PERMISSIONS_ALL;
7647                    it.remove();
7648                }
7649            }
7650        }
7651
7652        // Now update the permissions for all packages, in particular
7653        // replace the granted permissions of the system packages.
7654        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
7655            for (PackageParser.Package pkg : mPackages.values()) {
7656                if (pkg != pkgInfo) {
7657                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
7658                            changingPkg);
7659                }
7660            }
7661        }
7662
7663        if (pkgInfo != null) {
7664            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
7665        }
7666    }
7667
7668    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
7669            String packageOfInterest) {
7670        // IMPORTANT: There are two types of permissions: install and runtime.
7671        // Install time permissions are granted when the app is installed to
7672        // all device users and users added in the future. Runtime permissions
7673        // are granted at runtime explicitly to specific users. Normal and signature
7674        // protected permissions are install time permissions. Dangerous permissions
7675        // are install permissions if the app's target SDK is Lollipop MR1 or older,
7676        // otherwise they are runtime permissions. This function does not manage
7677        // runtime permissions except for the case an app targeting Lollipop MR1
7678        // being upgraded to target a newer SDK, in which case dangerous permissions
7679        // are transformed from install time to runtime ones.
7680
7681        final PackageSetting ps = (PackageSetting) pkg.mExtras;
7682        if (ps == null) {
7683            return;
7684        }
7685
7686        PermissionsState permissionsState = ps.getPermissionsState();
7687        PermissionsState origPermissions = permissionsState;
7688
7689        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
7690
7691        int[] upgradeUserIds = EMPTY_INT_ARRAY;
7692        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
7693
7694        boolean changedInstallPermission = false;
7695
7696        if (replace) {
7697            ps.installPermissionsFixed = false;
7698            if (!ps.isSharedUser()) {
7699                origPermissions = new PermissionsState(permissionsState);
7700                permissionsState.reset();
7701            }
7702        }
7703
7704        permissionsState.setGlobalGids(mGlobalGids);
7705
7706        final int N = pkg.requestedPermissions.size();
7707        for (int i=0; i<N; i++) {
7708            final String name = pkg.requestedPermissions.get(i);
7709            final BasePermission bp = mSettings.mPermissions.get(name);
7710
7711            if (DEBUG_INSTALL) {
7712                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
7713            }
7714
7715            if (bp == null || bp.packageSetting == null) {
7716                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7717                    Slog.w(TAG, "Unknown permission " + name
7718                            + " in package " + pkg.packageName);
7719                }
7720                continue;
7721            }
7722
7723            final String perm = bp.name;
7724            boolean allowedSig = false;
7725            int grant = GRANT_DENIED;
7726
7727            // Keep track of app op permissions.
7728            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7729                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
7730                if (pkgs == null) {
7731                    pkgs = new ArraySet<>();
7732                    mAppOpPermissionPackages.put(bp.name, pkgs);
7733                }
7734                pkgs.add(pkg.packageName);
7735            }
7736
7737            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
7738            switch (level) {
7739                case PermissionInfo.PROTECTION_NORMAL: {
7740                    // For all apps normal permissions are install time ones.
7741                    grant = GRANT_INSTALL;
7742                } break;
7743
7744                case PermissionInfo.PROTECTION_DANGEROUS: {
7745                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
7746                        // For legacy apps dangerous permissions are install time ones.
7747                        grant = GRANT_INSTALL_LEGACY;
7748                    } else if (ps.isSystem()) {
7749                        final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds();
7750                        if (origPermissions.hasInstallPermission(bp.name)) {
7751                            // If a system app had an install permission, then the app was
7752                            // upgraded and we grant the permissions as runtime to all users.
7753                            grant = GRANT_UPGRADE;
7754                            upgradeUserIds = currentUserIds;
7755                        } else if (!Arrays.equals(updatedUserIds, currentUserIds)) {
7756                            // If users changed since the last permissions update for a
7757                            // system app, we grant the permission as runtime to the new users.
7758                            grant = GRANT_UPGRADE;
7759                            upgradeUserIds = currentUserIds;
7760                            for (int userId : updatedUserIds) {
7761                                upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId);
7762                            }
7763                        } else {
7764                            // Otherwise, we grant the permission as runtime if the app
7765                            // already had it, i.e. we preserve runtime permissions.
7766                            grant = GRANT_RUNTIME;
7767                        }
7768                    } else if (origPermissions.hasInstallPermission(bp.name)) {
7769                        // For legacy apps that became modern, install becomes runtime.
7770                        grant = GRANT_UPGRADE;
7771                        upgradeUserIds = currentUserIds;
7772                    } else if (replace) {
7773                        // For upgraded modern apps keep runtime permissions unchanged.
7774                        grant = GRANT_RUNTIME;
7775                    }
7776                } break;
7777
7778                case PermissionInfo.PROTECTION_SIGNATURE: {
7779                    // For all apps signature permissions are install time ones.
7780                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
7781                    if (allowedSig) {
7782                        grant = GRANT_INSTALL;
7783                    }
7784                } break;
7785            }
7786
7787            if (DEBUG_INSTALL) {
7788                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
7789            }
7790
7791            if (grant != GRANT_DENIED) {
7792                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
7793                    // If this is an existing, non-system package, then
7794                    // we can't add any new permissions to it.
7795                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
7796                        // Except...  if this is a permission that was added
7797                        // to the platform (note: need to only do this when
7798                        // updating the platform).
7799                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
7800                            grant = GRANT_DENIED;
7801                        }
7802                    }
7803                }
7804
7805                switch (grant) {
7806                    case GRANT_INSTALL: {
7807                        // Revoke this as runtime permission to handle the case of
7808                        // a runtime permssion being downgraded to an install one.
7809                        for (int userId : UserManagerService.getInstance().getUserIds()) {
7810                            if (origPermissions.getRuntimePermissionState(
7811                                    bp.name, userId) != null) {
7812                                // Revoke the runtime permission and clear the flags.
7813                                origPermissions.revokeRuntimePermission(bp, userId);
7814                                origPermissions.updatePermissionFlags(bp, userId,
7815                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
7816                                // If we revoked a permission permission, we have to write.
7817                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7818                                        changedRuntimePermissionUserIds, userId);
7819                            }
7820                        }
7821                        // Grant an install permission.
7822                        if (permissionsState.grantInstallPermission(bp) !=
7823                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
7824                            changedInstallPermission = true;
7825                        }
7826                    } break;
7827
7828                    case GRANT_INSTALL_LEGACY: {
7829                        // Grant an install permission.
7830                        if (permissionsState.grantInstallPermission(bp) !=
7831                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
7832                            changedInstallPermission = true;
7833                        }
7834                    } break;
7835
7836                    case GRANT_RUNTIME: {
7837                        // Grant previously granted runtime permissions.
7838                        for (int userId : UserManagerService.getInstance().getUserIds()) {
7839                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
7840                                PermissionState permissionState = origPermissions
7841                                        .getRuntimePermissionState(bp.name, userId);
7842                                final int flags = permissionState.getFlags();
7843                                if (permissionsState.grantRuntimePermission(bp, userId) ==
7844                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7845                                    // If we cannot put the permission as it was, we have to write.
7846                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7847                                            changedRuntimePermissionUserIds, userId);
7848                                } else {
7849                                    // System components not only get the permissions but
7850                                    // they are also fixed, so nothing can change that.
7851                                    final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg)
7852                                            ? flags
7853                                            : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
7854                                    // Propagate the permission flags.
7855                                    permissionsState.updatePermissionFlags(bp, userId,
7856                                            newFlags, newFlags);
7857                                }
7858                            }
7859                        }
7860                    } break;
7861
7862                    case GRANT_UPGRADE: {
7863                        // Grant runtime permissions for a previously held install permission.
7864                        PermissionState permissionState = origPermissions
7865                                .getInstallPermissionState(bp.name);
7866                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
7867
7868                        origPermissions.revokeInstallPermission(bp);
7869                        // We will be transferring the permission flags, so clear them.
7870                        origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
7871                                PackageManager.MASK_PERMISSION_FLAGS, 0);
7872
7873                        // If the permission is not to be promoted to runtime we ignore it and
7874                        // also its other flags as they are not applicable to install permissions.
7875                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
7876                            for (int userId : upgradeUserIds) {
7877                                if (permissionsState.grantRuntimePermission(bp, userId) !=
7878                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7879                                    // System components not only get the permissions but
7880                                    // they are also fixed so nothing can change that.
7881                                    final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg)
7882                                            ? flags
7883                                            : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
7884                                    // Transfer the permission flags.
7885                                    permissionsState.updatePermissionFlags(bp, userId,
7886                                            newFlags, newFlags);
7887                                    // If we granted the permission, we have to write.
7888                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7889                                            changedRuntimePermissionUserIds, userId);
7890                                }
7891                            }
7892                        }
7893                    } break;
7894
7895                    default: {
7896                        if (packageOfInterest == null
7897                                || packageOfInterest.equals(pkg.packageName)) {
7898                            Slog.w(TAG, "Not granting permission " + perm
7899                                    + " to package " + pkg.packageName
7900                                    + " because it was previously installed without");
7901                        }
7902                    } break;
7903                }
7904            } else {
7905                if (permissionsState.revokeInstallPermission(bp) !=
7906                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7907                    // Also drop the permission flags.
7908                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
7909                            PackageManager.MASK_PERMISSION_FLAGS, 0);
7910                    changedInstallPermission = true;
7911                    Slog.i(TAG, "Un-granting permission " + perm
7912                            + " from package " + pkg.packageName
7913                            + " (protectionLevel=" + bp.protectionLevel
7914                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7915                            + ")");
7916                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
7917                    // Don't print warning for app op permissions, since it is fine for them
7918                    // not to be granted, there is a UI for the user to decide.
7919                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7920                        Slog.w(TAG, "Not granting permission " + perm
7921                                + " to package " + pkg.packageName
7922                                + " (protectionLevel=" + bp.protectionLevel
7923                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7924                                + ")");
7925                    }
7926                }
7927            }
7928        }
7929
7930        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
7931                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
7932            // This is the first that we have heard about this package, so the
7933            // permissions we have now selected are fixed until explicitly
7934            // changed.
7935            ps.installPermissionsFixed = true;
7936        }
7937
7938        ps.setPermissionsUpdatedForUserIds(currentUserIds);
7939
7940        // Persist the runtime permissions state for users with changes.
7941        for (int userId : changedRuntimePermissionUserIds) {
7942            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
7943        }
7944    }
7945
7946    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
7947        boolean allowed = false;
7948        final int NP = PackageParser.NEW_PERMISSIONS.length;
7949        for (int ip=0; ip<NP; ip++) {
7950            final PackageParser.NewPermissionInfo npi
7951                    = PackageParser.NEW_PERMISSIONS[ip];
7952            if (npi.name.equals(perm)
7953                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
7954                allowed = true;
7955                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
7956                        + pkg.packageName);
7957                break;
7958            }
7959        }
7960        return allowed;
7961    }
7962
7963    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
7964            BasePermission bp, PermissionsState origPermissions) {
7965        boolean allowed;
7966        allowed = (compareSignatures(
7967                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
7968                        == PackageManager.SIGNATURE_MATCH)
7969                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
7970                        == PackageManager.SIGNATURE_MATCH);
7971        if (!allowed && (bp.protectionLevel
7972                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
7973            if (isSystemApp(pkg)) {
7974                // For updated system applications, a system permission
7975                // is granted only if it had been defined by the original application.
7976                if (pkg.isUpdatedSystemApp()) {
7977                    final PackageSetting sysPs = mSettings
7978                            .getDisabledSystemPkgLPr(pkg.packageName);
7979                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
7980                        // If the original was granted this permission, we take
7981                        // that grant decision as read and propagate it to the
7982                        // update.
7983                        if (sysPs.isPrivileged()) {
7984                            allowed = true;
7985                        }
7986                    } else {
7987                        // The system apk may have been updated with an older
7988                        // version of the one on the data partition, but which
7989                        // granted a new system permission that it didn't have
7990                        // before.  In this case we do want to allow the app to
7991                        // now get the new permission if the ancestral apk is
7992                        // privileged to get it.
7993                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
7994                            for (int j=0;
7995                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
7996                                if (perm.equals(
7997                                        sysPs.pkg.requestedPermissions.get(j))) {
7998                                    allowed = true;
7999                                    break;
8000                                }
8001                            }
8002                        }
8003                    }
8004                } else {
8005                    allowed = isPrivilegedApp(pkg);
8006                }
8007            }
8008        }
8009        if (!allowed && (bp.protectionLevel
8010                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8011            // For development permissions, a development permission
8012            // is granted only if it was already granted.
8013            allowed = origPermissions.hasInstallPermission(perm);
8014        }
8015        return allowed;
8016    }
8017
8018    final class ActivityIntentResolver
8019            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8020        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8021                boolean defaultOnly, int userId) {
8022            if (!sUserManager.exists(userId)) return null;
8023            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8024            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8025        }
8026
8027        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8028                int userId) {
8029            if (!sUserManager.exists(userId)) return null;
8030            mFlags = flags;
8031            return super.queryIntent(intent, resolvedType,
8032                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8033        }
8034
8035        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8036                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8037            if (!sUserManager.exists(userId)) return null;
8038            if (packageActivities == null) {
8039                return null;
8040            }
8041            mFlags = flags;
8042            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8043            final int N = packageActivities.size();
8044            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8045                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8046
8047            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8048            for (int i = 0; i < N; ++i) {
8049                intentFilters = packageActivities.get(i).intents;
8050                if (intentFilters != null && intentFilters.size() > 0) {
8051                    PackageParser.ActivityIntentInfo[] array =
8052                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8053                    intentFilters.toArray(array);
8054                    listCut.add(array);
8055                }
8056            }
8057            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8058        }
8059
8060        public final void addActivity(PackageParser.Activity a, String type) {
8061            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8062            mActivities.put(a.getComponentName(), a);
8063            if (DEBUG_SHOW_INFO)
8064                Log.v(
8065                TAG, "  " + type + " " +
8066                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8067            if (DEBUG_SHOW_INFO)
8068                Log.v(TAG, "    Class=" + a.info.name);
8069            final int NI = a.intents.size();
8070            for (int j=0; j<NI; j++) {
8071                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8072                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8073                    intent.setPriority(0);
8074                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8075                            + a.className + " with priority > 0, forcing to 0");
8076                }
8077                if (DEBUG_SHOW_INFO) {
8078                    Log.v(TAG, "    IntentFilter:");
8079                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8080                }
8081                if (!intent.debugCheck()) {
8082                    Log.w(TAG, "==> For Activity " + a.info.name);
8083                }
8084                addFilter(intent);
8085            }
8086        }
8087
8088        public final void removeActivity(PackageParser.Activity a, String type) {
8089            mActivities.remove(a.getComponentName());
8090            if (DEBUG_SHOW_INFO) {
8091                Log.v(TAG, "  " + type + " "
8092                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8093                                : a.info.name) + ":");
8094                Log.v(TAG, "    Class=" + a.info.name);
8095            }
8096            final int NI = a.intents.size();
8097            for (int j=0; j<NI; j++) {
8098                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8099                if (DEBUG_SHOW_INFO) {
8100                    Log.v(TAG, "    IntentFilter:");
8101                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8102                }
8103                removeFilter(intent);
8104            }
8105        }
8106
8107        @Override
8108        protected boolean allowFilterResult(
8109                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8110            ActivityInfo filterAi = filter.activity.info;
8111            for (int i=dest.size()-1; i>=0; i--) {
8112                ActivityInfo destAi = dest.get(i).activityInfo;
8113                if (destAi.name == filterAi.name
8114                        && destAi.packageName == filterAi.packageName) {
8115                    return false;
8116                }
8117            }
8118            return true;
8119        }
8120
8121        @Override
8122        protected ActivityIntentInfo[] newArray(int size) {
8123            return new ActivityIntentInfo[size];
8124        }
8125
8126        @Override
8127        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8128            if (!sUserManager.exists(userId)) return true;
8129            PackageParser.Package p = filter.activity.owner;
8130            if (p != null) {
8131                PackageSetting ps = (PackageSetting)p.mExtras;
8132                if (ps != null) {
8133                    // System apps are never considered stopped for purposes of
8134                    // filtering, because there may be no way for the user to
8135                    // actually re-launch them.
8136                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8137                            && ps.getStopped(userId);
8138                }
8139            }
8140            return false;
8141        }
8142
8143        @Override
8144        protected boolean isPackageForFilter(String packageName,
8145                PackageParser.ActivityIntentInfo info) {
8146            return packageName.equals(info.activity.owner.packageName);
8147        }
8148
8149        @Override
8150        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8151                int match, int userId) {
8152            if (!sUserManager.exists(userId)) return null;
8153            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8154                return null;
8155            }
8156            final PackageParser.Activity activity = info.activity;
8157            if (mSafeMode && (activity.info.applicationInfo.flags
8158                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8159                return null;
8160            }
8161            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8162            if (ps == null) {
8163                return null;
8164            }
8165            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8166                    ps.readUserState(userId), userId);
8167            if (ai == null) {
8168                return null;
8169            }
8170            final ResolveInfo res = new ResolveInfo();
8171            res.activityInfo = ai;
8172            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8173                res.filter = info;
8174            }
8175            if (info != null) {
8176                res.handleAllWebDataURI = info.handleAllWebDataURI();
8177            }
8178            res.priority = info.getPriority();
8179            res.preferredOrder = activity.owner.mPreferredOrder;
8180            //System.out.println("Result: " + res.activityInfo.className +
8181            //                   " = " + res.priority);
8182            res.match = match;
8183            res.isDefault = info.hasDefault;
8184            res.labelRes = info.labelRes;
8185            res.nonLocalizedLabel = info.nonLocalizedLabel;
8186            if (userNeedsBadging(userId)) {
8187                res.noResourceId = true;
8188            } else {
8189                res.icon = info.icon;
8190            }
8191            res.system = res.activityInfo.applicationInfo.isSystemApp();
8192            return res;
8193        }
8194
8195        @Override
8196        protected void sortResults(List<ResolveInfo> results) {
8197            Collections.sort(results, mResolvePrioritySorter);
8198        }
8199
8200        @Override
8201        protected void dumpFilter(PrintWriter out, String prefix,
8202                PackageParser.ActivityIntentInfo filter) {
8203            out.print(prefix); out.print(
8204                    Integer.toHexString(System.identityHashCode(filter.activity)));
8205                    out.print(' ');
8206                    filter.activity.printComponentShortName(out);
8207                    out.print(" filter ");
8208                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8209        }
8210
8211        @Override
8212        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8213            return filter.activity;
8214        }
8215
8216        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8217            PackageParser.Activity activity = (PackageParser.Activity)label;
8218            out.print(prefix); out.print(
8219                    Integer.toHexString(System.identityHashCode(activity)));
8220                    out.print(' ');
8221                    activity.printComponentShortName(out);
8222            if (count > 1) {
8223                out.print(" ("); out.print(count); out.print(" filters)");
8224            }
8225            out.println();
8226        }
8227
8228//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8229//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8230//            final List<ResolveInfo> retList = Lists.newArrayList();
8231//            while (i.hasNext()) {
8232//                final ResolveInfo resolveInfo = i.next();
8233//                if (isEnabledLP(resolveInfo.activityInfo)) {
8234//                    retList.add(resolveInfo);
8235//                }
8236//            }
8237//            return retList;
8238//        }
8239
8240        // Keys are String (activity class name), values are Activity.
8241        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8242                = new ArrayMap<ComponentName, PackageParser.Activity>();
8243        private int mFlags;
8244    }
8245
8246    private final class ServiceIntentResolver
8247            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8248        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8249                boolean defaultOnly, int userId) {
8250            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8251            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8252        }
8253
8254        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8255                int userId) {
8256            if (!sUserManager.exists(userId)) return null;
8257            mFlags = flags;
8258            return super.queryIntent(intent, resolvedType,
8259                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8260        }
8261
8262        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8263                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8264            if (!sUserManager.exists(userId)) return null;
8265            if (packageServices == null) {
8266                return null;
8267            }
8268            mFlags = flags;
8269            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8270            final int N = packageServices.size();
8271            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8272                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8273
8274            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8275            for (int i = 0; i < N; ++i) {
8276                intentFilters = packageServices.get(i).intents;
8277                if (intentFilters != null && intentFilters.size() > 0) {
8278                    PackageParser.ServiceIntentInfo[] array =
8279                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8280                    intentFilters.toArray(array);
8281                    listCut.add(array);
8282                }
8283            }
8284            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8285        }
8286
8287        public final void addService(PackageParser.Service s) {
8288            mServices.put(s.getComponentName(), s);
8289            if (DEBUG_SHOW_INFO) {
8290                Log.v(TAG, "  "
8291                        + (s.info.nonLocalizedLabel != null
8292                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8293                Log.v(TAG, "    Class=" + s.info.name);
8294            }
8295            final int NI = s.intents.size();
8296            int j;
8297            for (j=0; j<NI; j++) {
8298                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8299                if (DEBUG_SHOW_INFO) {
8300                    Log.v(TAG, "    IntentFilter:");
8301                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8302                }
8303                if (!intent.debugCheck()) {
8304                    Log.w(TAG, "==> For Service " + s.info.name);
8305                }
8306                addFilter(intent);
8307            }
8308        }
8309
8310        public final void removeService(PackageParser.Service s) {
8311            mServices.remove(s.getComponentName());
8312            if (DEBUG_SHOW_INFO) {
8313                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8314                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8315                Log.v(TAG, "    Class=" + s.info.name);
8316            }
8317            final int NI = s.intents.size();
8318            int j;
8319            for (j=0; j<NI; j++) {
8320                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8321                if (DEBUG_SHOW_INFO) {
8322                    Log.v(TAG, "    IntentFilter:");
8323                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8324                }
8325                removeFilter(intent);
8326            }
8327        }
8328
8329        @Override
8330        protected boolean allowFilterResult(
8331                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8332            ServiceInfo filterSi = filter.service.info;
8333            for (int i=dest.size()-1; i>=0; i--) {
8334                ServiceInfo destAi = dest.get(i).serviceInfo;
8335                if (destAi.name == filterSi.name
8336                        && destAi.packageName == filterSi.packageName) {
8337                    return false;
8338                }
8339            }
8340            return true;
8341        }
8342
8343        @Override
8344        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8345            return new PackageParser.ServiceIntentInfo[size];
8346        }
8347
8348        @Override
8349        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8350            if (!sUserManager.exists(userId)) return true;
8351            PackageParser.Package p = filter.service.owner;
8352            if (p != null) {
8353                PackageSetting ps = (PackageSetting)p.mExtras;
8354                if (ps != null) {
8355                    // System apps are never considered stopped for purposes of
8356                    // filtering, because there may be no way for the user to
8357                    // actually re-launch them.
8358                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8359                            && ps.getStopped(userId);
8360                }
8361            }
8362            return false;
8363        }
8364
8365        @Override
8366        protected boolean isPackageForFilter(String packageName,
8367                PackageParser.ServiceIntentInfo info) {
8368            return packageName.equals(info.service.owner.packageName);
8369        }
8370
8371        @Override
8372        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8373                int match, int userId) {
8374            if (!sUserManager.exists(userId)) return null;
8375            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8376            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8377                return null;
8378            }
8379            final PackageParser.Service service = info.service;
8380            if (mSafeMode && (service.info.applicationInfo.flags
8381                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8382                return null;
8383            }
8384            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8385            if (ps == null) {
8386                return null;
8387            }
8388            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8389                    ps.readUserState(userId), userId);
8390            if (si == null) {
8391                return null;
8392            }
8393            final ResolveInfo res = new ResolveInfo();
8394            res.serviceInfo = si;
8395            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8396                res.filter = filter;
8397            }
8398            res.priority = info.getPriority();
8399            res.preferredOrder = service.owner.mPreferredOrder;
8400            res.match = match;
8401            res.isDefault = info.hasDefault;
8402            res.labelRes = info.labelRes;
8403            res.nonLocalizedLabel = info.nonLocalizedLabel;
8404            res.icon = info.icon;
8405            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8406            return res;
8407        }
8408
8409        @Override
8410        protected void sortResults(List<ResolveInfo> results) {
8411            Collections.sort(results, mResolvePrioritySorter);
8412        }
8413
8414        @Override
8415        protected void dumpFilter(PrintWriter out, String prefix,
8416                PackageParser.ServiceIntentInfo filter) {
8417            out.print(prefix); out.print(
8418                    Integer.toHexString(System.identityHashCode(filter.service)));
8419                    out.print(' ');
8420                    filter.service.printComponentShortName(out);
8421                    out.print(" filter ");
8422                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8423        }
8424
8425        @Override
8426        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8427            return filter.service;
8428        }
8429
8430        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8431            PackageParser.Service service = (PackageParser.Service)label;
8432            out.print(prefix); out.print(
8433                    Integer.toHexString(System.identityHashCode(service)));
8434                    out.print(' ');
8435                    service.printComponentShortName(out);
8436            if (count > 1) {
8437                out.print(" ("); out.print(count); out.print(" filters)");
8438            }
8439            out.println();
8440        }
8441
8442//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8443//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8444//            final List<ResolveInfo> retList = Lists.newArrayList();
8445//            while (i.hasNext()) {
8446//                final ResolveInfo resolveInfo = (ResolveInfo) i;
8447//                if (isEnabledLP(resolveInfo.serviceInfo)) {
8448//                    retList.add(resolveInfo);
8449//                }
8450//            }
8451//            return retList;
8452//        }
8453
8454        // Keys are String (activity class name), values are Activity.
8455        private final ArrayMap<ComponentName, PackageParser.Service> mServices
8456                = new ArrayMap<ComponentName, PackageParser.Service>();
8457        private int mFlags;
8458    };
8459
8460    private final class ProviderIntentResolver
8461            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
8462        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8463                boolean defaultOnly, int userId) {
8464            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8465            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8466        }
8467
8468        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8469                int userId) {
8470            if (!sUserManager.exists(userId))
8471                return null;
8472            mFlags = flags;
8473            return super.queryIntent(intent, resolvedType,
8474                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8475        }
8476
8477        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8478                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
8479            if (!sUserManager.exists(userId))
8480                return null;
8481            if (packageProviders == null) {
8482                return null;
8483            }
8484            mFlags = flags;
8485            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
8486            final int N = packageProviders.size();
8487            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
8488                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
8489
8490            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
8491            for (int i = 0; i < N; ++i) {
8492                intentFilters = packageProviders.get(i).intents;
8493                if (intentFilters != null && intentFilters.size() > 0) {
8494                    PackageParser.ProviderIntentInfo[] array =
8495                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
8496                    intentFilters.toArray(array);
8497                    listCut.add(array);
8498                }
8499            }
8500            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8501        }
8502
8503        public final void addProvider(PackageParser.Provider p) {
8504            if (mProviders.containsKey(p.getComponentName())) {
8505                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
8506                return;
8507            }
8508
8509            mProviders.put(p.getComponentName(), p);
8510            if (DEBUG_SHOW_INFO) {
8511                Log.v(TAG, "  "
8512                        + (p.info.nonLocalizedLabel != null
8513                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
8514                Log.v(TAG, "    Class=" + p.info.name);
8515            }
8516            final int NI = p.intents.size();
8517            int j;
8518            for (j = 0; j < NI; j++) {
8519                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8520                if (DEBUG_SHOW_INFO) {
8521                    Log.v(TAG, "    IntentFilter:");
8522                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8523                }
8524                if (!intent.debugCheck()) {
8525                    Log.w(TAG, "==> For Provider " + p.info.name);
8526                }
8527                addFilter(intent);
8528            }
8529        }
8530
8531        public final void removeProvider(PackageParser.Provider p) {
8532            mProviders.remove(p.getComponentName());
8533            if (DEBUG_SHOW_INFO) {
8534                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
8535                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
8536                Log.v(TAG, "    Class=" + p.info.name);
8537            }
8538            final int NI = p.intents.size();
8539            int j;
8540            for (j = 0; j < NI; j++) {
8541                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8542                if (DEBUG_SHOW_INFO) {
8543                    Log.v(TAG, "    IntentFilter:");
8544                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8545                }
8546                removeFilter(intent);
8547            }
8548        }
8549
8550        @Override
8551        protected boolean allowFilterResult(
8552                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
8553            ProviderInfo filterPi = filter.provider.info;
8554            for (int i = dest.size() - 1; i >= 0; i--) {
8555                ProviderInfo destPi = dest.get(i).providerInfo;
8556                if (destPi.name == filterPi.name
8557                        && destPi.packageName == filterPi.packageName) {
8558                    return false;
8559                }
8560            }
8561            return true;
8562        }
8563
8564        @Override
8565        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
8566            return new PackageParser.ProviderIntentInfo[size];
8567        }
8568
8569        @Override
8570        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
8571            if (!sUserManager.exists(userId))
8572                return true;
8573            PackageParser.Package p = filter.provider.owner;
8574            if (p != null) {
8575                PackageSetting ps = (PackageSetting) p.mExtras;
8576                if (ps != null) {
8577                    // System apps are never considered stopped for purposes of
8578                    // filtering, because there may be no way for the user to
8579                    // actually re-launch them.
8580                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8581                            && ps.getStopped(userId);
8582                }
8583            }
8584            return false;
8585        }
8586
8587        @Override
8588        protected boolean isPackageForFilter(String packageName,
8589                PackageParser.ProviderIntentInfo info) {
8590            return packageName.equals(info.provider.owner.packageName);
8591        }
8592
8593        @Override
8594        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
8595                int match, int userId) {
8596            if (!sUserManager.exists(userId))
8597                return null;
8598            final PackageParser.ProviderIntentInfo info = filter;
8599            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
8600                return null;
8601            }
8602            final PackageParser.Provider provider = info.provider;
8603            if (mSafeMode && (provider.info.applicationInfo.flags
8604                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
8605                return null;
8606            }
8607            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
8608            if (ps == null) {
8609                return null;
8610            }
8611            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
8612                    ps.readUserState(userId), userId);
8613            if (pi == null) {
8614                return null;
8615            }
8616            final ResolveInfo res = new ResolveInfo();
8617            res.providerInfo = pi;
8618            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
8619                res.filter = filter;
8620            }
8621            res.priority = info.getPriority();
8622            res.preferredOrder = provider.owner.mPreferredOrder;
8623            res.match = match;
8624            res.isDefault = info.hasDefault;
8625            res.labelRes = info.labelRes;
8626            res.nonLocalizedLabel = info.nonLocalizedLabel;
8627            res.icon = info.icon;
8628            res.system = res.providerInfo.applicationInfo.isSystemApp();
8629            return res;
8630        }
8631
8632        @Override
8633        protected void sortResults(List<ResolveInfo> results) {
8634            Collections.sort(results, mResolvePrioritySorter);
8635        }
8636
8637        @Override
8638        protected void dumpFilter(PrintWriter out, String prefix,
8639                PackageParser.ProviderIntentInfo filter) {
8640            out.print(prefix);
8641            out.print(
8642                    Integer.toHexString(System.identityHashCode(filter.provider)));
8643            out.print(' ');
8644            filter.provider.printComponentShortName(out);
8645            out.print(" filter ");
8646            out.println(Integer.toHexString(System.identityHashCode(filter)));
8647        }
8648
8649        @Override
8650        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
8651            return filter.provider;
8652        }
8653
8654        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8655            PackageParser.Provider provider = (PackageParser.Provider)label;
8656            out.print(prefix); out.print(
8657                    Integer.toHexString(System.identityHashCode(provider)));
8658                    out.print(' ');
8659                    provider.printComponentShortName(out);
8660            if (count > 1) {
8661                out.print(" ("); out.print(count); out.print(" filters)");
8662            }
8663            out.println();
8664        }
8665
8666        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
8667                = new ArrayMap<ComponentName, PackageParser.Provider>();
8668        private int mFlags;
8669    };
8670
8671    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
8672            new Comparator<ResolveInfo>() {
8673        public int compare(ResolveInfo r1, ResolveInfo r2) {
8674            int v1 = r1.priority;
8675            int v2 = r2.priority;
8676            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
8677            if (v1 != v2) {
8678                return (v1 > v2) ? -1 : 1;
8679            }
8680            v1 = r1.preferredOrder;
8681            v2 = r2.preferredOrder;
8682            if (v1 != v2) {
8683                return (v1 > v2) ? -1 : 1;
8684            }
8685            if (r1.isDefault != r2.isDefault) {
8686                return r1.isDefault ? -1 : 1;
8687            }
8688            v1 = r1.match;
8689            v2 = r2.match;
8690            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
8691            if (v1 != v2) {
8692                return (v1 > v2) ? -1 : 1;
8693            }
8694            if (r1.system != r2.system) {
8695                return r1.system ? -1 : 1;
8696            }
8697            return 0;
8698        }
8699    };
8700
8701    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
8702            new Comparator<ProviderInfo>() {
8703        public int compare(ProviderInfo p1, ProviderInfo p2) {
8704            final int v1 = p1.initOrder;
8705            final int v2 = p2.initOrder;
8706            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
8707        }
8708    };
8709
8710    final void sendPackageBroadcast(final String action, final String pkg,
8711            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
8712            final int[] userIds) {
8713        mHandler.post(new Runnable() {
8714            @Override
8715            public void run() {
8716                try {
8717                    final IActivityManager am = ActivityManagerNative.getDefault();
8718                    if (am == null) return;
8719                    final int[] resolvedUserIds;
8720                    if (userIds == null) {
8721                        resolvedUserIds = am.getRunningUserIds();
8722                    } else {
8723                        resolvedUserIds = userIds;
8724                    }
8725                    for (int id : resolvedUserIds) {
8726                        final Intent intent = new Intent(action,
8727                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
8728                        if (extras != null) {
8729                            intent.putExtras(extras);
8730                        }
8731                        if (targetPkg != null) {
8732                            intent.setPackage(targetPkg);
8733                        }
8734                        // Modify the UID when posting to other users
8735                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
8736                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
8737                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
8738                            intent.putExtra(Intent.EXTRA_UID, uid);
8739                        }
8740                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
8741                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
8742                        if (DEBUG_BROADCASTS) {
8743                            RuntimeException here = new RuntimeException("here");
8744                            here.fillInStackTrace();
8745                            Slog.d(TAG, "Sending to user " + id + ": "
8746                                    + intent.toShortString(false, true, false, false)
8747                                    + " " + intent.getExtras(), here);
8748                        }
8749                        am.broadcastIntent(null, intent, null, finishedReceiver,
8750                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
8751                                finishedReceiver != null, false, id);
8752                    }
8753                } catch (RemoteException ex) {
8754                }
8755            }
8756        });
8757    }
8758
8759    /**
8760     * Check if the external storage media is available. This is true if there
8761     * is a mounted external storage medium or if the external storage is
8762     * emulated.
8763     */
8764    private boolean isExternalMediaAvailable() {
8765        return mMediaMounted || Environment.isExternalStorageEmulated();
8766    }
8767
8768    @Override
8769    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
8770        // writer
8771        synchronized (mPackages) {
8772            if (!isExternalMediaAvailable()) {
8773                // If the external storage is no longer mounted at this point,
8774                // the caller may not have been able to delete all of this
8775                // packages files and can not delete any more.  Bail.
8776                return null;
8777            }
8778            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
8779            if (lastPackage != null) {
8780                pkgs.remove(lastPackage);
8781            }
8782            if (pkgs.size() > 0) {
8783                return pkgs.get(0);
8784            }
8785        }
8786        return null;
8787    }
8788
8789    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
8790        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
8791                userId, andCode ? 1 : 0, packageName);
8792        if (mSystemReady) {
8793            msg.sendToTarget();
8794        } else {
8795            if (mPostSystemReadyMessages == null) {
8796                mPostSystemReadyMessages = new ArrayList<>();
8797            }
8798            mPostSystemReadyMessages.add(msg);
8799        }
8800    }
8801
8802    void startCleaningPackages() {
8803        // reader
8804        synchronized (mPackages) {
8805            if (!isExternalMediaAvailable()) {
8806                return;
8807            }
8808            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
8809                return;
8810            }
8811        }
8812        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
8813        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
8814        IActivityManager am = ActivityManagerNative.getDefault();
8815        if (am != null) {
8816            try {
8817                am.startService(null, intent, null, UserHandle.USER_OWNER);
8818            } catch (RemoteException e) {
8819            }
8820        }
8821    }
8822
8823    @Override
8824    public void installPackage(String originPath, IPackageInstallObserver2 observer,
8825            int installFlags, String installerPackageName, VerificationParams verificationParams,
8826            String packageAbiOverride) {
8827        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
8828                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
8829    }
8830
8831    @Override
8832    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
8833            int installFlags, String installerPackageName, VerificationParams verificationParams,
8834            String packageAbiOverride, int userId) {
8835        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
8836
8837        final int callingUid = Binder.getCallingUid();
8838        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
8839
8840        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8841            try {
8842                if (observer != null) {
8843                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
8844                }
8845            } catch (RemoteException re) {
8846            }
8847            return;
8848        }
8849
8850        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
8851            installFlags |= PackageManager.INSTALL_FROM_ADB;
8852
8853        } else {
8854            // Caller holds INSTALL_PACKAGES permission, so we're less strict
8855            // about installerPackageName.
8856
8857            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
8858            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
8859        }
8860
8861        UserHandle user;
8862        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
8863            user = UserHandle.ALL;
8864        } else {
8865            user = new UserHandle(userId);
8866        }
8867
8868        // Only system components can circumvent runtime permissions when installing.
8869        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
8870                && mContext.checkCallingOrSelfPermission(Manifest.permission
8871                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
8872            throw new SecurityException("You need the "
8873                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
8874                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
8875        }
8876
8877        verificationParams.setInstallerUid(callingUid);
8878
8879        final File originFile = new File(originPath);
8880        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
8881
8882        final Message msg = mHandler.obtainMessage(INIT_COPY);
8883        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
8884                null, verificationParams, user, packageAbiOverride);
8885        mHandler.sendMessage(msg);
8886    }
8887
8888    void installStage(String packageName, File stagedDir, String stagedCid,
8889            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
8890            String installerPackageName, int installerUid, UserHandle user) {
8891        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
8892                params.referrerUri, installerUid, null);
8893
8894        final OriginInfo origin;
8895        if (stagedDir != null) {
8896            origin = OriginInfo.fromStagedFile(stagedDir);
8897        } else {
8898            origin = OriginInfo.fromStagedContainer(stagedCid);
8899        }
8900
8901        final Message msg = mHandler.obtainMessage(INIT_COPY);
8902        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
8903                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
8904        mHandler.sendMessage(msg);
8905    }
8906
8907    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
8908        Bundle extras = new Bundle(1);
8909        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
8910
8911        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
8912                packageName, extras, null, null, new int[] {userId});
8913        try {
8914            IActivityManager am = ActivityManagerNative.getDefault();
8915            final boolean isSystem =
8916                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
8917            if (isSystem && am.isUserRunning(userId, false)) {
8918                // The just-installed/enabled app is bundled on the system, so presumed
8919                // to be able to run automatically without needing an explicit launch.
8920                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
8921                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
8922                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
8923                        .setPackage(packageName);
8924                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
8925                        android.app.AppOpsManager.OP_NONE, false, false, userId);
8926            }
8927        } catch (RemoteException e) {
8928            // shouldn't happen
8929            Slog.w(TAG, "Unable to bootstrap installed package", e);
8930        }
8931    }
8932
8933    @Override
8934    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
8935            int userId) {
8936        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8937        PackageSetting pkgSetting;
8938        final int uid = Binder.getCallingUid();
8939        enforceCrossUserPermission(uid, userId, true, true,
8940                "setApplicationHiddenSetting for user " + userId);
8941
8942        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
8943            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
8944            return false;
8945        }
8946
8947        long callingId = Binder.clearCallingIdentity();
8948        try {
8949            boolean sendAdded = false;
8950            boolean sendRemoved = false;
8951            // writer
8952            synchronized (mPackages) {
8953                pkgSetting = mSettings.mPackages.get(packageName);
8954                if (pkgSetting == null) {
8955                    return false;
8956                }
8957                if (pkgSetting.getHidden(userId) != hidden) {
8958                    pkgSetting.setHidden(hidden, userId);
8959                    mSettings.writePackageRestrictionsLPr(userId);
8960                    if (hidden) {
8961                        sendRemoved = true;
8962                    } else {
8963                        sendAdded = true;
8964                    }
8965                }
8966            }
8967            if (sendAdded) {
8968                sendPackageAddedForUser(packageName, pkgSetting, userId);
8969                return true;
8970            }
8971            if (sendRemoved) {
8972                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
8973                        "hiding pkg");
8974                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
8975            }
8976        } finally {
8977            Binder.restoreCallingIdentity(callingId);
8978        }
8979        return false;
8980    }
8981
8982    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
8983            int userId) {
8984        final PackageRemovedInfo info = new PackageRemovedInfo();
8985        info.removedPackage = packageName;
8986        info.removedUsers = new int[] {userId};
8987        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
8988        info.sendBroadcast(false, false, false);
8989    }
8990
8991    /**
8992     * Returns true if application is not found or there was an error. Otherwise it returns
8993     * the hidden state of the package for the given user.
8994     */
8995    @Override
8996    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
8997        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8998        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
8999                false, "getApplicationHidden for user " + userId);
9000        PackageSetting pkgSetting;
9001        long callingId = Binder.clearCallingIdentity();
9002        try {
9003            // writer
9004            synchronized (mPackages) {
9005                pkgSetting = mSettings.mPackages.get(packageName);
9006                if (pkgSetting == null) {
9007                    return true;
9008                }
9009                return pkgSetting.getHidden(userId);
9010            }
9011        } finally {
9012            Binder.restoreCallingIdentity(callingId);
9013        }
9014    }
9015
9016    /**
9017     * @hide
9018     */
9019    @Override
9020    public int installExistingPackageAsUser(String packageName, int userId) {
9021        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9022                null);
9023        PackageSetting pkgSetting;
9024        final int uid = Binder.getCallingUid();
9025        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9026                + userId);
9027        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9028            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9029        }
9030
9031        long callingId = Binder.clearCallingIdentity();
9032        try {
9033            boolean sendAdded = false;
9034
9035            // writer
9036            synchronized (mPackages) {
9037                pkgSetting = mSettings.mPackages.get(packageName);
9038                if (pkgSetting == null) {
9039                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9040                }
9041                if (!pkgSetting.getInstalled(userId)) {
9042                    pkgSetting.setInstalled(true, userId);
9043                    pkgSetting.setHidden(false, userId);
9044                    mSettings.writePackageRestrictionsLPr(userId);
9045                    sendAdded = true;
9046                }
9047            }
9048
9049            if (sendAdded) {
9050                sendPackageAddedForUser(packageName, pkgSetting, userId);
9051            }
9052        } finally {
9053            Binder.restoreCallingIdentity(callingId);
9054        }
9055
9056        return PackageManager.INSTALL_SUCCEEDED;
9057    }
9058
9059    boolean isUserRestricted(int userId, String restrictionKey) {
9060        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9061        if (restrictions.getBoolean(restrictionKey, false)) {
9062            Log.w(TAG, "User is restricted: " + restrictionKey);
9063            return true;
9064        }
9065        return false;
9066    }
9067
9068    @Override
9069    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9070        mContext.enforceCallingOrSelfPermission(
9071                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9072                "Only package verification agents can verify applications");
9073
9074        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9075        final PackageVerificationResponse response = new PackageVerificationResponse(
9076                verificationCode, Binder.getCallingUid());
9077        msg.arg1 = id;
9078        msg.obj = response;
9079        mHandler.sendMessage(msg);
9080    }
9081
9082    @Override
9083    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9084            long millisecondsToDelay) {
9085        mContext.enforceCallingOrSelfPermission(
9086                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9087                "Only package verification agents can extend verification timeouts");
9088
9089        final PackageVerificationState state = mPendingVerification.get(id);
9090        final PackageVerificationResponse response = new PackageVerificationResponse(
9091                verificationCodeAtTimeout, Binder.getCallingUid());
9092
9093        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9094            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9095        }
9096        if (millisecondsToDelay < 0) {
9097            millisecondsToDelay = 0;
9098        }
9099        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9100                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9101            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9102        }
9103
9104        if ((state != null) && !state.timeoutExtended()) {
9105            state.extendTimeout();
9106
9107            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9108            msg.arg1 = id;
9109            msg.obj = response;
9110            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9111        }
9112    }
9113
9114    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9115            int verificationCode, UserHandle user) {
9116        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9117        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9118        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9119        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9120        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9121
9122        mContext.sendBroadcastAsUser(intent, user,
9123                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9124    }
9125
9126    private ComponentName matchComponentForVerifier(String packageName,
9127            List<ResolveInfo> receivers) {
9128        ActivityInfo targetReceiver = null;
9129
9130        final int NR = receivers.size();
9131        for (int i = 0; i < NR; i++) {
9132            final ResolveInfo info = receivers.get(i);
9133            if (info.activityInfo == null) {
9134                continue;
9135            }
9136
9137            if (packageName.equals(info.activityInfo.packageName)) {
9138                targetReceiver = info.activityInfo;
9139                break;
9140            }
9141        }
9142
9143        if (targetReceiver == null) {
9144            return null;
9145        }
9146
9147        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9148    }
9149
9150    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9151            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9152        if (pkgInfo.verifiers.length == 0) {
9153            return null;
9154        }
9155
9156        final int N = pkgInfo.verifiers.length;
9157        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9158        for (int i = 0; i < N; i++) {
9159            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9160
9161            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9162                    receivers);
9163            if (comp == null) {
9164                continue;
9165            }
9166
9167            final int verifierUid = getUidForVerifier(verifierInfo);
9168            if (verifierUid == -1) {
9169                continue;
9170            }
9171
9172            if (DEBUG_VERIFY) {
9173                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9174                        + " with the correct signature");
9175            }
9176            sufficientVerifiers.add(comp);
9177            verificationState.addSufficientVerifier(verifierUid);
9178        }
9179
9180        return sufficientVerifiers;
9181    }
9182
9183    private int getUidForVerifier(VerifierInfo verifierInfo) {
9184        synchronized (mPackages) {
9185            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9186            if (pkg == null) {
9187                return -1;
9188            } else if (pkg.mSignatures.length != 1) {
9189                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9190                        + " has more than one signature; ignoring");
9191                return -1;
9192            }
9193
9194            /*
9195             * If the public key of the package's signature does not match
9196             * our expected public key, then this is a different package and
9197             * we should skip.
9198             */
9199
9200            final byte[] expectedPublicKey;
9201            try {
9202                final Signature verifierSig = pkg.mSignatures[0];
9203                final PublicKey publicKey = verifierSig.getPublicKey();
9204                expectedPublicKey = publicKey.getEncoded();
9205            } catch (CertificateException e) {
9206                return -1;
9207            }
9208
9209            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9210
9211            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9212                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9213                        + " does not have the expected public key; ignoring");
9214                return -1;
9215            }
9216
9217            return pkg.applicationInfo.uid;
9218        }
9219    }
9220
9221    @Override
9222    public void finishPackageInstall(int token) {
9223        enforceSystemOrRoot("Only the system is allowed to finish installs");
9224
9225        if (DEBUG_INSTALL) {
9226            Slog.v(TAG, "BM finishing package install for " + token);
9227        }
9228
9229        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9230        mHandler.sendMessage(msg);
9231    }
9232
9233    /**
9234     * Get the verification agent timeout.
9235     *
9236     * @return verification timeout in milliseconds
9237     */
9238    private long getVerificationTimeout() {
9239        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9240                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9241                DEFAULT_VERIFICATION_TIMEOUT);
9242    }
9243
9244    /**
9245     * Get the default verification agent response code.
9246     *
9247     * @return default verification response code
9248     */
9249    private int getDefaultVerificationResponse() {
9250        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9251                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9252                DEFAULT_VERIFICATION_RESPONSE);
9253    }
9254
9255    /**
9256     * Check whether or not package verification has been enabled.
9257     *
9258     * @return true if verification should be performed
9259     */
9260    private boolean isVerificationEnabled(int userId, int installFlags) {
9261        if (!DEFAULT_VERIFY_ENABLE) {
9262            return false;
9263        }
9264
9265        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9266
9267        // Check if installing from ADB
9268        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9269            // Do not run verification in a test harness environment
9270            if (ActivityManager.isRunningInTestHarness()) {
9271                return false;
9272            }
9273            if (ensureVerifyAppsEnabled) {
9274                return true;
9275            }
9276            // Check if the developer does not want package verification for ADB installs
9277            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9278                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9279                return false;
9280            }
9281        }
9282
9283        if (ensureVerifyAppsEnabled) {
9284            return true;
9285        }
9286
9287        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9288                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9289    }
9290
9291    @Override
9292    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9293            throws RemoteException {
9294        mContext.enforceCallingOrSelfPermission(
9295                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9296                "Only intentfilter verification agents can verify applications");
9297
9298        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9299        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9300                Binder.getCallingUid(), verificationCode, failedDomains);
9301        msg.arg1 = id;
9302        msg.obj = response;
9303        mHandler.sendMessage(msg);
9304    }
9305
9306    @Override
9307    public int getIntentVerificationStatus(String packageName, int userId) {
9308        synchronized (mPackages) {
9309            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9310        }
9311    }
9312
9313    @Override
9314    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9315        boolean result = false;
9316        synchronized (mPackages) {
9317            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9318        }
9319        if (result) {
9320            scheduleWritePackageRestrictionsLocked(userId);
9321        }
9322        return result;
9323    }
9324
9325    @Override
9326    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9327        synchronized (mPackages) {
9328            return mSettings.getIntentFilterVerificationsLPr(packageName);
9329        }
9330    }
9331
9332    @Override
9333    public List<IntentFilter> getAllIntentFilters(String packageName) {
9334        if (TextUtils.isEmpty(packageName)) {
9335            return Collections.<IntentFilter>emptyList();
9336        }
9337        synchronized (mPackages) {
9338            PackageParser.Package pkg = mPackages.get(packageName);
9339            if (pkg == null || pkg.activities == null) {
9340                return Collections.<IntentFilter>emptyList();
9341            }
9342            final int count = pkg.activities.size();
9343            ArrayList<IntentFilter> result = new ArrayList<>();
9344            for (int n=0; n<count; n++) {
9345                PackageParser.Activity activity = pkg.activities.get(n);
9346                if (activity.intents != null || activity.intents.size() > 0) {
9347                    result.addAll(activity.intents);
9348                }
9349            }
9350            return result;
9351        }
9352    }
9353
9354    @Override
9355    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9356        synchronized (mPackages) {
9357            boolean result = mSettings.setDefaultBrowserPackageNameLPr(packageName, userId);
9358            if (packageName != null) {
9359                result |= updateIntentVerificationStatus(packageName,
9360                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9361                        UserHandle.myUserId());
9362            }
9363            return result;
9364        }
9365    }
9366
9367    @Override
9368    public String getDefaultBrowserPackageName(int userId) {
9369        synchronized (mPackages) {
9370            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9371        }
9372    }
9373
9374    /**
9375     * Get the "allow unknown sources" setting.
9376     *
9377     * @return the current "allow unknown sources" setting
9378     */
9379    private int getUnknownSourcesSettings() {
9380        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9381                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9382                -1);
9383    }
9384
9385    @Override
9386    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9387        final int uid = Binder.getCallingUid();
9388        // writer
9389        synchronized (mPackages) {
9390            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9391            if (targetPackageSetting == null) {
9392                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9393            }
9394
9395            PackageSetting installerPackageSetting;
9396            if (installerPackageName != null) {
9397                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9398                if (installerPackageSetting == null) {
9399                    throw new IllegalArgumentException("Unknown installer package: "
9400                            + installerPackageName);
9401                }
9402            } else {
9403                installerPackageSetting = null;
9404            }
9405
9406            Signature[] callerSignature;
9407            Object obj = mSettings.getUserIdLPr(uid);
9408            if (obj != null) {
9409                if (obj instanceof SharedUserSetting) {
9410                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9411                } else if (obj instanceof PackageSetting) {
9412                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9413                } else {
9414                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9415                }
9416            } else {
9417                throw new SecurityException("Unknown calling uid " + uid);
9418            }
9419
9420            // Verify: can't set installerPackageName to a package that is
9421            // not signed with the same cert as the caller.
9422            if (installerPackageSetting != null) {
9423                if (compareSignatures(callerSignature,
9424                        installerPackageSetting.signatures.mSignatures)
9425                        != PackageManager.SIGNATURE_MATCH) {
9426                    throw new SecurityException(
9427                            "Caller does not have same cert as new installer package "
9428                            + installerPackageName);
9429                }
9430            }
9431
9432            // Verify: if target already has an installer package, it must
9433            // be signed with the same cert as the caller.
9434            if (targetPackageSetting.installerPackageName != null) {
9435                PackageSetting setting = mSettings.mPackages.get(
9436                        targetPackageSetting.installerPackageName);
9437                // If the currently set package isn't valid, then it's always
9438                // okay to change it.
9439                if (setting != null) {
9440                    if (compareSignatures(callerSignature,
9441                            setting.signatures.mSignatures)
9442                            != PackageManager.SIGNATURE_MATCH) {
9443                        throw new SecurityException(
9444                                "Caller does not have same cert as old installer package "
9445                                + targetPackageSetting.installerPackageName);
9446                    }
9447                }
9448            }
9449
9450            // Okay!
9451            targetPackageSetting.installerPackageName = installerPackageName;
9452            scheduleWriteSettingsLocked();
9453        }
9454    }
9455
9456    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
9457        // Queue up an async operation since the package installation may take a little while.
9458        mHandler.post(new Runnable() {
9459            public void run() {
9460                mHandler.removeCallbacks(this);
9461                 // Result object to be returned
9462                PackageInstalledInfo res = new PackageInstalledInfo();
9463                res.returnCode = currentStatus;
9464                res.uid = -1;
9465                res.pkg = null;
9466                res.removedInfo = new PackageRemovedInfo();
9467                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9468                    args.doPreInstall(res.returnCode);
9469                    synchronized (mInstallLock) {
9470                        installPackageLI(args, res);
9471                    }
9472                    args.doPostInstall(res.returnCode, res.uid);
9473                }
9474
9475                // A restore should be performed at this point if (a) the install
9476                // succeeded, (b) the operation is not an update, and (c) the new
9477                // package has not opted out of backup participation.
9478                final boolean update = res.removedInfo.removedPackage != null;
9479                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
9480                boolean doRestore = !update
9481                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
9482
9483                // Set up the post-install work request bookkeeping.  This will be used
9484                // and cleaned up by the post-install event handling regardless of whether
9485                // there's a restore pass performed.  Token values are >= 1.
9486                int token;
9487                if (mNextInstallToken < 0) mNextInstallToken = 1;
9488                token = mNextInstallToken++;
9489
9490                PostInstallData data = new PostInstallData(args, res);
9491                mRunningInstalls.put(token, data);
9492                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
9493
9494                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
9495                    // Pass responsibility to the Backup Manager.  It will perform a
9496                    // restore if appropriate, then pass responsibility back to the
9497                    // Package Manager to run the post-install observer callbacks
9498                    // and broadcasts.
9499                    IBackupManager bm = IBackupManager.Stub.asInterface(
9500                            ServiceManager.getService(Context.BACKUP_SERVICE));
9501                    if (bm != null) {
9502                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
9503                                + " to BM for possible restore");
9504                        try {
9505                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
9506                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
9507                            } else {
9508                                doRestore = false;
9509                            }
9510                        } catch (RemoteException e) {
9511                            // can't happen; the backup manager is local
9512                        } catch (Exception e) {
9513                            Slog.e(TAG, "Exception trying to enqueue restore", e);
9514                            doRestore = false;
9515                        }
9516                    } else {
9517                        Slog.e(TAG, "Backup Manager not found!");
9518                        doRestore = false;
9519                    }
9520                }
9521
9522                if (!doRestore) {
9523                    // No restore possible, or the Backup Manager was mysteriously not
9524                    // available -- just fire the post-install work request directly.
9525                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
9526                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9527                    mHandler.sendMessage(msg);
9528                }
9529            }
9530        });
9531    }
9532
9533    private abstract class HandlerParams {
9534        private static final int MAX_RETRIES = 4;
9535
9536        /**
9537         * Number of times startCopy() has been attempted and had a non-fatal
9538         * error.
9539         */
9540        private int mRetries = 0;
9541
9542        /** User handle for the user requesting the information or installation. */
9543        private final UserHandle mUser;
9544
9545        HandlerParams(UserHandle user) {
9546            mUser = user;
9547        }
9548
9549        UserHandle getUser() {
9550            return mUser;
9551        }
9552
9553        final boolean startCopy() {
9554            boolean res;
9555            try {
9556                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
9557
9558                if (++mRetries > MAX_RETRIES) {
9559                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
9560                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
9561                    handleServiceError();
9562                    return false;
9563                } else {
9564                    handleStartCopy();
9565                    res = true;
9566                }
9567            } catch (RemoteException e) {
9568                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
9569                mHandler.sendEmptyMessage(MCS_RECONNECT);
9570                res = false;
9571            }
9572            handleReturnCode();
9573            return res;
9574        }
9575
9576        final void serviceError() {
9577            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
9578            handleServiceError();
9579            handleReturnCode();
9580        }
9581
9582        abstract void handleStartCopy() throws RemoteException;
9583        abstract void handleServiceError();
9584        abstract void handleReturnCode();
9585    }
9586
9587    class MeasureParams extends HandlerParams {
9588        private final PackageStats mStats;
9589        private boolean mSuccess;
9590
9591        private final IPackageStatsObserver mObserver;
9592
9593        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
9594            super(new UserHandle(stats.userHandle));
9595            mObserver = observer;
9596            mStats = stats;
9597        }
9598
9599        @Override
9600        public String toString() {
9601            return "MeasureParams{"
9602                + Integer.toHexString(System.identityHashCode(this))
9603                + " " + mStats.packageName + "}";
9604        }
9605
9606        @Override
9607        void handleStartCopy() throws RemoteException {
9608            synchronized (mInstallLock) {
9609                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
9610            }
9611
9612            if (mSuccess) {
9613                final boolean mounted;
9614                if (Environment.isExternalStorageEmulated()) {
9615                    mounted = true;
9616                } else {
9617                    final String status = Environment.getExternalStorageState();
9618                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
9619                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
9620                }
9621
9622                if (mounted) {
9623                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
9624
9625                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
9626                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
9627
9628                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
9629                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
9630
9631                    // Always subtract cache size, since it's a subdirectory
9632                    mStats.externalDataSize -= mStats.externalCacheSize;
9633
9634                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
9635                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
9636
9637                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
9638                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
9639                }
9640            }
9641        }
9642
9643        @Override
9644        void handleReturnCode() {
9645            if (mObserver != null) {
9646                try {
9647                    mObserver.onGetStatsCompleted(mStats, mSuccess);
9648                } catch (RemoteException e) {
9649                    Slog.i(TAG, "Observer no longer exists.");
9650                }
9651            }
9652        }
9653
9654        @Override
9655        void handleServiceError() {
9656            Slog.e(TAG, "Could not measure application " + mStats.packageName
9657                            + " external storage");
9658        }
9659    }
9660
9661    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
9662            throws RemoteException {
9663        long result = 0;
9664        for (File path : paths) {
9665            result += mcs.calculateDirectorySize(path.getAbsolutePath());
9666        }
9667        return result;
9668    }
9669
9670    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
9671        for (File path : paths) {
9672            try {
9673                mcs.clearDirectory(path.getAbsolutePath());
9674            } catch (RemoteException e) {
9675            }
9676        }
9677    }
9678
9679    static class OriginInfo {
9680        /**
9681         * Location where install is coming from, before it has been
9682         * copied/renamed into place. This could be a single monolithic APK
9683         * file, or a cluster directory. This location may be untrusted.
9684         */
9685        final File file;
9686        final String cid;
9687
9688        /**
9689         * Flag indicating that {@link #file} or {@link #cid} has already been
9690         * staged, meaning downstream users don't need to defensively copy the
9691         * contents.
9692         */
9693        final boolean staged;
9694
9695        /**
9696         * Flag indicating that {@link #file} or {@link #cid} is an already
9697         * installed app that is being moved.
9698         */
9699        final boolean existing;
9700
9701        final String resolvedPath;
9702        final File resolvedFile;
9703
9704        static OriginInfo fromNothing() {
9705            return new OriginInfo(null, null, false, false);
9706        }
9707
9708        static OriginInfo fromUntrustedFile(File file) {
9709            return new OriginInfo(file, null, false, false);
9710        }
9711
9712        static OriginInfo fromExistingFile(File file) {
9713            return new OriginInfo(file, null, false, true);
9714        }
9715
9716        static OriginInfo fromStagedFile(File file) {
9717            return new OriginInfo(file, null, true, false);
9718        }
9719
9720        static OriginInfo fromStagedContainer(String cid) {
9721            return new OriginInfo(null, cid, true, false);
9722        }
9723
9724        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
9725            this.file = file;
9726            this.cid = cid;
9727            this.staged = staged;
9728            this.existing = existing;
9729
9730            if (cid != null) {
9731                resolvedPath = PackageHelper.getSdDir(cid);
9732                resolvedFile = new File(resolvedPath);
9733            } else if (file != null) {
9734                resolvedPath = file.getAbsolutePath();
9735                resolvedFile = file;
9736            } else {
9737                resolvedPath = null;
9738                resolvedFile = null;
9739            }
9740        }
9741    }
9742
9743    class MoveInfo {
9744        final int moveId;
9745        final String fromUuid;
9746        final String toUuid;
9747        final String packageName;
9748        final String dataAppName;
9749        final int appId;
9750        final String seinfo;
9751
9752        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
9753                String dataAppName, int appId, String seinfo) {
9754            this.moveId = moveId;
9755            this.fromUuid = fromUuid;
9756            this.toUuid = toUuid;
9757            this.packageName = packageName;
9758            this.dataAppName = dataAppName;
9759            this.appId = appId;
9760            this.seinfo = seinfo;
9761        }
9762    }
9763
9764    class InstallParams extends HandlerParams {
9765        final OriginInfo origin;
9766        final MoveInfo move;
9767        final IPackageInstallObserver2 observer;
9768        int installFlags;
9769        final String installerPackageName;
9770        final String volumeUuid;
9771        final VerificationParams verificationParams;
9772        private InstallArgs mArgs;
9773        private int mRet;
9774        final String packageAbiOverride;
9775
9776        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
9777                int installFlags, String installerPackageName, String volumeUuid,
9778                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
9779            super(user);
9780            this.origin = origin;
9781            this.move = move;
9782            this.observer = observer;
9783            this.installFlags = installFlags;
9784            this.installerPackageName = installerPackageName;
9785            this.volumeUuid = volumeUuid;
9786            this.verificationParams = verificationParams;
9787            this.packageAbiOverride = packageAbiOverride;
9788        }
9789
9790        @Override
9791        public String toString() {
9792            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
9793                    + " file=" + origin.file + " cid=" + origin.cid + "}";
9794        }
9795
9796        public ManifestDigest getManifestDigest() {
9797            if (verificationParams == null) {
9798                return null;
9799            }
9800            return verificationParams.getManifestDigest();
9801        }
9802
9803        private int installLocationPolicy(PackageInfoLite pkgLite) {
9804            String packageName = pkgLite.packageName;
9805            int installLocation = pkgLite.installLocation;
9806            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9807            // reader
9808            synchronized (mPackages) {
9809                PackageParser.Package pkg = mPackages.get(packageName);
9810                if (pkg != null) {
9811                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
9812                        // Check for downgrading.
9813                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
9814                            try {
9815                                checkDowngrade(pkg, pkgLite);
9816                            } catch (PackageManagerException e) {
9817                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
9818                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
9819                            }
9820                        }
9821                        // Check for updated system application.
9822                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9823                            if (onSd) {
9824                                Slog.w(TAG, "Cannot install update to system app on sdcard");
9825                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
9826                            }
9827                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9828                        } else {
9829                            if (onSd) {
9830                                // Install flag overrides everything.
9831                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9832                            }
9833                            // If current upgrade specifies particular preference
9834                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
9835                                // Application explicitly specified internal.
9836                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9837                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
9838                                // App explictly prefers external. Let policy decide
9839                            } else {
9840                                // Prefer previous location
9841                                if (isExternal(pkg)) {
9842                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9843                                }
9844                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9845                            }
9846                        }
9847                    } else {
9848                        // Invalid install. Return error code
9849                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
9850                    }
9851                }
9852            }
9853            // All the special cases have been taken care of.
9854            // Return result based on recommended install location.
9855            if (onSd) {
9856                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9857            }
9858            return pkgLite.recommendedInstallLocation;
9859        }
9860
9861        /*
9862         * Invoke remote method to get package information and install
9863         * location values. Override install location based on default
9864         * policy if needed and then create install arguments based
9865         * on the install location.
9866         */
9867        public void handleStartCopy() throws RemoteException {
9868            int ret = PackageManager.INSTALL_SUCCEEDED;
9869
9870            // If we're already staged, we've firmly committed to an install location
9871            if (origin.staged) {
9872                if (origin.file != null) {
9873                    installFlags |= PackageManager.INSTALL_INTERNAL;
9874                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
9875                } else if (origin.cid != null) {
9876                    installFlags |= PackageManager.INSTALL_EXTERNAL;
9877                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
9878                } else {
9879                    throw new IllegalStateException("Invalid stage location");
9880                }
9881            }
9882
9883            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9884            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
9885
9886            PackageInfoLite pkgLite = null;
9887
9888            if (onInt && onSd) {
9889                // Check if both bits are set.
9890                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
9891                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9892            } else {
9893                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
9894                        packageAbiOverride);
9895
9896                /*
9897                 * If we have too little free space, try to free cache
9898                 * before giving up.
9899                 */
9900                if (!origin.staged && pkgLite.recommendedInstallLocation
9901                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9902                    // TODO: focus freeing disk space on the target device
9903                    final StorageManager storage = StorageManager.from(mContext);
9904                    final long lowThreshold = storage.getStorageLowBytes(
9905                            Environment.getDataDirectory());
9906
9907                    final long sizeBytes = mContainerService.calculateInstalledSize(
9908                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
9909
9910                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
9911                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
9912                                installFlags, packageAbiOverride);
9913                    }
9914
9915                    /*
9916                     * The cache free must have deleted the file we
9917                     * downloaded to install.
9918                     *
9919                     * TODO: fix the "freeCache" call to not delete
9920                     *       the file we care about.
9921                     */
9922                    if (pkgLite.recommendedInstallLocation
9923                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9924                        pkgLite.recommendedInstallLocation
9925                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
9926                    }
9927                }
9928            }
9929
9930            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9931                int loc = pkgLite.recommendedInstallLocation;
9932                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
9933                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9934                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
9935                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9936                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9937                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9938                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
9939                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
9940                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9941                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
9942                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
9943                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
9944                } else {
9945                    // Override with defaults if needed.
9946                    loc = installLocationPolicy(pkgLite);
9947                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
9948                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
9949                    } else if (!onSd && !onInt) {
9950                        // Override install location with flags
9951                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
9952                            // Set the flag to install on external media.
9953                            installFlags |= PackageManager.INSTALL_EXTERNAL;
9954                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
9955                        } else {
9956                            // Make sure the flag for installing on external
9957                            // media is unset
9958                            installFlags |= PackageManager.INSTALL_INTERNAL;
9959                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
9960                        }
9961                    }
9962                }
9963            }
9964
9965            final InstallArgs args = createInstallArgs(this);
9966            mArgs = args;
9967
9968            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9969                 /*
9970                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
9971                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
9972                 */
9973                int userIdentifier = getUser().getIdentifier();
9974                if (userIdentifier == UserHandle.USER_ALL
9975                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
9976                    userIdentifier = UserHandle.USER_OWNER;
9977                }
9978
9979                /*
9980                 * Determine if we have any installed package verifiers. If we
9981                 * do, then we'll defer to them to verify the packages.
9982                 */
9983                final int requiredUid = mRequiredVerifierPackage == null ? -1
9984                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
9985                if (!origin.existing && requiredUid != -1
9986                        && isVerificationEnabled(userIdentifier, installFlags)) {
9987                    final Intent verification = new Intent(
9988                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
9989                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
9990                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
9991                            PACKAGE_MIME_TYPE);
9992                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9993
9994                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
9995                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
9996                            0 /* TODO: Which userId? */);
9997
9998                    if (DEBUG_VERIFY) {
9999                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10000                                + verification.toString() + " with " + pkgLite.verifiers.length
10001                                + " optional verifiers");
10002                    }
10003
10004                    final int verificationId = mPendingVerificationToken++;
10005
10006                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10007
10008                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10009                            installerPackageName);
10010
10011                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10012                            installFlags);
10013
10014                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10015                            pkgLite.packageName);
10016
10017                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10018                            pkgLite.versionCode);
10019
10020                    if (verificationParams != null) {
10021                        if (verificationParams.getVerificationURI() != null) {
10022                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10023                                 verificationParams.getVerificationURI());
10024                        }
10025                        if (verificationParams.getOriginatingURI() != null) {
10026                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10027                                  verificationParams.getOriginatingURI());
10028                        }
10029                        if (verificationParams.getReferrer() != null) {
10030                            verification.putExtra(Intent.EXTRA_REFERRER,
10031                                  verificationParams.getReferrer());
10032                        }
10033                        if (verificationParams.getOriginatingUid() >= 0) {
10034                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10035                                  verificationParams.getOriginatingUid());
10036                        }
10037                        if (verificationParams.getInstallerUid() >= 0) {
10038                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10039                                  verificationParams.getInstallerUid());
10040                        }
10041                    }
10042
10043                    final PackageVerificationState verificationState = new PackageVerificationState(
10044                            requiredUid, args);
10045
10046                    mPendingVerification.append(verificationId, verificationState);
10047
10048                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10049                            receivers, verificationState);
10050
10051                    /*
10052                     * If any sufficient verifiers were listed in the package
10053                     * manifest, attempt to ask them.
10054                     */
10055                    if (sufficientVerifiers != null) {
10056                        final int N = sufficientVerifiers.size();
10057                        if (N == 0) {
10058                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10059                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10060                        } else {
10061                            for (int i = 0; i < N; i++) {
10062                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10063
10064                                final Intent sufficientIntent = new Intent(verification);
10065                                sufficientIntent.setComponent(verifierComponent);
10066
10067                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
10068                            }
10069                        }
10070                    }
10071
10072                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10073                            mRequiredVerifierPackage, receivers);
10074                    if (ret == PackageManager.INSTALL_SUCCEEDED
10075                            && mRequiredVerifierPackage != null) {
10076                        /*
10077                         * Send the intent to the required verification agent,
10078                         * but only start the verification timeout after the
10079                         * target BroadcastReceivers have run.
10080                         */
10081                        verification.setComponent(requiredVerifierComponent);
10082                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
10083                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10084                                new BroadcastReceiver() {
10085                                    @Override
10086                                    public void onReceive(Context context, Intent intent) {
10087                                        final Message msg = mHandler
10088                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10089                                        msg.arg1 = verificationId;
10090                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10091                                    }
10092                                }, null, 0, null, null);
10093
10094                        /*
10095                         * We don't want the copy to proceed until verification
10096                         * succeeds, so null out this field.
10097                         */
10098                        mArgs = null;
10099                    }
10100                } else {
10101                    /*
10102                     * No package verification is enabled, so immediately start
10103                     * the remote call to initiate copy using temporary file.
10104                     */
10105                    ret = args.copyApk(mContainerService, true);
10106                }
10107            }
10108
10109            mRet = ret;
10110        }
10111
10112        @Override
10113        void handleReturnCode() {
10114            // If mArgs is null, then MCS couldn't be reached. When it
10115            // reconnects, it will try again to install. At that point, this
10116            // will succeed.
10117            if (mArgs != null) {
10118                processPendingInstall(mArgs, mRet);
10119            }
10120        }
10121
10122        @Override
10123        void handleServiceError() {
10124            mArgs = createInstallArgs(this);
10125            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10126        }
10127
10128        public boolean isForwardLocked() {
10129            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10130        }
10131    }
10132
10133    /**
10134     * Used during creation of InstallArgs
10135     *
10136     * @param installFlags package installation flags
10137     * @return true if should be installed on external storage
10138     */
10139    private static boolean installOnExternalAsec(int installFlags) {
10140        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10141            return false;
10142        }
10143        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10144            return true;
10145        }
10146        return false;
10147    }
10148
10149    /**
10150     * Used during creation of InstallArgs
10151     *
10152     * @param installFlags package installation flags
10153     * @return true if should be installed as forward locked
10154     */
10155    private static boolean installForwardLocked(int installFlags) {
10156        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10157    }
10158
10159    private InstallArgs createInstallArgs(InstallParams params) {
10160        if (params.move != null) {
10161            return new MoveInstallArgs(params);
10162        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10163            return new AsecInstallArgs(params);
10164        } else {
10165            return new FileInstallArgs(params);
10166        }
10167    }
10168
10169    /**
10170     * Create args that describe an existing installed package. Typically used
10171     * when cleaning up old installs, or used as a move source.
10172     */
10173    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10174            String resourcePath, String[] instructionSets) {
10175        final boolean isInAsec;
10176        if (installOnExternalAsec(installFlags)) {
10177            /* Apps on SD card are always in ASEC containers. */
10178            isInAsec = true;
10179        } else if (installForwardLocked(installFlags)
10180                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10181            /*
10182             * Forward-locked apps are only in ASEC containers if they're the
10183             * new style
10184             */
10185            isInAsec = true;
10186        } else {
10187            isInAsec = false;
10188        }
10189
10190        if (isInAsec) {
10191            return new AsecInstallArgs(codePath, instructionSets,
10192                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10193        } else {
10194            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10195        }
10196    }
10197
10198    static abstract class InstallArgs {
10199        /** @see InstallParams#origin */
10200        final OriginInfo origin;
10201        /** @see InstallParams#move */
10202        final MoveInfo move;
10203
10204        final IPackageInstallObserver2 observer;
10205        // Always refers to PackageManager flags only
10206        final int installFlags;
10207        final String installerPackageName;
10208        final String volumeUuid;
10209        final ManifestDigest manifestDigest;
10210        final UserHandle user;
10211        final String abiOverride;
10212
10213        // The list of instruction sets supported by this app. This is currently
10214        // only used during the rmdex() phase to clean up resources. We can get rid of this
10215        // if we move dex files under the common app path.
10216        /* nullable */ String[] instructionSets;
10217
10218        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10219                int installFlags, String installerPackageName, String volumeUuid,
10220                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10221                String abiOverride) {
10222            this.origin = origin;
10223            this.move = move;
10224            this.installFlags = installFlags;
10225            this.observer = observer;
10226            this.installerPackageName = installerPackageName;
10227            this.volumeUuid = volumeUuid;
10228            this.manifestDigest = manifestDigest;
10229            this.user = user;
10230            this.instructionSets = instructionSets;
10231            this.abiOverride = abiOverride;
10232        }
10233
10234        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10235        abstract int doPreInstall(int status);
10236
10237        /**
10238         * Rename package into final resting place. All paths on the given
10239         * scanned package should be updated to reflect the rename.
10240         */
10241        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10242        abstract int doPostInstall(int status, int uid);
10243
10244        /** @see PackageSettingBase#codePathString */
10245        abstract String getCodePath();
10246        /** @see PackageSettingBase#resourcePathString */
10247        abstract String getResourcePath();
10248
10249        // Need installer lock especially for dex file removal.
10250        abstract void cleanUpResourcesLI();
10251        abstract boolean doPostDeleteLI(boolean delete);
10252
10253        /**
10254         * Called before the source arguments are copied. This is used mostly
10255         * for MoveParams when it needs to read the source file to put it in the
10256         * destination.
10257         */
10258        int doPreCopy() {
10259            return PackageManager.INSTALL_SUCCEEDED;
10260        }
10261
10262        /**
10263         * Called after the source arguments are copied. This is used mostly for
10264         * MoveParams when it needs to read the source file to put it in the
10265         * destination.
10266         *
10267         * @return
10268         */
10269        int doPostCopy(int uid) {
10270            return PackageManager.INSTALL_SUCCEEDED;
10271        }
10272
10273        protected boolean isFwdLocked() {
10274            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10275        }
10276
10277        protected boolean isExternalAsec() {
10278            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10279        }
10280
10281        UserHandle getUser() {
10282            return user;
10283        }
10284    }
10285
10286    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10287        if (!allCodePaths.isEmpty()) {
10288            if (instructionSets == null) {
10289                throw new IllegalStateException("instructionSet == null");
10290            }
10291            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10292            for (String codePath : allCodePaths) {
10293                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10294                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10295                    if (retCode < 0) {
10296                        Slog.w(TAG, "Couldn't remove dex file for package: "
10297                                + " at location " + codePath + ", retcode=" + retCode);
10298                        // we don't consider this to be a failure of the core package deletion
10299                    }
10300                }
10301            }
10302        }
10303    }
10304
10305    /**
10306     * Logic to handle installation of non-ASEC applications, including copying
10307     * and renaming logic.
10308     */
10309    class FileInstallArgs extends InstallArgs {
10310        private File codeFile;
10311        private File resourceFile;
10312
10313        // Example topology:
10314        // /data/app/com.example/base.apk
10315        // /data/app/com.example/split_foo.apk
10316        // /data/app/com.example/lib/arm/libfoo.so
10317        // /data/app/com.example/lib/arm64/libfoo.so
10318        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10319
10320        /** New install */
10321        FileInstallArgs(InstallParams params) {
10322            super(params.origin, params.move, params.observer, params.installFlags,
10323                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10324                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10325            if (isFwdLocked()) {
10326                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10327            }
10328        }
10329
10330        /** Existing install */
10331        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10332            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10333                    null);
10334            this.codeFile = (codePath != null) ? new File(codePath) : null;
10335            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10336        }
10337
10338        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10339            if (origin.staged) {
10340                Slog.d(TAG, origin.file + " already staged; skipping copy");
10341                codeFile = origin.file;
10342                resourceFile = origin.file;
10343                return PackageManager.INSTALL_SUCCEEDED;
10344            }
10345
10346            try {
10347                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10348                codeFile = tempDir;
10349                resourceFile = tempDir;
10350            } catch (IOException e) {
10351                Slog.w(TAG, "Failed to create copy file: " + e);
10352                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10353            }
10354
10355            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10356                @Override
10357                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10358                    if (!FileUtils.isValidExtFilename(name)) {
10359                        throw new IllegalArgumentException("Invalid filename: " + name);
10360                    }
10361                    try {
10362                        final File file = new File(codeFile, name);
10363                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10364                                O_RDWR | O_CREAT, 0644);
10365                        Os.chmod(file.getAbsolutePath(), 0644);
10366                        return new ParcelFileDescriptor(fd);
10367                    } catch (ErrnoException e) {
10368                        throw new RemoteException("Failed to open: " + e.getMessage());
10369                    }
10370                }
10371            };
10372
10373            int ret = PackageManager.INSTALL_SUCCEEDED;
10374            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10375            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10376                Slog.e(TAG, "Failed to copy package");
10377                return ret;
10378            }
10379
10380            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10381            NativeLibraryHelper.Handle handle = null;
10382            try {
10383                handle = NativeLibraryHelper.Handle.create(codeFile);
10384                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10385                        abiOverride);
10386            } catch (IOException e) {
10387                Slog.e(TAG, "Copying native libraries failed", e);
10388                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10389            } finally {
10390                IoUtils.closeQuietly(handle);
10391            }
10392
10393            return ret;
10394        }
10395
10396        int doPreInstall(int status) {
10397            if (status != PackageManager.INSTALL_SUCCEEDED) {
10398                cleanUp();
10399            }
10400            return status;
10401        }
10402
10403        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10404            if (status != PackageManager.INSTALL_SUCCEEDED) {
10405                cleanUp();
10406                return false;
10407            }
10408
10409            final File targetDir = codeFile.getParentFile();
10410            final File beforeCodeFile = codeFile;
10411            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10412
10413            Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10414            try {
10415                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10416            } catch (ErrnoException e) {
10417                Slog.d(TAG, "Failed to rename", e);
10418                return false;
10419            }
10420
10421            if (!SELinux.restoreconRecursive(afterCodeFile)) {
10422                Slog.d(TAG, "Failed to restorecon");
10423                return false;
10424            }
10425
10426            // Reflect the rename internally
10427            codeFile = afterCodeFile;
10428            resourceFile = afterCodeFile;
10429
10430            // Reflect the rename in scanned details
10431            pkg.codePath = afterCodeFile.getAbsolutePath();
10432            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10433                    pkg.baseCodePath);
10434            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10435                    pkg.splitCodePaths);
10436
10437            // Reflect the rename in app info
10438            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10439            pkg.applicationInfo.setCodePath(pkg.codePath);
10440            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10441            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10442            pkg.applicationInfo.setResourcePath(pkg.codePath);
10443            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10444            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10445
10446            return true;
10447        }
10448
10449        int doPostInstall(int status, int uid) {
10450            if (status != PackageManager.INSTALL_SUCCEEDED) {
10451                cleanUp();
10452            }
10453            return status;
10454        }
10455
10456        @Override
10457        String getCodePath() {
10458            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10459        }
10460
10461        @Override
10462        String getResourcePath() {
10463            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10464        }
10465
10466        private boolean cleanUp() {
10467            if (codeFile == null || !codeFile.exists()) {
10468                return false;
10469            }
10470
10471            if (codeFile.isDirectory()) {
10472                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10473            } else {
10474                codeFile.delete();
10475            }
10476
10477            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10478                resourceFile.delete();
10479            }
10480
10481            return true;
10482        }
10483
10484        void cleanUpResourcesLI() {
10485            // Try enumerating all code paths before deleting
10486            List<String> allCodePaths = Collections.EMPTY_LIST;
10487            if (codeFile != null && codeFile.exists()) {
10488                try {
10489                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10490                    allCodePaths = pkg.getAllCodePaths();
10491                } catch (PackageParserException e) {
10492                    // Ignored; we tried our best
10493                }
10494            }
10495
10496            cleanUp();
10497            removeDexFiles(allCodePaths, instructionSets);
10498        }
10499
10500        boolean doPostDeleteLI(boolean delete) {
10501            // XXX err, shouldn't we respect the delete flag?
10502            cleanUpResourcesLI();
10503            return true;
10504        }
10505    }
10506
10507    private boolean isAsecExternal(String cid) {
10508        final String asecPath = PackageHelper.getSdFilesystem(cid);
10509        return !asecPath.startsWith(mAsecInternalPath);
10510    }
10511
10512    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
10513            PackageManagerException {
10514        if (copyRet < 0) {
10515            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
10516                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
10517                throw new PackageManagerException(copyRet, message);
10518            }
10519        }
10520    }
10521
10522    /**
10523     * Extract the MountService "container ID" from the full code path of an
10524     * .apk.
10525     */
10526    static String cidFromCodePath(String fullCodePath) {
10527        int eidx = fullCodePath.lastIndexOf("/");
10528        String subStr1 = fullCodePath.substring(0, eidx);
10529        int sidx = subStr1.lastIndexOf("/");
10530        return subStr1.substring(sidx+1, eidx);
10531    }
10532
10533    /**
10534     * Logic to handle installation of ASEC applications, including copying and
10535     * renaming logic.
10536     */
10537    class AsecInstallArgs extends InstallArgs {
10538        static final String RES_FILE_NAME = "pkg.apk";
10539        static final String PUBLIC_RES_FILE_NAME = "res.zip";
10540
10541        String cid;
10542        String packagePath;
10543        String resourcePath;
10544
10545        /** New install */
10546        AsecInstallArgs(InstallParams params) {
10547            super(params.origin, params.move, params.observer, params.installFlags,
10548                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10549                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10550        }
10551
10552        /** Existing install */
10553        AsecInstallArgs(String fullCodePath, String[] instructionSets,
10554                        boolean isExternal, boolean isForwardLocked) {
10555            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
10556                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10557                    instructionSets, null);
10558            // Hackily pretend we're still looking at a full code path
10559            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
10560                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
10561            }
10562
10563            // Extract cid from fullCodePath
10564            int eidx = fullCodePath.lastIndexOf("/");
10565            String subStr1 = fullCodePath.substring(0, eidx);
10566            int sidx = subStr1.lastIndexOf("/");
10567            cid = subStr1.substring(sidx+1, eidx);
10568            setMountPath(subStr1);
10569        }
10570
10571        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
10572            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
10573                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10574                    instructionSets, null);
10575            this.cid = cid;
10576            setMountPath(PackageHelper.getSdDir(cid));
10577        }
10578
10579        void createCopyFile() {
10580            cid = mInstallerService.allocateExternalStageCidLegacy();
10581        }
10582
10583        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10584            if (origin.staged) {
10585                Slog.d(TAG, origin.cid + " already staged; skipping copy");
10586                cid = origin.cid;
10587                setMountPath(PackageHelper.getSdDir(cid));
10588                return PackageManager.INSTALL_SUCCEEDED;
10589            }
10590
10591            if (temp) {
10592                createCopyFile();
10593            } else {
10594                /*
10595                 * Pre-emptively destroy the container since it's destroyed if
10596                 * copying fails due to it existing anyway.
10597                 */
10598                PackageHelper.destroySdDir(cid);
10599            }
10600
10601            final String newMountPath = imcs.copyPackageToContainer(
10602                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
10603                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
10604
10605            if (newMountPath != null) {
10606                setMountPath(newMountPath);
10607                return PackageManager.INSTALL_SUCCEEDED;
10608            } else {
10609                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10610            }
10611        }
10612
10613        @Override
10614        String getCodePath() {
10615            return packagePath;
10616        }
10617
10618        @Override
10619        String getResourcePath() {
10620            return resourcePath;
10621        }
10622
10623        int doPreInstall(int status) {
10624            if (status != PackageManager.INSTALL_SUCCEEDED) {
10625                // Destroy container
10626                PackageHelper.destroySdDir(cid);
10627            } else {
10628                boolean mounted = PackageHelper.isContainerMounted(cid);
10629                if (!mounted) {
10630                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
10631                            Process.SYSTEM_UID);
10632                    if (newMountPath != null) {
10633                        setMountPath(newMountPath);
10634                    } else {
10635                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10636                    }
10637                }
10638            }
10639            return status;
10640        }
10641
10642        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10643            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
10644            String newMountPath = null;
10645            if (PackageHelper.isContainerMounted(cid)) {
10646                // Unmount the container
10647                if (!PackageHelper.unMountSdDir(cid)) {
10648                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
10649                    return false;
10650                }
10651            }
10652            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10653                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
10654                        " which might be stale. Will try to clean up.");
10655                // Clean up the stale container and proceed to recreate.
10656                if (!PackageHelper.destroySdDir(newCacheId)) {
10657                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
10658                    return false;
10659                }
10660                // Successfully cleaned up stale container. Try to rename again.
10661                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10662                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
10663                            + " inspite of cleaning it up.");
10664                    return false;
10665                }
10666            }
10667            if (!PackageHelper.isContainerMounted(newCacheId)) {
10668                Slog.w(TAG, "Mounting container " + newCacheId);
10669                newMountPath = PackageHelper.mountSdDir(newCacheId,
10670                        getEncryptKey(), Process.SYSTEM_UID);
10671            } else {
10672                newMountPath = PackageHelper.getSdDir(newCacheId);
10673            }
10674            if (newMountPath == null) {
10675                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
10676                return false;
10677            }
10678            Log.i(TAG, "Succesfully renamed " + cid +
10679                    " to " + newCacheId +
10680                    " at new path: " + newMountPath);
10681            cid = newCacheId;
10682
10683            final File beforeCodeFile = new File(packagePath);
10684            setMountPath(newMountPath);
10685            final File afterCodeFile = new File(packagePath);
10686
10687            // Reflect the rename in scanned details
10688            pkg.codePath = afterCodeFile.getAbsolutePath();
10689            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10690                    pkg.baseCodePath);
10691            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10692                    pkg.splitCodePaths);
10693
10694            // Reflect the rename in app info
10695            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10696            pkg.applicationInfo.setCodePath(pkg.codePath);
10697            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10698            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10699            pkg.applicationInfo.setResourcePath(pkg.codePath);
10700            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10701            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10702
10703            return true;
10704        }
10705
10706        private void setMountPath(String mountPath) {
10707            final File mountFile = new File(mountPath);
10708
10709            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
10710            if (monolithicFile.exists()) {
10711                packagePath = monolithicFile.getAbsolutePath();
10712                if (isFwdLocked()) {
10713                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
10714                } else {
10715                    resourcePath = packagePath;
10716                }
10717            } else {
10718                packagePath = mountFile.getAbsolutePath();
10719                resourcePath = packagePath;
10720            }
10721        }
10722
10723        int doPostInstall(int status, int uid) {
10724            if (status != PackageManager.INSTALL_SUCCEEDED) {
10725                cleanUp();
10726            } else {
10727                final int groupOwner;
10728                final String protectedFile;
10729                if (isFwdLocked()) {
10730                    groupOwner = UserHandle.getSharedAppGid(uid);
10731                    protectedFile = RES_FILE_NAME;
10732                } else {
10733                    groupOwner = -1;
10734                    protectedFile = null;
10735                }
10736
10737                if (uid < Process.FIRST_APPLICATION_UID
10738                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
10739                    Slog.e(TAG, "Failed to finalize " + cid);
10740                    PackageHelper.destroySdDir(cid);
10741                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10742                }
10743
10744                boolean mounted = PackageHelper.isContainerMounted(cid);
10745                if (!mounted) {
10746                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
10747                }
10748            }
10749            return status;
10750        }
10751
10752        private void cleanUp() {
10753            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
10754
10755            // Destroy secure container
10756            PackageHelper.destroySdDir(cid);
10757        }
10758
10759        private List<String> getAllCodePaths() {
10760            final File codeFile = new File(getCodePath());
10761            if (codeFile != null && codeFile.exists()) {
10762                try {
10763                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10764                    return pkg.getAllCodePaths();
10765                } catch (PackageParserException e) {
10766                    // Ignored; we tried our best
10767                }
10768            }
10769            return Collections.EMPTY_LIST;
10770        }
10771
10772        void cleanUpResourcesLI() {
10773            // Enumerate all code paths before deleting
10774            cleanUpResourcesLI(getAllCodePaths());
10775        }
10776
10777        private void cleanUpResourcesLI(List<String> allCodePaths) {
10778            cleanUp();
10779            removeDexFiles(allCodePaths, instructionSets);
10780        }
10781
10782        String getPackageName() {
10783            return getAsecPackageName(cid);
10784        }
10785
10786        boolean doPostDeleteLI(boolean delete) {
10787            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
10788            final List<String> allCodePaths = getAllCodePaths();
10789            boolean mounted = PackageHelper.isContainerMounted(cid);
10790            if (mounted) {
10791                // Unmount first
10792                if (PackageHelper.unMountSdDir(cid)) {
10793                    mounted = false;
10794                }
10795            }
10796            if (!mounted && delete) {
10797                cleanUpResourcesLI(allCodePaths);
10798            }
10799            return !mounted;
10800        }
10801
10802        @Override
10803        int doPreCopy() {
10804            if (isFwdLocked()) {
10805                if (!PackageHelper.fixSdPermissions(cid,
10806                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
10807                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10808                }
10809            }
10810
10811            return PackageManager.INSTALL_SUCCEEDED;
10812        }
10813
10814        @Override
10815        int doPostCopy(int uid) {
10816            if (isFwdLocked()) {
10817                if (uid < Process.FIRST_APPLICATION_UID
10818                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
10819                                RES_FILE_NAME)) {
10820                    Slog.e(TAG, "Failed to finalize " + cid);
10821                    PackageHelper.destroySdDir(cid);
10822                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10823                }
10824            }
10825
10826            return PackageManager.INSTALL_SUCCEEDED;
10827        }
10828    }
10829
10830    /**
10831     * Logic to handle movement of existing installed applications.
10832     */
10833    class MoveInstallArgs extends InstallArgs {
10834        private File codeFile;
10835        private File resourceFile;
10836
10837        /** New install */
10838        MoveInstallArgs(InstallParams params) {
10839            super(params.origin, params.move, params.observer, params.installFlags,
10840                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10841                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10842        }
10843
10844        int copyApk(IMediaContainerService imcs, boolean temp) {
10845            Slog.d(TAG, "Moving " + move.packageName + " from " + move.fromUuid + " to "
10846                    + move.toUuid);
10847            synchronized (mInstaller) {
10848                if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
10849                        move.dataAppName, move.appId, move.seinfo) != 0) {
10850                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10851                }
10852            }
10853
10854            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
10855            resourceFile = codeFile;
10856            Slog.d(TAG, "codeFile after move is " + codeFile);
10857
10858            return PackageManager.INSTALL_SUCCEEDED;
10859        }
10860
10861        int doPreInstall(int status) {
10862            if (status != PackageManager.INSTALL_SUCCEEDED) {
10863                cleanUp();
10864            }
10865            return status;
10866        }
10867
10868        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10869            if (status != PackageManager.INSTALL_SUCCEEDED) {
10870                cleanUp();
10871                return false;
10872            }
10873
10874            // Reflect the move in app info
10875            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10876            pkg.applicationInfo.setCodePath(pkg.codePath);
10877            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10878            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10879            pkg.applicationInfo.setResourcePath(pkg.codePath);
10880            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10881            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10882
10883            return true;
10884        }
10885
10886        int doPostInstall(int status, int uid) {
10887            if (status != PackageManager.INSTALL_SUCCEEDED) {
10888                cleanUp();
10889            }
10890            return status;
10891        }
10892
10893        @Override
10894        String getCodePath() {
10895            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10896        }
10897
10898        @Override
10899        String getResourcePath() {
10900            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10901        }
10902
10903        private boolean cleanUp() {
10904            if (codeFile == null || !codeFile.exists()) {
10905                return false;
10906            }
10907
10908            if (codeFile.isDirectory()) {
10909                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10910            } else {
10911                codeFile.delete();
10912            }
10913
10914            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10915                resourceFile.delete();
10916            }
10917
10918            return true;
10919        }
10920
10921        void cleanUpResourcesLI() {
10922            cleanUp();
10923        }
10924
10925        boolean doPostDeleteLI(boolean delete) {
10926            // XXX err, shouldn't we respect the delete flag?
10927            cleanUpResourcesLI();
10928            return true;
10929        }
10930    }
10931
10932    static String getAsecPackageName(String packageCid) {
10933        int idx = packageCid.lastIndexOf("-");
10934        if (idx == -1) {
10935            return packageCid;
10936        }
10937        return packageCid.substring(0, idx);
10938    }
10939
10940    // Utility method used to create code paths based on package name and available index.
10941    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
10942        String idxStr = "";
10943        int idx = 1;
10944        // Fall back to default value of idx=1 if prefix is not
10945        // part of oldCodePath
10946        if (oldCodePath != null) {
10947            String subStr = oldCodePath;
10948            // Drop the suffix right away
10949            if (suffix != null && subStr.endsWith(suffix)) {
10950                subStr = subStr.substring(0, subStr.length() - suffix.length());
10951            }
10952            // If oldCodePath already contains prefix find out the
10953            // ending index to either increment or decrement.
10954            int sidx = subStr.lastIndexOf(prefix);
10955            if (sidx != -1) {
10956                subStr = subStr.substring(sidx + prefix.length());
10957                if (subStr != null) {
10958                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
10959                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
10960                    }
10961                    try {
10962                        idx = Integer.parseInt(subStr);
10963                        if (idx <= 1) {
10964                            idx++;
10965                        } else {
10966                            idx--;
10967                        }
10968                    } catch(NumberFormatException e) {
10969                    }
10970                }
10971            }
10972        }
10973        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
10974        return prefix + idxStr;
10975    }
10976
10977    private File getNextCodePath(File targetDir, String packageName) {
10978        int suffix = 1;
10979        File result;
10980        do {
10981            result = new File(targetDir, packageName + "-" + suffix);
10982            suffix++;
10983        } while (result.exists());
10984        return result;
10985    }
10986
10987    // Utility method that returns the relative package path with respect
10988    // to the installation directory. Like say for /data/data/com.test-1.apk
10989    // string com.test-1 is returned.
10990    static String deriveCodePathName(String codePath) {
10991        if (codePath == null) {
10992            return null;
10993        }
10994        final File codeFile = new File(codePath);
10995        final String name = codeFile.getName();
10996        if (codeFile.isDirectory()) {
10997            return name;
10998        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
10999            final int lastDot = name.lastIndexOf('.');
11000            return name.substring(0, lastDot);
11001        } else {
11002            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11003            return null;
11004        }
11005    }
11006
11007    class PackageInstalledInfo {
11008        String name;
11009        int uid;
11010        // The set of users that originally had this package installed.
11011        int[] origUsers;
11012        // The set of users that now have this package installed.
11013        int[] newUsers;
11014        PackageParser.Package pkg;
11015        int returnCode;
11016        String returnMsg;
11017        PackageRemovedInfo removedInfo;
11018
11019        public void setError(int code, String msg) {
11020            returnCode = code;
11021            returnMsg = msg;
11022            Slog.w(TAG, msg);
11023        }
11024
11025        public void setError(String msg, PackageParserException e) {
11026            returnCode = e.error;
11027            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11028            Slog.w(TAG, msg, e);
11029        }
11030
11031        public void setError(String msg, PackageManagerException e) {
11032            returnCode = e.error;
11033            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11034            Slog.w(TAG, msg, e);
11035        }
11036
11037        // In some error cases we want to convey more info back to the observer
11038        String origPackage;
11039        String origPermission;
11040    }
11041
11042    /*
11043     * Install a non-existing package.
11044     */
11045    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11046            UserHandle user, String installerPackageName, String volumeUuid,
11047            PackageInstalledInfo res) {
11048        // Remember this for later, in case we need to rollback this install
11049        String pkgName = pkg.packageName;
11050
11051        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11052        final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName,
11053                UserHandle.USER_OWNER).exists();
11054        synchronized(mPackages) {
11055            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11056                // A package with the same name is already installed, though
11057                // it has been renamed to an older name.  The package we
11058                // are trying to install should be installed as an update to
11059                // the existing one, but that has not been requested, so bail.
11060                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11061                        + " without first uninstalling package running as "
11062                        + mSettings.mRenamedPackages.get(pkgName));
11063                return;
11064            }
11065            if (mPackages.containsKey(pkgName)) {
11066                // Don't allow installation over an existing package with the same name.
11067                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11068                        + " without first uninstalling.");
11069                return;
11070            }
11071        }
11072
11073        try {
11074            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11075                    System.currentTimeMillis(), user);
11076
11077            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11078            // delete the partially installed application. the data directory will have to be
11079            // restored if it was already existing
11080            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11081                // remove package from internal structures.  Note that we want deletePackageX to
11082                // delete the package data and cache directories that it created in
11083                // scanPackageLocked, unless those directories existed before we even tried to
11084                // install.
11085                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11086                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11087                                res.removedInfo, true);
11088            }
11089
11090        } catch (PackageManagerException e) {
11091            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11092        }
11093    }
11094
11095    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11096        // Upgrade keysets are being used.  Determine if new package has a superset of the
11097        // required keys.
11098        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11099        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11100        for (int i = 0; i < upgradeKeySets.length; i++) {
11101            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11102            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
11103                return true;
11104            }
11105        }
11106        return false;
11107    }
11108
11109    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11110            UserHandle user, String installerPackageName, String volumeUuid,
11111            PackageInstalledInfo res) {
11112        final PackageParser.Package oldPackage;
11113        final String pkgName = pkg.packageName;
11114        final int[] allUsers;
11115        final boolean[] perUserInstalled;
11116        final boolean weFroze;
11117
11118        // First find the old package info and check signatures
11119        synchronized(mPackages) {
11120            oldPackage = mPackages.get(pkgName);
11121            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11122            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11123            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
11124                // default to original signature matching
11125                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11126                    != PackageManager.SIGNATURE_MATCH) {
11127                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11128                            "New package has a different signature: " + pkgName);
11129                    return;
11130                }
11131            } else {
11132                if(!checkUpgradeKeySetLP(ps, pkg)) {
11133                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11134                            "New package not signed by keys specified by upgrade-keysets: "
11135                            + pkgName);
11136                    return;
11137                }
11138            }
11139
11140            // In case of rollback, remember per-user/profile install state
11141            allUsers = sUserManager.getUserIds();
11142            perUserInstalled = new boolean[allUsers.length];
11143            for (int i = 0; i < allUsers.length; i++) {
11144                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11145            }
11146
11147            // Mark the app as frozen to prevent launching during the upgrade
11148            // process, and then kill all running instances
11149            if (!ps.frozen) {
11150                ps.frozen = true;
11151                weFroze = true;
11152            } else {
11153                weFroze = false;
11154            }
11155        }
11156
11157        // Now that we're guarded by frozen state, kill app during upgrade
11158        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11159
11160        try {
11161            boolean sysPkg = (isSystemApp(oldPackage));
11162            if (sysPkg) {
11163                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11164                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11165            } else {
11166                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11167                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11168            }
11169        } finally {
11170            // Regardless of success or failure of upgrade steps above, always
11171            // unfreeze the package if we froze it
11172            if (weFroze) {
11173                unfreezePackage(pkgName);
11174            }
11175        }
11176    }
11177
11178    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11179            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11180            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11181            String volumeUuid, PackageInstalledInfo res) {
11182        String pkgName = deletedPackage.packageName;
11183        boolean deletedPkg = true;
11184        boolean updatedSettings = false;
11185
11186        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11187                + deletedPackage);
11188        long origUpdateTime;
11189        if (pkg.mExtras != null) {
11190            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11191        } else {
11192            origUpdateTime = 0;
11193        }
11194
11195        // First delete the existing package while retaining the data directory
11196        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11197                res.removedInfo, true)) {
11198            // If the existing package wasn't successfully deleted
11199            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11200            deletedPkg = false;
11201        } else {
11202            // Successfully deleted the old package; proceed with replace.
11203
11204            // If deleted package lived in a container, give users a chance to
11205            // relinquish resources before killing.
11206            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11207                if (DEBUG_INSTALL) {
11208                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11209                }
11210                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11211                final ArrayList<String> pkgList = new ArrayList<String>(1);
11212                pkgList.add(deletedPackage.applicationInfo.packageName);
11213                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11214            }
11215
11216            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11217            try {
11218                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11219                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11220                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11221                        perUserInstalled, res, user);
11222                updatedSettings = true;
11223            } catch (PackageManagerException e) {
11224                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11225            }
11226        }
11227
11228        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11229            // remove package from internal structures.  Note that we want deletePackageX to
11230            // delete the package data and cache directories that it created in
11231            // scanPackageLocked, unless those directories existed before we even tried to
11232            // install.
11233            if(updatedSettings) {
11234                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11235                deletePackageLI(
11236                        pkgName, null, true, allUsers, perUserInstalled,
11237                        PackageManager.DELETE_KEEP_DATA,
11238                                res.removedInfo, true);
11239            }
11240            // Since we failed to install the new package we need to restore the old
11241            // package that we deleted.
11242            if (deletedPkg) {
11243                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11244                File restoreFile = new File(deletedPackage.codePath);
11245                // Parse old package
11246                boolean oldExternal = isExternal(deletedPackage);
11247                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11248                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11249                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11250                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11251                try {
11252                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11253                } catch (PackageManagerException e) {
11254                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11255                            + e.getMessage());
11256                    return;
11257                }
11258                // Restore of old package succeeded. Update permissions.
11259                // writer
11260                synchronized (mPackages) {
11261                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11262                            UPDATE_PERMISSIONS_ALL);
11263                    // can downgrade to reader
11264                    mSettings.writeLPr();
11265                }
11266                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11267            }
11268        }
11269    }
11270
11271    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11272            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11273            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11274            String volumeUuid, PackageInstalledInfo res) {
11275        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11276                + ", old=" + deletedPackage);
11277        boolean disabledSystem = false;
11278        boolean updatedSettings = false;
11279        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11280        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11281                != 0) {
11282            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11283        }
11284        String packageName = deletedPackage.packageName;
11285        if (packageName == null) {
11286            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11287                    "Attempt to delete null packageName.");
11288            return;
11289        }
11290        PackageParser.Package oldPkg;
11291        PackageSetting oldPkgSetting;
11292        // reader
11293        synchronized (mPackages) {
11294            oldPkg = mPackages.get(packageName);
11295            oldPkgSetting = mSettings.mPackages.get(packageName);
11296            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11297                    (oldPkgSetting == null)) {
11298                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11299                        "Couldn't find package:" + packageName + " information");
11300                return;
11301            }
11302        }
11303
11304        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11305        res.removedInfo.removedPackage = packageName;
11306        // Remove existing system package
11307        removePackageLI(oldPkgSetting, true);
11308        // writer
11309        synchronized (mPackages) {
11310            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11311            if (!disabledSystem && deletedPackage != null) {
11312                // We didn't need to disable the .apk as a current system package,
11313                // which means we are replacing another update that is already
11314                // installed.  We need to make sure to delete the older one's .apk.
11315                res.removedInfo.args = createInstallArgsForExisting(0,
11316                        deletedPackage.applicationInfo.getCodePath(),
11317                        deletedPackage.applicationInfo.getResourcePath(),
11318                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11319            } else {
11320                res.removedInfo.args = null;
11321            }
11322        }
11323
11324        // Successfully disabled the old package. Now proceed with re-installation
11325        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11326
11327        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11328        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11329
11330        PackageParser.Package newPackage = null;
11331        try {
11332            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11333            if (newPackage.mExtras != null) {
11334                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11335                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11336                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11337
11338                // is the update attempting to change shared user? that isn't going to work...
11339                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11340                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11341                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11342                            + " to " + newPkgSetting.sharedUser);
11343                    updatedSettings = true;
11344                }
11345            }
11346
11347            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11348                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11349                        perUserInstalled, res, user);
11350                updatedSettings = true;
11351            }
11352
11353        } catch (PackageManagerException e) {
11354            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11355        }
11356
11357        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11358            // Re installation failed. Restore old information
11359            // Remove new pkg information
11360            if (newPackage != null) {
11361                removeInstalledPackageLI(newPackage, true);
11362            }
11363            // Add back the old system package
11364            try {
11365                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11366            } catch (PackageManagerException e) {
11367                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11368            }
11369            // Restore the old system information in Settings
11370            synchronized (mPackages) {
11371                if (disabledSystem) {
11372                    mSettings.enableSystemPackageLPw(packageName);
11373                }
11374                if (updatedSettings) {
11375                    mSettings.setInstallerPackageName(packageName,
11376                            oldPkgSetting.installerPackageName);
11377                }
11378                mSettings.writeLPr();
11379            }
11380        }
11381    }
11382
11383    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
11384            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
11385            UserHandle user) {
11386        String pkgName = newPackage.packageName;
11387        synchronized (mPackages) {
11388            //write settings. the installStatus will be incomplete at this stage.
11389            //note that the new package setting would have already been
11390            //added to mPackages. It hasn't been persisted yet.
11391            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11392            mSettings.writeLPr();
11393        }
11394
11395        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11396
11397        synchronized (mPackages) {
11398            updatePermissionsLPw(newPackage.packageName, newPackage,
11399                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11400                            ? UPDATE_PERMISSIONS_ALL : 0));
11401            // For system-bundled packages, we assume that installing an upgraded version
11402            // of the package implies that the user actually wants to run that new code,
11403            // so we enable the package.
11404            PackageSetting ps = mSettings.mPackages.get(pkgName);
11405            if (ps != null) {
11406                if (isSystemApp(newPackage)) {
11407                    // NB: implicit assumption that system package upgrades apply to all users
11408                    if (DEBUG_INSTALL) {
11409                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
11410                    }
11411                    if (res.origUsers != null) {
11412                        for (int userHandle : res.origUsers) {
11413                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
11414                                    userHandle, installerPackageName);
11415                        }
11416                    }
11417                    // Also convey the prior install/uninstall state
11418                    if (allUsers != null && perUserInstalled != null) {
11419                        for (int i = 0; i < allUsers.length; i++) {
11420                            if (DEBUG_INSTALL) {
11421                                Slog.d(TAG, "    user " + allUsers[i]
11422                                        + " => " + perUserInstalled[i]);
11423                            }
11424                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
11425                        }
11426                        // these install state changes will be persisted in the
11427                        // upcoming call to mSettings.writeLPr().
11428                    }
11429                }
11430                // It's implied that when a user requests installation, they want the app to be
11431                // installed and enabled.
11432                int userId = user.getIdentifier();
11433                if (userId != UserHandle.USER_ALL) {
11434                    ps.setInstalled(true, userId);
11435                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
11436                }
11437            }
11438            res.name = pkgName;
11439            res.uid = newPackage.applicationInfo.uid;
11440            res.pkg = newPackage;
11441            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
11442            mSettings.setInstallerPackageName(pkgName, installerPackageName);
11443            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11444            //to update install status
11445            mSettings.writeLPr();
11446        }
11447    }
11448
11449    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
11450        final int installFlags = args.installFlags;
11451        final String installerPackageName = args.installerPackageName;
11452        final String volumeUuid = args.volumeUuid;
11453        final File tmpPackageFile = new File(args.getCodePath());
11454        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
11455        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
11456                || (args.volumeUuid != null));
11457        boolean replace = false;
11458        int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE;
11459        // Result object to be returned
11460        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11461
11462        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
11463        // Retrieve PackageSettings and parse package
11464        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
11465                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
11466                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11467        PackageParser pp = new PackageParser();
11468        pp.setSeparateProcesses(mSeparateProcesses);
11469        pp.setDisplayMetrics(mMetrics);
11470
11471        final PackageParser.Package pkg;
11472        try {
11473            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
11474        } catch (PackageParserException e) {
11475            res.setError("Failed parse during installPackageLI", e);
11476            return;
11477        }
11478
11479        // Mark that we have an install time CPU ABI override.
11480        pkg.cpuAbiOverride = args.abiOverride;
11481
11482        String pkgName = res.name = pkg.packageName;
11483        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
11484            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
11485                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
11486                return;
11487            }
11488        }
11489
11490        try {
11491            pp.collectCertificates(pkg, parseFlags);
11492            pp.collectManifestDigest(pkg);
11493        } catch (PackageParserException e) {
11494            res.setError("Failed collect during installPackageLI", e);
11495            return;
11496        }
11497
11498        /* If the installer passed in a manifest digest, compare it now. */
11499        if (args.manifestDigest != null) {
11500            if (DEBUG_INSTALL) {
11501                final String parsedManifest = pkg.manifestDigest == null ? "null"
11502                        : pkg.manifestDigest.toString();
11503                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
11504                        + parsedManifest);
11505            }
11506
11507            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
11508                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
11509                return;
11510            }
11511        } else if (DEBUG_INSTALL) {
11512            final String parsedManifest = pkg.manifestDigest == null
11513                    ? "null" : pkg.manifestDigest.toString();
11514            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
11515        }
11516
11517        // Get rid of all references to package scan path via parser.
11518        pp = null;
11519        String oldCodePath = null;
11520        boolean systemApp = false;
11521        synchronized (mPackages) {
11522            // Check if installing already existing package
11523            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11524                String oldName = mSettings.mRenamedPackages.get(pkgName);
11525                if (pkg.mOriginalPackages != null
11526                        && pkg.mOriginalPackages.contains(oldName)
11527                        && mPackages.containsKey(oldName)) {
11528                    // This package is derived from an original package,
11529                    // and this device has been updating from that original
11530                    // name.  We must continue using the original name, so
11531                    // rename the new package here.
11532                    pkg.setPackageName(oldName);
11533                    pkgName = pkg.packageName;
11534                    replace = true;
11535                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
11536                            + oldName + " pkgName=" + pkgName);
11537                } else if (mPackages.containsKey(pkgName)) {
11538                    // This package, under its official name, already exists
11539                    // on the device; we should replace it.
11540                    replace = true;
11541                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
11542                }
11543
11544                // Prevent apps opting out from runtime permissions
11545                if (replace) {
11546                    PackageParser.Package oldPackage = mPackages.get(pkgName);
11547                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
11548                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
11549                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
11550                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
11551                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
11552                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
11553                                        + " doesn't support runtime permissions but the old"
11554                                        + " target SDK " + oldTargetSdk + " does.");
11555                        return;
11556                    }
11557                }
11558            }
11559
11560            PackageSetting ps = mSettings.mPackages.get(pkgName);
11561            if (ps != null) {
11562                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
11563
11564                // Quick sanity check that we're signed correctly if updating;
11565                // we'll check this again later when scanning, but we want to
11566                // bail early here before tripping over redefined permissions.
11567                if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
11568                    try {
11569                        verifySignaturesLP(ps, pkg);
11570                    } catch (PackageManagerException e) {
11571                        res.setError(e.error, e.getMessage());
11572                        return;
11573                    }
11574                } else {
11575                    if (!checkUpgradeKeySetLP(ps, pkg)) {
11576                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
11577                                + pkg.packageName + " upgrade keys do not match the "
11578                                + "previously installed version");
11579                        return;
11580                    }
11581                }
11582
11583                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
11584                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
11585                    systemApp = (ps.pkg.applicationInfo.flags &
11586                            ApplicationInfo.FLAG_SYSTEM) != 0;
11587                }
11588                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11589            }
11590
11591            // Check whether the newly-scanned package wants to define an already-defined perm
11592            int N = pkg.permissions.size();
11593            for (int i = N-1; i >= 0; i--) {
11594                PackageParser.Permission perm = pkg.permissions.get(i);
11595                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
11596                if (bp != null) {
11597                    // If the defining package is signed with our cert, it's okay.  This
11598                    // also includes the "updating the same package" case, of course.
11599                    // "updating same package" could also involve key-rotation.
11600                    final boolean sigsOk;
11601                    if (!bp.sourcePackage.equals(pkg.packageName)
11602                            || !(bp.packageSetting instanceof PackageSetting)
11603                            || !bp.packageSetting.keySetData.isUsingUpgradeKeySets()
11604                            || ((PackageSetting) bp.packageSetting).sharedUser != null) {
11605                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
11606                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
11607                    } else {
11608                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
11609                    }
11610                    if (!sigsOk) {
11611                        // If the owning package is the system itself, we log but allow
11612                        // install to proceed; we fail the install on all other permission
11613                        // redefinitions.
11614                        if (!bp.sourcePackage.equals("android")) {
11615                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
11616                                    + pkg.packageName + " attempting to redeclare permission "
11617                                    + perm.info.name + " already owned by " + bp.sourcePackage);
11618                            res.origPermission = perm.info.name;
11619                            res.origPackage = bp.sourcePackage;
11620                            return;
11621                        } else {
11622                            Slog.w(TAG, "Package " + pkg.packageName
11623                                    + " attempting to redeclare system permission "
11624                                    + perm.info.name + "; ignoring new declaration");
11625                            pkg.permissions.remove(i);
11626                        }
11627                    }
11628                }
11629            }
11630
11631        }
11632
11633        if (systemApp && onExternal) {
11634            // Disable updates to system apps on sdcard
11635            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11636                    "Cannot install updates to system apps on sdcard");
11637            return;
11638        }
11639
11640        if (args.move != null) {
11641            // We did an in-place move, so dex is ready to roll
11642            scanFlags |= SCAN_NO_DEX;
11643        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
11644            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
11645            scanFlags |= SCAN_NO_DEX;
11646
11647            try {
11648                deriveNonSystemPackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
11649                        true /* extract libs */);
11650            } catch (PackageManagerException pme) {
11651                Slog.e(TAG, "Error deriving application ABI", pme);
11652                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error ");
11653                return;
11654            }
11655
11656            // Run dexopt before old package gets removed, to minimize time when app is unavailable
11657            int result = mPackageDexOptimizer
11658                    .performDexOpt(pkg, null /* instruction sets */, true /* forceDex */,
11659                            false /* defer */, false /* inclDependencies */);
11660            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
11661                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
11662                return;
11663            }
11664        }
11665
11666        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
11667            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
11668            return;
11669        }
11670
11671        startIntentFilterVerifications(args.user.getIdentifier(), pkg);
11672
11673        if (replace) {
11674            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
11675                    installerPackageName, volumeUuid, res);
11676        } else {
11677            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
11678                    args.user, installerPackageName, volumeUuid, res);
11679        }
11680        synchronized (mPackages) {
11681            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11682            if (ps != null) {
11683                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11684            }
11685        }
11686    }
11687
11688    private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) {
11689        if (mIntentFilterVerifierComponent == null) {
11690            Slog.d(TAG, "No IntentFilter verification will not be done as "
11691                    + "there is no IntentFilterVerifier available!");
11692            return;
11693        }
11694
11695        final int verifierUid = getPackageUid(
11696                mIntentFilterVerifierComponent.getPackageName(),
11697                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
11698
11699        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
11700        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
11701        msg.obj = pkg;
11702        msg.arg1 = userId;
11703        msg.arg2 = verifierUid;
11704
11705        mHandler.sendMessage(msg);
11706    }
11707
11708    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid,
11709            PackageParser.Package pkg) {
11710        int size = pkg.activities.size();
11711        if (size == 0) {
11712            Slog.d(TAG, "No activity, so no need to verify any IntentFilter!");
11713            return;
11714        }
11715
11716        final boolean hasDomainURLs = hasDomainURLs(pkg);
11717        if (!hasDomainURLs) {
11718            Slog.d(TAG, "No domain URLs, so no need to verify any IntentFilter!");
11719            return;
11720        }
11721
11722        Slog.d(TAG, "Checking for userId:" + userId + " if any IntentFilter from the " + size
11723                + " Activities needs verification ...");
11724
11725        final int verificationId = mIntentFilterVerificationToken++;
11726        int count = 0;
11727        final String packageName = pkg.packageName;
11728        ArrayList<String> allHosts = new ArrayList<>();
11729
11730        synchronized (mPackages) {
11731            for (PackageParser.Activity a : pkg.activities) {
11732                for (ActivityIntentInfo filter : a.intents) {
11733                    boolean needsFilterVerification = filter.needsVerification();
11734                    if (needsFilterVerification && needsNetworkVerificationLPr(filter)) {
11735                        Slog.d(TAG, "Verification needed for IntentFilter:" + filter.toString());
11736                        mIntentFilterVerifier.addOneIntentFilterVerification(
11737                                verifierUid, userId, verificationId, filter, packageName);
11738                        count++;
11739                    } else if (!needsFilterVerification) {
11740                        Slog.d(TAG, "No verification needed for IntentFilter:" + filter.toString());
11741                        if (hasValidDomains(filter)) {
11742                            ArrayList<String> hosts = filter.getHostsList();
11743                            if (hosts.size() > 0) {
11744                                allHosts.addAll(hosts);
11745                            } else {
11746                                if (allHosts.isEmpty()) {
11747                                    allHosts.add("*");
11748                                }
11749                            }
11750                        }
11751                    } else {
11752                        Slog.d(TAG, "Verification already done for IntentFilter:"
11753                                + filter.toString());
11754                    }
11755                }
11756            }
11757        }
11758
11759        if (count > 0) {
11760            mIntentFilterVerifier.startVerifications(userId);
11761            Slog.d(TAG, "Started " + count + " IntentFilter verification"
11762                    + (count > 1 ? "s" : "") +  " for userId:" + userId + "!");
11763        } else {
11764            Slog.d(TAG, "No need to start any IntentFilter verification!");
11765            if (allHosts.size() > 0 && mSettings.createIntentFilterVerificationIfNeededLPw(
11766                    packageName, allHosts) != null) {
11767                scheduleWriteSettingsLocked();
11768            }
11769        }
11770    }
11771
11772    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
11773        final ComponentName cn  = filter.activity.getComponentName();
11774        final String packageName = cn.getPackageName();
11775
11776        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
11777                packageName);
11778        if (ivi == null) {
11779            return true;
11780        }
11781        int status = ivi.getStatus();
11782        switch (status) {
11783            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
11784            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
11785                return true;
11786
11787            default:
11788                // Nothing to do
11789                return false;
11790        }
11791    }
11792
11793    private boolean isSystemComponentOrPersistentPrivApp(PackageParser.Package pkg) {
11794        return UserHandle.getAppId(pkg.applicationInfo.uid) < FIRST_APPLICATION_UID
11795                || ((pkg.applicationInfo.privateFlags
11796                        & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0
11797                && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0);
11798    }
11799
11800    private static boolean isMultiArch(PackageSetting ps) {
11801        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
11802    }
11803
11804    private static boolean isMultiArch(ApplicationInfo info) {
11805        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
11806    }
11807
11808    private static boolean isExternal(PackageParser.Package pkg) {
11809        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11810    }
11811
11812    private static boolean isExternal(PackageSetting ps) {
11813        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11814    }
11815
11816    private static boolean isExternal(ApplicationInfo info) {
11817        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11818    }
11819
11820    private static boolean isSystemApp(PackageParser.Package pkg) {
11821        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
11822    }
11823
11824    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
11825        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
11826    }
11827
11828    private static boolean hasDomainURLs(PackageParser.Package pkg) {
11829        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
11830    }
11831
11832    private static boolean isSystemApp(PackageSetting ps) {
11833        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
11834    }
11835
11836    private static boolean isUpdatedSystemApp(PackageSetting ps) {
11837        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
11838    }
11839
11840    private int packageFlagsToInstallFlags(PackageSetting ps) {
11841        int installFlags = 0;
11842        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
11843            // This existing package was an external ASEC install when we have
11844            // the external flag without a UUID
11845            installFlags |= PackageManager.INSTALL_EXTERNAL;
11846        }
11847        if (ps.isForwardLocked()) {
11848            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
11849        }
11850        return installFlags;
11851    }
11852
11853    private void deleteTempPackageFiles() {
11854        final FilenameFilter filter = new FilenameFilter() {
11855            public boolean accept(File dir, String name) {
11856                return name.startsWith("vmdl") && name.endsWith(".tmp");
11857            }
11858        };
11859        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
11860            file.delete();
11861        }
11862    }
11863
11864    @Override
11865    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
11866            int flags) {
11867        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
11868                flags);
11869    }
11870
11871    @Override
11872    public void deletePackage(final String packageName,
11873            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
11874        mContext.enforceCallingOrSelfPermission(
11875                android.Manifest.permission.DELETE_PACKAGES, null);
11876        final int uid = Binder.getCallingUid();
11877        if (UserHandle.getUserId(uid) != userId) {
11878            mContext.enforceCallingPermission(
11879                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
11880                    "deletePackage for user " + userId);
11881        }
11882        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
11883            try {
11884                observer.onPackageDeleted(packageName,
11885                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
11886            } catch (RemoteException re) {
11887            }
11888            return;
11889        }
11890
11891        boolean uninstallBlocked = false;
11892        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
11893            int[] users = sUserManager.getUserIds();
11894            for (int i = 0; i < users.length; ++i) {
11895                if (getBlockUninstallForUser(packageName, users[i])) {
11896                    uninstallBlocked = true;
11897                    break;
11898                }
11899            }
11900        } else {
11901            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
11902        }
11903        if (uninstallBlocked) {
11904            try {
11905                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
11906                        null);
11907            } catch (RemoteException re) {
11908            }
11909            return;
11910        }
11911
11912        if (DEBUG_REMOVE) {
11913            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
11914        }
11915        // Queue up an async operation since the package deletion may take a little while.
11916        mHandler.post(new Runnable() {
11917            public void run() {
11918                mHandler.removeCallbacks(this);
11919                final int returnCode = deletePackageX(packageName, userId, flags);
11920                if (observer != null) {
11921                    try {
11922                        observer.onPackageDeleted(packageName, returnCode, null);
11923                    } catch (RemoteException e) {
11924                        Log.i(TAG, "Observer no longer exists.");
11925                    } //end catch
11926                } //end if
11927            } //end run
11928        });
11929    }
11930
11931    private boolean isPackageDeviceAdmin(String packageName, int userId) {
11932        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
11933                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
11934        try {
11935            if (dpm != null) {
11936                if (dpm.isDeviceOwner(packageName)) {
11937                    return true;
11938                }
11939                int[] users;
11940                if (userId == UserHandle.USER_ALL) {
11941                    users = sUserManager.getUserIds();
11942                } else {
11943                    users = new int[]{userId};
11944                }
11945                for (int i = 0; i < users.length; ++i) {
11946                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
11947                        return true;
11948                    }
11949                }
11950            }
11951        } catch (RemoteException e) {
11952        }
11953        return false;
11954    }
11955
11956    /**
11957     *  This method is an internal method that could be get invoked either
11958     *  to delete an installed package or to clean up a failed installation.
11959     *  After deleting an installed package, a broadcast is sent to notify any
11960     *  listeners that the package has been installed. For cleaning up a failed
11961     *  installation, the broadcast is not necessary since the package's
11962     *  installation wouldn't have sent the initial broadcast either
11963     *  The key steps in deleting a package are
11964     *  deleting the package information in internal structures like mPackages,
11965     *  deleting the packages base directories through installd
11966     *  updating mSettings to reflect current status
11967     *  persisting settings for later use
11968     *  sending a broadcast if necessary
11969     */
11970    private int deletePackageX(String packageName, int userId, int flags) {
11971        final PackageRemovedInfo info = new PackageRemovedInfo();
11972        final boolean res;
11973
11974        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
11975                ? UserHandle.ALL : new UserHandle(userId);
11976
11977        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
11978            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
11979            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
11980        }
11981
11982        boolean removedForAllUsers = false;
11983        boolean systemUpdate = false;
11984
11985        // for the uninstall-updates case and restricted profiles, remember the per-
11986        // userhandle installed state
11987        int[] allUsers;
11988        boolean[] perUserInstalled;
11989        synchronized (mPackages) {
11990            PackageSetting ps = mSettings.mPackages.get(packageName);
11991            allUsers = sUserManager.getUserIds();
11992            perUserInstalled = new boolean[allUsers.length];
11993            for (int i = 0; i < allUsers.length; i++) {
11994                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11995            }
11996        }
11997
11998        synchronized (mInstallLock) {
11999            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12000            res = deletePackageLI(packageName, removeForUser,
12001                    true, allUsers, perUserInstalled,
12002                    flags | REMOVE_CHATTY, info, true);
12003            systemUpdate = info.isRemovedPackageSystemUpdate;
12004            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12005                removedForAllUsers = true;
12006            }
12007            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12008                    + " removedForAllUsers=" + removedForAllUsers);
12009        }
12010
12011        if (res) {
12012            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12013
12014            // If the removed package was a system update, the old system package
12015            // was re-enabled; we need to broadcast this information
12016            if (systemUpdate) {
12017                Bundle extras = new Bundle(1);
12018                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12019                        ? info.removedAppId : info.uid);
12020                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12021
12022                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12023                        extras, null, null, null);
12024                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12025                        extras, null, null, null);
12026                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12027                        null, packageName, null, null);
12028            }
12029        }
12030        // Force a gc here.
12031        Runtime.getRuntime().gc();
12032        // Delete the resources here after sending the broadcast to let
12033        // other processes clean up before deleting resources.
12034        if (info.args != null) {
12035            synchronized (mInstallLock) {
12036                info.args.doPostDeleteLI(true);
12037            }
12038        }
12039
12040        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12041    }
12042
12043    class PackageRemovedInfo {
12044        String removedPackage;
12045        int uid = -1;
12046        int removedAppId = -1;
12047        int[] removedUsers = null;
12048        boolean isRemovedPackageSystemUpdate = false;
12049        // Clean up resources deleted packages.
12050        InstallArgs args = null;
12051
12052        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12053            Bundle extras = new Bundle(1);
12054            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12055            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12056            if (replacing) {
12057                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12058            }
12059            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12060            if (removedPackage != null) {
12061                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12062                        extras, null, null, removedUsers);
12063                if (fullRemove && !replacing) {
12064                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12065                            extras, null, null, removedUsers);
12066                }
12067            }
12068            if (removedAppId >= 0) {
12069                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12070                        removedUsers);
12071            }
12072        }
12073    }
12074
12075    /*
12076     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12077     * flag is not set, the data directory is removed as well.
12078     * make sure this flag is set for partially installed apps. If not its meaningless to
12079     * delete a partially installed application.
12080     */
12081    private void removePackageDataLI(PackageSetting ps,
12082            int[] allUserHandles, boolean[] perUserInstalled,
12083            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12084        String packageName = ps.name;
12085        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12086        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12087        // Retrieve object to delete permissions for shared user later on
12088        final PackageSetting deletedPs;
12089        // reader
12090        synchronized (mPackages) {
12091            deletedPs = mSettings.mPackages.get(packageName);
12092            if (outInfo != null) {
12093                outInfo.removedPackage = packageName;
12094                outInfo.removedUsers = deletedPs != null
12095                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12096                        : null;
12097            }
12098        }
12099        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12100            removeDataDirsLI(ps.volumeUuid, packageName);
12101            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12102        }
12103        // writer
12104        synchronized (mPackages) {
12105            if (deletedPs != null) {
12106                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12107                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12108                    clearDefaultBrowserIfNeeded(packageName);
12109                    if (outInfo != null) {
12110                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12111                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12112                    }
12113                    updatePermissionsLPw(deletedPs.name, null, 0);
12114                    if (deletedPs.sharedUser != null) {
12115                        // Remove permissions associated with package. Since runtime
12116                        // permissions are per user we have to kill the removed package
12117                        // or packages running under the shared user of the removed
12118                        // package if revoking the permissions requested only by the removed
12119                        // package is successful and this causes a change in gids.
12120                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12121                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12122                                    userId);
12123                            if (userIdToKill == UserHandle.USER_ALL
12124                                    || userIdToKill >= UserHandle.USER_OWNER) {
12125                                // If gids changed for this user, kill all affected packages.
12126                                mHandler.post(new Runnable() {
12127                                    @Override
12128                                    public void run() {
12129                                        // This has to happen with no lock held.
12130                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12131                                                KILL_APP_REASON_GIDS_CHANGED);
12132                                    }
12133                                });
12134                            break;
12135                            }
12136                        }
12137                    }
12138                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12139                }
12140                // make sure to preserve per-user disabled state if this removal was just
12141                // a downgrade of a system app to the factory package
12142                if (allUserHandles != null && perUserInstalled != null) {
12143                    if (DEBUG_REMOVE) {
12144                        Slog.d(TAG, "Propagating install state across downgrade");
12145                    }
12146                    for (int i = 0; i < allUserHandles.length; i++) {
12147                        if (DEBUG_REMOVE) {
12148                            Slog.d(TAG, "    user " + allUserHandles[i]
12149                                    + " => " + perUserInstalled[i]);
12150                        }
12151                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12152                    }
12153                }
12154            }
12155            // can downgrade to reader
12156            if (writeSettings) {
12157                // Save settings now
12158                mSettings.writeLPr();
12159            }
12160        }
12161        if (outInfo != null) {
12162            // A user ID was deleted here. Go through all users and remove it
12163            // from KeyStore.
12164            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12165        }
12166    }
12167
12168    static boolean locationIsPrivileged(File path) {
12169        try {
12170            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12171                    .getCanonicalPath();
12172            return path.getCanonicalPath().startsWith(privilegedAppDir);
12173        } catch (IOException e) {
12174            Slog.e(TAG, "Unable to access code path " + path);
12175        }
12176        return false;
12177    }
12178
12179    /*
12180     * Tries to delete system package.
12181     */
12182    private boolean deleteSystemPackageLI(PackageSetting newPs,
12183            int[] allUserHandles, boolean[] perUserInstalled,
12184            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12185        final boolean applyUserRestrictions
12186                = (allUserHandles != null) && (perUserInstalled != null);
12187        PackageSetting disabledPs = null;
12188        // Confirm if the system package has been updated
12189        // An updated system app can be deleted. This will also have to restore
12190        // the system pkg from system partition
12191        // reader
12192        synchronized (mPackages) {
12193            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12194        }
12195        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12196                + " disabledPs=" + disabledPs);
12197        if (disabledPs == null) {
12198            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12199            return false;
12200        } else if (DEBUG_REMOVE) {
12201            Slog.d(TAG, "Deleting system pkg from data partition");
12202        }
12203        if (DEBUG_REMOVE) {
12204            if (applyUserRestrictions) {
12205                Slog.d(TAG, "Remembering install states:");
12206                for (int i = 0; i < allUserHandles.length; i++) {
12207                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12208                }
12209            }
12210        }
12211        // Delete the updated package
12212        outInfo.isRemovedPackageSystemUpdate = true;
12213        if (disabledPs.versionCode < newPs.versionCode) {
12214            // Delete data for downgrades
12215            flags &= ~PackageManager.DELETE_KEEP_DATA;
12216        } else {
12217            // Preserve data by setting flag
12218            flags |= PackageManager.DELETE_KEEP_DATA;
12219        }
12220        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12221                allUserHandles, perUserInstalled, outInfo, writeSettings);
12222        if (!ret) {
12223            return false;
12224        }
12225        // writer
12226        synchronized (mPackages) {
12227            // Reinstate the old system package
12228            mSettings.enableSystemPackageLPw(newPs.name);
12229            // Remove any native libraries from the upgraded package.
12230            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12231        }
12232        // Install the system package
12233        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12234        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12235        if (locationIsPrivileged(disabledPs.codePath)) {
12236            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12237        }
12238
12239        final PackageParser.Package newPkg;
12240        try {
12241            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12242        } catch (PackageManagerException e) {
12243            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12244            return false;
12245        }
12246
12247        // writer
12248        synchronized (mPackages) {
12249            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12250            updatePermissionsLPw(newPkg.packageName, newPkg,
12251                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12252            if (applyUserRestrictions) {
12253                if (DEBUG_REMOVE) {
12254                    Slog.d(TAG, "Propagating install state across reinstall");
12255                }
12256                for (int i = 0; i < allUserHandles.length; i++) {
12257                    if (DEBUG_REMOVE) {
12258                        Slog.d(TAG, "    user " + allUserHandles[i]
12259                                + " => " + perUserInstalled[i]);
12260                    }
12261                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12262                }
12263                // Regardless of writeSettings we need to ensure that this restriction
12264                // state propagation is persisted
12265                mSettings.writeAllUsersPackageRestrictionsLPr();
12266            }
12267            // can downgrade to reader here
12268            if (writeSettings) {
12269                mSettings.writeLPr();
12270            }
12271        }
12272        return true;
12273    }
12274
12275    private boolean deleteInstalledPackageLI(PackageSetting ps,
12276            boolean deleteCodeAndResources, int flags,
12277            int[] allUserHandles, boolean[] perUserInstalled,
12278            PackageRemovedInfo outInfo, boolean writeSettings) {
12279        if (outInfo != null) {
12280            outInfo.uid = ps.appId;
12281        }
12282
12283        // Delete package data from internal structures and also remove data if flag is set
12284        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12285
12286        // Delete application code and resources
12287        if (deleteCodeAndResources && (outInfo != null)) {
12288            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12289                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12290            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12291        }
12292        return true;
12293    }
12294
12295    @Override
12296    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12297            int userId) {
12298        mContext.enforceCallingOrSelfPermission(
12299                android.Manifest.permission.DELETE_PACKAGES, null);
12300        synchronized (mPackages) {
12301            PackageSetting ps = mSettings.mPackages.get(packageName);
12302            if (ps == null) {
12303                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12304                return false;
12305            }
12306            if (!ps.getInstalled(userId)) {
12307                // Can't block uninstall for an app that is not installed or enabled.
12308                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12309                return false;
12310            }
12311            ps.setBlockUninstall(blockUninstall, userId);
12312            mSettings.writePackageRestrictionsLPr(userId);
12313        }
12314        return true;
12315    }
12316
12317    @Override
12318    public boolean getBlockUninstallForUser(String packageName, int userId) {
12319        synchronized (mPackages) {
12320            PackageSetting ps = mSettings.mPackages.get(packageName);
12321            if (ps == null) {
12322                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
12323                return false;
12324            }
12325            return ps.getBlockUninstall(userId);
12326        }
12327    }
12328
12329    /*
12330     * This method handles package deletion in general
12331     */
12332    private boolean deletePackageLI(String packageName, UserHandle user,
12333            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
12334            int flags, PackageRemovedInfo outInfo,
12335            boolean writeSettings) {
12336        if (packageName == null) {
12337            Slog.w(TAG, "Attempt to delete null packageName.");
12338            return false;
12339        }
12340        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
12341        PackageSetting ps;
12342        boolean dataOnly = false;
12343        int removeUser = -1;
12344        int appId = -1;
12345        synchronized (mPackages) {
12346            ps = mSettings.mPackages.get(packageName);
12347            if (ps == null) {
12348                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12349                return false;
12350            }
12351            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
12352                    && user.getIdentifier() != UserHandle.USER_ALL) {
12353                // The caller is asking that the package only be deleted for a single
12354                // user.  To do this, we just mark its uninstalled state and delete
12355                // its data.  If this is a system app, we only allow this to happen if
12356                // they have set the special DELETE_SYSTEM_APP which requests different
12357                // semantics than normal for uninstalling system apps.
12358                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
12359                ps.setUserState(user.getIdentifier(),
12360                        COMPONENT_ENABLED_STATE_DEFAULT,
12361                        false, //installed
12362                        true,  //stopped
12363                        true,  //notLaunched
12364                        false, //hidden
12365                        null, null, null,
12366                        false, // blockUninstall
12367                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
12368                if (!isSystemApp(ps)) {
12369                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
12370                        // Other user still have this package installed, so all
12371                        // we need to do is clear this user's data and save that
12372                        // it is uninstalled.
12373                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
12374                        removeUser = user.getIdentifier();
12375                        appId = ps.appId;
12376                        scheduleWritePackageRestrictionsLocked(removeUser);
12377                    } else {
12378                        // We need to set it back to 'installed' so the uninstall
12379                        // broadcasts will be sent correctly.
12380                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
12381                        ps.setInstalled(true, user.getIdentifier());
12382                    }
12383                } else {
12384                    // This is a system app, so we assume that the
12385                    // other users still have this package installed, so all
12386                    // we need to do is clear this user's data and save that
12387                    // it is uninstalled.
12388                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
12389                    removeUser = user.getIdentifier();
12390                    appId = ps.appId;
12391                    scheduleWritePackageRestrictionsLocked(removeUser);
12392                }
12393            }
12394        }
12395
12396        if (removeUser >= 0) {
12397            // From above, we determined that we are deleting this only
12398            // for a single user.  Continue the work here.
12399            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
12400            if (outInfo != null) {
12401                outInfo.removedPackage = packageName;
12402                outInfo.removedAppId = appId;
12403                outInfo.removedUsers = new int[] {removeUser};
12404            }
12405            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
12406            removeKeystoreDataIfNeeded(removeUser, appId);
12407            schedulePackageCleaning(packageName, removeUser, false);
12408            synchronized (mPackages) {
12409                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
12410                    scheduleWritePackageRestrictionsLocked(removeUser);
12411                }
12412            }
12413            return true;
12414        }
12415
12416        if (dataOnly) {
12417            // Delete application data first
12418            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
12419            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
12420            return true;
12421        }
12422
12423        boolean ret = false;
12424        if (isSystemApp(ps)) {
12425            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
12426            // When an updated system application is deleted we delete the existing resources as well and
12427            // fall back to existing code in system partition
12428            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
12429                    flags, outInfo, writeSettings);
12430        } else {
12431            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
12432            // Kill application pre-emptively especially for apps on sd.
12433            killApplication(packageName, ps.appId, "uninstall pkg");
12434            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
12435                    allUserHandles, perUserInstalled,
12436                    outInfo, writeSettings);
12437        }
12438
12439        return ret;
12440    }
12441
12442    private final class ClearStorageConnection implements ServiceConnection {
12443        IMediaContainerService mContainerService;
12444
12445        @Override
12446        public void onServiceConnected(ComponentName name, IBinder service) {
12447            synchronized (this) {
12448                mContainerService = IMediaContainerService.Stub.asInterface(service);
12449                notifyAll();
12450            }
12451        }
12452
12453        @Override
12454        public void onServiceDisconnected(ComponentName name) {
12455        }
12456    }
12457
12458    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
12459        final boolean mounted;
12460        if (Environment.isExternalStorageEmulated()) {
12461            mounted = true;
12462        } else {
12463            final String status = Environment.getExternalStorageState();
12464
12465            mounted = status.equals(Environment.MEDIA_MOUNTED)
12466                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
12467        }
12468
12469        if (!mounted) {
12470            return;
12471        }
12472
12473        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
12474        int[] users;
12475        if (userId == UserHandle.USER_ALL) {
12476            users = sUserManager.getUserIds();
12477        } else {
12478            users = new int[] { userId };
12479        }
12480        final ClearStorageConnection conn = new ClearStorageConnection();
12481        if (mContext.bindServiceAsUser(
12482                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
12483            try {
12484                for (int curUser : users) {
12485                    long timeout = SystemClock.uptimeMillis() + 5000;
12486                    synchronized (conn) {
12487                        long now = SystemClock.uptimeMillis();
12488                        while (conn.mContainerService == null && now < timeout) {
12489                            try {
12490                                conn.wait(timeout - now);
12491                            } catch (InterruptedException e) {
12492                            }
12493                        }
12494                    }
12495                    if (conn.mContainerService == null) {
12496                        return;
12497                    }
12498
12499                    final UserEnvironment userEnv = new UserEnvironment(curUser);
12500                    clearDirectory(conn.mContainerService,
12501                            userEnv.buildExternalStorageAppCacheDirs(packageName));
12502                    if (allData) {
12503                        clearDirectory(conn.mContainerService,
12504                                userEnv.buildExternalStorageAppDataDirs(packageName));
12505                        clearDirectory(conn.mContainerService,
12506                                userEnv.buildExternalStorageAppMediaDirs(packageName));
12507                    }
12508                }
12509            } finally {
12510                mContext.unbindService(conn);
12511            }
12512        }
12513    }
12514
12515    @Override
12516    public void clearApplicationUserData(final String packageName,
12517            final IPackageDataObserver observer, final int userId) {
12518        mContext.enforceCallingOrSelfPermission(
12519                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
12520        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
12521        // Queue up an async operation since the package deletion may take a little while.
12522        mHandler.post(new Runnable() {
12523            public void run() {
12524                mHandler.removeCallbacks(this);
12525                final boolean succeeded;
12526                synchronized (mInstallLock) {
12527                    succeeded = clearApplicationUserDataLI(packageName, userId);
12528                }
12529                clearExternalStorageDataSync(packageName, userId, true);
12530                if (succeeded) {
12531                    // invoke DeviceStorageMonitor's update method to clear any notifications
12532                    DeviceStorageMonitorInternal
12533                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
12534                    if (dsm != null) {
12535                        dsm.checkMemory();
12536                    }
12537                }
12538                if(observer != null) {
12539                    try {
12540                        observer.onRemoveCompleted(packageName, succeeded);
12541                    } catch (RemoteException e) {
12542                        Log.i(TAG, "Observer no longer exists.");
12543                    }
12544                } //end if observer
12545            } //end run
12546        });
12547    }
12548
12549    private boolean clearApplicationUserDataLI(String packageName, int userId) {
12550        if (packageName == null) {
12551            Slog.w(TAG, "Attempt to delete null packageName.");
12552            return false;
12553        }
12554
12555        // Try finding details about the requested package
12556        PackageParser.Package pkg;
12557        synchronized (mPackages) {
12558            pkg = mPackages.get(packageName);
12559            if (pkg == null) {
12560                final PackageSetting ps = mSettings.mPackages.get(packageName);
12561                if (ps != null) {
12562                    pkg = ps.pkg;
12563                }
12564            }
12565        }
12566
12567        if (pkg == null) {
12568            Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12569        }
12570
12571        // Always delete data directories for package, even if we found no other
12572        // record of app. This helps users recover from UID mismatches without
12573        // resorting to a full data wipe.
12574        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
12575        if (retCode < 0) {
12576            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
12577            return false;
12578        }
12579
12580        if (pkg == null) {
12581            return false;
12582        }
12583
12584        if (pkg != null && pkg.applicationInfo != null) {
12585            final int appId = pkg.applicationInfo.uid;
12586            removeKeystoreDataIfNeeded(userId, appId);
12587        }
12588
12589        // Create a native library symlink only if we have native libraries
12590        // and if the native libraries are 32 bit libraries. We do not provide
12591        // this symlink for 64 bit libraries.
12592        if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null &&
12593                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
12594            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
12595            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
12596                    nativeLibPath, userId) < 0) {
12597                Slog.w(TAG, "Failed linking native library dir");
12598                return false;
12599            }
12600        }
12601
12602        return true;
12603    }
12604
12605    /**
12606     * Remove entries from the keystore daemon. Will only remove it if the
12607     * {@code appId} is valid.
12608     */
12609    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
12610        if (appId < 0) {
12611            return;
12612        }
12613
12614        final KeyStore keyStore = KeyStore.getInstance();
12615        if (keyStore != null) {
12616            if (userId == UserHandle.USER_ALL) {
12617                for (final int individual : sUserManager.getUserIds()) {
12618                    keyStore.clearUid(UserHandle.getUid(individual, appId));
12619                }
12620            } else {
12621                keyStore.clearUid(UserHandle.getUid(userId, appId));
12622            }
12623        } else {
12624            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
12625        }
12626    }
12627
12628    @Override
12629    public void deleteApplicationCacheFiles(final String packageName,
12630            final IPackageDataObserver observer) {
12631        mContext.enforceCallingOrSelfPermission(
12632                android.Manifest.permission.DELETE_CACHE_FILES, null);
12633        // Queue up an async operation since the package deletion may take a little while.
12634        final int userId = UserHandle.getCallingUserId();
12635        mHandler.post(new Runnable() {
12636            public void run() {
12637                mHandler.removeCallbacks(this);
12638                final boolean succeded;
12639                synchronized (mInstallLock) {
12640                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
12641                }
12642                clearExternalStorageDataSync(packageName, userId, false);
12643                if (observer != null) {
12644                    try {
12645                        observer.onRemoveCompleted(packageName, succeded);
12646                    } catch (RemoteException e) {
12647                        Log.i(TAG, "Observer no longer exists.");
12648                    }
12649                } //end if observer
12650            } //end run
12651        });
12652    }
12653
12654    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
12655        if (packageName == null) {
12656            Slog.w(TAG, "Attempt to delete null packageName.");
12657            return false;
12658        }
12659        PackageParser.Package p;
12660        synchronized (mPackages) {
12661            p = mPackages.get(packageName);
12662        }
12663        if (p == null) {
12664            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12665            return false;
12666        }
12667        final ApplicationInfo applicationInfo = p.applicationInfo;
12668        if (applicationInfo == null) {
12669            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12670            return false;
12671        }
12672        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
12673        if (retCode < 0) {
12674            Slog.w(TAG, "Couldn't remove cache files for package: "
12675                       + packageName + " u" + userId);
12676            return false;
12677        }
12678        return true;
12679    }
12680
12681    @Override
12682    public void getPackageSizeInfo(final String packageName, int userHandle,
12683            final IPackageStatsObserver observer) {
12684        mContext.enforceCallingOrSelfPermission(
12685                android.Manifest.permission.GET_PACKAGE_SIZE, null);
12686        if (packageName == null) {
12687            throw new IllegalArgumentException("Attempt to get size of null packageName");
12688        }
12689
12690        PackageStats stats = new PackageStats(packageName, userHandle);
12691
12692        /*
12693         * Queue up an async operation since the package measurement may take a
12694         * little while.
12695         */
12696        Message msg = mHandler.obtainMessage(INIT_COPY);
12697        msg.obj = new MeasureParams(stats, observer);
12698        mHandler.sendMessage(msg);
12699    }
12700
12701    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
12702            PackageStats pStats) {
12703        if (packageName == null) {
12704            Slog.w(TAG, "Attempt to get size of null packageName.");
12705            return false;
12706        }
12707        PackageParser.Package p;
12708        boolean dataOnly = false;
12709        String libDirRoot = null;
12710        String asecPath = null;
12711        PackageSetting ps = null;
12712        synchronized (mPackages) {
12713            p = mPackages.get(packageName);
12714            ps = mSettings.mPackages.get(packageName);
12715            if(p == null) {
12716                dataOnly = true;
12717                if((ps == null) || (ps.pkg == null)) {
12718                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12719                    return false;
12720                }
12721                p = ps.pkg;
12722            }
12723            if (ps != null) {
12724                libDirRoot = ps.legacyNativeLibraryPathString;
12725            }
12726            if (p != null && (isExternal(p) || p.isForwardLocked())) {
12727                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
12728                if (secureContainerId != null) {
12729                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
12730                }
12731            }
12732        }
12733        String publicSrcDir = null;
12734        if(!dataOnly) {
12735            final ApplicationInfo applicationInfo = p.applicationInfo;
12736            if (applicationInfo == null) {
12737                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12738                return false;
12739            }
12740            if (p.isForwardLocked()) {
12741                publicSrcDir = applicationInfo.getBaseResourcePath();
12742            }
12743        }
12744        // TODO: extend to measure size of split APKs
12745        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
12746        // not just the first level.
12747        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
12748        // just the primary.
12749        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
12750        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
12751                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
12752        if (res < 0) {
12753            return false;
12754        }
12755
12756        // Fix-up for forward-locked applications in ASEC containers.
12757        if (!isExternal(p)) {
12758            pStats.codeSize += pStats.externalCodeSize;
12759            pStats.externalCodeSize = 0L;
12760        }
12761
12762        return true;
12763    }
12764
12765
12766    @Override
12767    public void addPackageToPreferred(String packageName) {
12768        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
12769    }
12770
12771    @Override
12772    public void removePackageFromPreferred(String packageName) {
12773        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
12774    }
12775
12776    @Override
12777    public List<PackageInfo> getPreferredPackages(int flags) {
12778        return new ArrayList<PackageInfo>();
12779    }
12780
12781    private int getUidTargetSdkVersionLockedLPr(int uid) {
12782        Object obj = mSettings.getUserIdLPr(uid);
12783        if (obj instanceof SharedUserSetting) {
12784            final SharedUserSetting sus = (SharedUserSetting) obj;
12785            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
12786            final Iterator<PackageSetting> it = sus.packages.iterator();
12787            while (it.hasNext()) {
12788                final PackageSetting ps = it.next();
12789                if (ps.pkg != null) {
12790                    int v = ps.pkg.applicationInfo.targetSdkVersion;
12791                    if (v < vers) vers = v;
12792                }
12793            }
12794            return vers;
12795        } else if (obj instanceof PackageSetting) {
12796            final PackageSetting ps = (PackageSetting) obj;
12797            if (ps.pkg != null) {
12798                return ps.pkg.applicationInfo.targetSdkVersion;
12799            }
12800        }
12801        return Build.VERSION_CODES.CUR_DEVELOPMENT;
12802    }
12803
12804    @Override
12805    public void addPreferredActivity(IntentFilter filter, int match,
12806            ComponentName[] set, ComponentName activity, int userId) {
12807        addPreferredActivityInternal(filter, match, set, activity, true, userId,
12808                "Adding preferred");
12809    }
12810
12811    private void addPreferredActivityInternal(IntentFilter filter, int match,
12812            ComponentName[] set, ComponentName activity, boolean always, int userId,
12813            String opname) {
12814        // writer
12815        int callingUid = Binder.getCallingUid();
12816        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
12817        if (filter.countActions() == 0) {
12818            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
12819            return;
12820        }
12821        synchronized (mPackages) {
12822            if (mContext.checkCallingOrSelfPermission(
12823                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12824                    != PackageManager.PERMISSION_GRANTED) {
12825                if (getUidTargetSdkVersionLockedLPr(callingUid)
12826                        < Build.VERSION_CODES.FROYO) {
12827                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
12828                            + callingUid);
12829                    return;
12830                }
12831                mContext.enforceCallingOrSelfPermission(
12832                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12833            }
12834
12835            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
12836            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
12837                    + userId + ":");
12838            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12839            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
12840            scheduleWritePackageRestrictionsLocked(userId);
12841        }
12842    }
12843
12844    @Override
12845    public void replacePreferredActivity(IntentFilter filter, int match,
12846            ComponentName[] set, ComponentName activity, int userId) {
12847        if (filter.countActions() != 1) {
12848            throw new IllegalArgumentException(
12849                    "replacePreferredActivity expects filter to have only 1 action.");
12850        }
12851        if (filter.countDataAuthorities() != 0
12852                || filter.countDataPaths() != 0
12853                || filter.countDataSchemes() > 1
12854                || filter.countDataTypes() != 0) {
12855            throw new IllegalArgumentException(
12856                    "replacePreferredActivity expects filter to have no data authorities, " +
12857                    "paths, or types; and at most one scheme.");
12858        }
12859
12860        final int callingUid = Binder.getCallingUid();
12861        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
12862        synchronized (mPackages) {
12863            if (mContext.checkCallingOrSelfPermission(
12864                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12865                    != PackageManager.PERMISSION_GRANTED) {
12866                if (getUidTargetSdkVersionLockedLPr(callingUid)
12867                        < Build.VERSION_CODES.FROYO) {
12868                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
12869                            + Binder.getCallingUid());
12870                    return;
12871                }
12872                mContext.enforceCallingOrSelfPermission(
12873                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12874            }
12875
12876            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
12877            if (pir != null) {
12878                // Get all of the existing entries that exactly match this filter.
12879                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
12880                if (existing != null && existing.size() == 1) {
12881                    PreferredActivity cur = existing.get(0);
12882                    if (DEBUG_PREFERRED) {
12883                        Slog.i(TAG, "Checking replace of preferred:");
12884                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12885                        if (!cur.mPref.mAlways) {
12886                            Slog.i(TAG, "  -- CUR; not mAlways!");
12887                        } else {
12888                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
12889                            Slog.i(TAG, "  -- CUR: mSet="
12890                                    + Arrays.toString(cur.mPref.mSetComponents));
12891                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
12892                            Slog.i(TAG, "  -- NEW: mMatch="
12893                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
12894                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
12895                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
12896                        }
12897                    }
12898                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
12899                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
12900                            && cur.mPref.sameSet(set)) {
12901                        // Setting the preferred activity to what it happens to be already
12902                        if (DEBUG_PREFERRED) {
12903                            Slog.i(TAG, "Replacing with same preferred activity "
12904                                    + cur.mPref.mShortComponent + " for user "
12905                                    + userId + ":");
12906                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12907                        }
12908                        return;
12909                    }
12910                }
12911
12912                if (existing != null) {
12913                    if (DEBUG_PREFERRED) {
12914                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
12915                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12916                    }
12917                    for (int i = 0; i < existing.size(); i++) {
12918                        PreferredActivity pa = existing.get(i);
12919                        if (DEBUG_PREFERRED) {
12920                            Slog.i(TAG, "Removing existing preferred activity "
12921                                    + pa.mPref.mComponent + ":");
12922                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
12923                        }
12924                        pir.removeFilter(pa);
12925                    }
12926                }
12927            }
12928            addPreferredActivityInternal(filter, match, set, activity, true, userId,
12929                    "Replacing preferred");
12930        }
12931    }
12932
12933    @Override
12934    public void clearPackagePreferredActivities(String packageName) {
12935        final int uid = Binder.getCallingUid();
12936        // writer
12937        synchronized (mPackages) {
12938            PackageParser.Package pkg = mPackages.get(packageName);
12939            if (pkg == null || pkg.applicationInfo.uid != uid) {
12940                if (mContext.checkCallingOrSelfPermission(
12941                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12942                        != PackageManager.PERMISSION_GRANTED) {
12943                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
12944                            < Build.VERSION_CODES.FROYO) {
12945                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
12946                                + Binder.getCallingUid());
12947                        return;
12948                    }
12949                    mContext.enforceCallingOrSelfPermission(
12950                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12951                }
12952            }
12953
12954            int user = UserHandle.getCallingUserId();
12955            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
12956                scheduleWritePackageRestrictionsLocked(user);
12957            }
12958        }
12959    }
12960
12961    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
12962    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
12963        ArrayList<PreferredActivity> removed = null;
12964        boolean changed = false;
12965        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12966            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
12967            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12968            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
12969                continue;
12970            }
12971            Iterator<PreferredActivity> it = pir.filterIterator();
12972            while (it.hasNext()) {
12973                PreferredActivity pa = it.next();
12974                // Mark entry for removal only if it matches the package name
12975                // and the entry is of type "always".
12976                if (packageName == null ||
12977                        (pa.mPref.mComponent.getPackageName().equals(packageName)
12978                                && pa.mPref.mAlways)) {
12979                    if (removed == null) {
12980                        removed = new ArrayList<PreferredActivity>();
12981                    }
12982                    removed.add(pa);
12983                }
12984            }
12985            if (removed != null) {
12986                for (int j=0; j<removed.size(); j++) {
12987                    PreferredActivity pa = removed.get(j);
12988                    pir.removeFilter(pa);
12989                }
12990                changed = true;
12991            }
12992        }
12993        return changed;
12994    }
12995
12996    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
12997    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
12998        if (userId == UserHandle.USER_ALL) {
12999            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13000                    sUserManager.getUserIds())) {
13001                for (int oneUserId : sUserManager.getUserIds()) {
13002                    scheduleWritePackageRestrictionsLocked(oneUserId);
13003                }
13004            }
13005        } else {
13006            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13007                scheduleWritePackageRestrictionsLocked(userId);
13008            }
13009        }
13010    }
13011
13012
13013    void clearDefaultBrowserIfNeeded(String packageName) {
13014        for (int oneUserId : sUserManager.getUserIds()) {
13015            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13016            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13017            if (packageName.equals(defaultBrowserPackageName)) {
13018                setDefaultBrowserPackageName(null, oneUserId);
13019            }
13020        }
13021    }
13022
13023    @Override
13024    public void resetPreferredActivities(int userId) {
13025        /* TODO: Actually use userId. Why is it being passed in? */
13026        mContext.enforceCallingOrSelfPermission(
13027                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13028        // writer
13029        synchronized (mPackages) {
13030            int user = UserHandle.getCallingUserId();
13031            clearPackagePreferredActivitiesLPw(null, user);
13032            mSettings.readDefaultPreferredAppsLPw(this, user);
13033            scheduleWritePackageRestrictionsLocked(user);
13034        }
13035    }
13036
13037    @Override
13038    public int getPreferredActivities(List<IntentFilter> outFilters,
13039            List<ComponentName> outActivities, String packageName) {
13040
13041        int num = 0;
13042        final int userId = UserHandle.getCallingUserId();
13043        // reader
13044        synchronized (mPackages) {
13045            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13046            if (pir != null) {
13047                final Iterator<PreferredActivity> it = pir.filterIterator();
13048                while (it.hasNext()) {
13049                    final PreferredActivity pa = it.next();
13050                    if (packageName == null
13051                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13052                                    && pa.mPref.mAlways)) {
13053                        if (outFilters != null) {
13054                            outFilters.add(new IntentFilter(pa));
13055                        }
13056                        if (outActivities != null) {
13057                            outActivities.add(pa.mPref.mComponent);
13058                        }
13059                    }
13060                }
13061            }
13062        }
13063
13064        return num;
13065    }
13066
13067    @Override
13068    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13069            int userId) {
13070        int callingUid = Binder.getCallingUid();
13071        if (callingUid != Process.SYSTEM_UID) {
13072            throw new SecurityException(
13073                    "addPersistentPreferredActivity can only be run by the system");
13074        }
13075        if (filter.countActions() == 0) {
13076            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13077            return;
13078        }
13079        synchronized (mPackages) {
13080            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13081                    " :");
13082            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13083            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13084                    new PersistentPreferredActivity(filter, activity));
13085            scheduleWritePackageRestrictionsLocked(userId);
13086        }
13087    }
13088
13089    @Override
13090    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13091        int callingUid = Binder.getCallingUid();
13092        if (callingUid != Process.SYSTEM_UID) {
13093            throw new SecurityException(
13094                    "clearPackagePersistentPreferredActivities can only be run by the system");
13095        }
13096        ArrayList<PersistentPreferredActivity> removed = null;
13097        boolean changed = false;
13098        synchronized (mPackages) {
13099            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13100                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13101                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13102                        .valueAt(i);
13103                if (userId != thisUserId) {
13104                    continue;
13105                }
13106                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13107                while (it.hasNext()) {
13108                    PersistentPreferredActivity ppa = it.next();
13109                    // Mark entry for removal only if it matches the package name.
13110                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13111                        if (removed == null) {
13112                            removed = new ArrayList<PersistentPreferredActivity>();
13113                        }
13114                        removed.add(ppa);
13115                    }
13116                }
13117                if (removed != null) {
13118                    for (int j=0; j<removed.size(); j++) {
13119                        PersistentPreferredActivity ppa = removed.get(j);
13120                        ppir.removeFilter(ppa);
13121                    }
13122                    changed = true;
13123                }
13124            }
13125
13126            if (changed) {
13127                scheduleWritePackageRestrictionsLocked(userId);
13128            }
13129        }
13130    }
13131
13132    /**
13133     * Non-Binder method, support for the backup/restore mechanism: write the
13134     * full set of preferred activities in its canonical XML format.  Returns true
13135     * on success; false otherwise.
13136     */
13137    @Override
13138    public byte[] getPreferredActivityBackup(int userId) {
13139        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13140            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13141        }
13142
13143        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13144        try {
13145            final XmlSerializer serializer = new FastXmlSerializer();
13146            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13147            serializer.startDocument(null, true);
13148            serializer.startTag(null, TAG_PREFERRED_BACKUP);
13149
13150            synchronized (mPackages) {
13151                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13152            }
13153
13154            serializer.endTag(null, TAG_PREFERRED_BACKUP);
13155            serializer.endDocument();
13156            serializer.flush();
13157        } catch (Exception e) {
13158            if (DEBUG_BACKUP) {
13159                Slog.e(TAG, "Unable to write preferred activities for backup", e);
13160            }
13161            return null;
13162        }
13163
13164        return dataStream.toByteArray();
13165    }
13166
13167    @Override
13168    public void restorePreferredActivities(byte[] backup, int userId) {
13169        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13170            throw new SecurityException("Only the system may call restorePreferredActivities()");
13171        }
13172
13173        try {
13174            final XmlPullParser parser = Xml.newPullParser();
13175            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13176
13177            int type;
13178            while ((type = parser.next()) != XmlPullParser.START_TAG
13179                    && type != XmlPullParser.END_DOCUMENT) {
13180            }
13181            if (type != XmlPullParser.START_TAG) {
13182                // oops didn't find a start tag?!
13183                if (DEBUG_BACKUP) {
13184                    Slog.e(TAG, "Didn't find start tag during restore");
13185                }
13186                return;
13187            }
13188
13189            // this is supposed to be TAG_PREFERRED_BACKUP
13190            if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) {
13191                if (DEBUG_BACKUP) {
13192                    Slog.e(TAG, "Found unexpected tag " + parser.getName());
13193                }
13194                return;
13195            }
13196
13197            // skip interfering stuff, then we're aligned with the backing implementation
13198            while ((type = parser.next()) == XmlPullParser.TEXT) { }
13199            synchronized (mPackages) {
13200                mSettings.readPreferredActivitiesLPw(parser, userId);
13201            }
13202        } catch (Exception e) {
13203            if (DEBUG_BACKUP) {
13204                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13205            }
13206        }
13207    }
13208
13209    @Override
13210    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
13211            int sourceUserId, int targetUserId, int flags) {
13212        mContext.enforceCallingOrSelfPermission(
13213                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13214        int callingUid = Binder.getCallingUid();
13215        enforceOwnerRights(ownerPackage, callingUid);
13216        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13217        if (intentFilter.countActions() == 0) {
13218            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
13219            return;
13220        }
13221        synchronized (mPackages) {
13222            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
13223                    ownerPackage, targetUserId, flags);
13224            CrossProfileIntentResolver resolver =
13225                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13226            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
13227            // We have all those whose filter is equal. Now checking if the rest is equal as well.
13228            if (existing != null) {
13229                int size = existing.size();
13230                for (int i = 0; i < size; i++) {
13231                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
13232                        return;
13233                    }
13234                }
13235            }
13236            resolver.addFilter(newFilter);
13237            scheduleWritePackageRestrictionsLocked(sourceUserId);
13238        }
13239    }
13240
13241    @Override
13242    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
13243        mContext.enforceCallingOrSelfPermission(
13244                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13245        int callingUid = Binder.getCallingUid();
13246        enforceOwnerRights(ownerPackage, callingUid);
13247        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13248        synchronized (mPackages) {
13249            CrossProfileIntentResolver resolver =
13250                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13251            ArraySet<CrossProfileIntentFilter> set =
13252                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
13253            for (CrossProfileIntentFilter filter : set) {
13254                if (filter.getOwnerPackage().equals(ownerPackage)) {
13255                    resolver.removeFilter(filter);
13256                }
13257            }
13258            scheduleWritePackageRestrictionsLocked(sourceUserId);
13259        }
13260    }
13261
13262    // Enforcing that callingUid is owning pkg on userId
13263    private void enforceOwnerRights(String pkg, int callingUid) {
13264        // The system owns everything.
13265        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
13266            return;
13267        }
13268        int callingUserId = UserHandle.getUserId(callingUid);
13269        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
13270        if (pi == null) {
13271            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
13272                    + callingUserId);
13273        }
13274        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
13275            throw new SecurityException("Calling uid " + callingUid
13276                    + " does not own package " + pkg);
13277        }
13278    }
13279
13280    @Override
13281    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
13282        Intent intent = new Intent(Intent.ACTION_MAIN);
13283        intent.addCategory(Intent.CATEGORY_HOME);
13284
13285        final int callingUserId = UserHandle.getCallingUserId();
13286        List<ResolveInfo> list = queryIntentActivities(intent, null,
13287                PackageManager.GET_META_DATA, callingUserId);
13288        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
13289                true, false, false, callingUserId);
13290
13291        allHomeCandidates.clear();
13292        if (list != null) {
13293            for (ResolveInfo ri : list) {
13294                allHomeCandidates.add(ri);
13295            }
13296        }
13297        return (preferred == null || preferred.activityInfo == null)
13298                ? null
13299                : new ComponentName(preferred.activityInfo.packageName,
13300                        preferred.activityInfo.name);
13301    }
13302
13303    @Override
13304    public void setApplicationEnabledSetting(String appPackageName,
13305            int newState, int flags, int userId, String callingPackage) {
13306        if (!sUserManager.exists(userId)) return;
13307        if (callingPackage == null) {
13308            callingPackage = Integer.toString(Binder.getCallingUid());
13309        }
13310        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
13311    }
13312
13313    @Override
13314    public void setComponentEnabledSetting(ComponentName componentName,
13315            int newState, int flags, int userId) {
13316        if (!sUserManager.exists(userId)) return;
13317        setEnabledSetting(componentName.getPackageName(),
13318                componentName.getClassName(), newState, flags, userId, null);
13319    }
13320
13321    private void setEnabledSetting(final String packageName, String className, int newState,
13322            final int flags, int userId, String callingPackage) {
13323        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
13324              || newState == COMPONENT_ENABLED_STATE_ENABLED
13325              || newState == COMPONENT_ENABLED_STATE_DISABLED
13326              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
13327              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
13328            throw new IllegalArgumentException("Invalid new component state: "
13329                    + newState);
13330        }
13331        PackageSetting pkgSetting;
13332        final int uid = Binder.getCallingUid();
13333        final int permission = mContext.checkCallingOrSelfPermission(
13334                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13335        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
13336        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13337        boolean sendNow = false;
13338        boolean isApp = (className == null);
13339        String componentName = isApp ? packageName : className;
13340        int packageUid = -1;
13341        ArrayList<String> components;
13342
13343        // writer
13344        synchronized (mPackages) {
13345            pkgSetting = mSettings.mPackages.get(packageName);
13346            if (pkgSetting == null) {
13347                if (className == null) {
13348                    throw new IllegalArgumentException(
13349                            "Unknown package: " + packageName);
13350                }
13351                throw new IllegalArgumentException(
13352                        "Unknown component: " + packageName
13353                        + "/" + className);
13354            }
13355            // Allow root and verify that userId is not being specified by a different user
13356            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
13357                throw new SecurityException(
13358                        "Permission Denial: attempt to change component state from pid="
13359                        + Binder.getCallingPid()
13360                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
13361            }
13362            if (className == null) {
13363                // We're dealing with an application/package level state change
13364                if (pkgSetting.getEnabled(userId) == newState) {
13365                    // Nothing to do
13366                    return;
13367                }
13368                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
13369                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
13370                    // Don't care about who enables an app.
13371                    callingPackage = null;
13372                }
13373                pkgSetting.setEnabled(newState, userId, callingPackage);
13374                // pkgSetting.pkg.mSetEnabled = newState;
13375            } else {
13376                // We're dealing with a component level state change
13377                // First, verify that this is a valid class name.
13378                PackageParser.Package pkg = pkgSetting.pkg;
13379                if (pkg == null || !pkg.hasComponentClassName(className)) {
13380                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
13381                        throw new IllegalArgumentException("Component class " + className
13382                                + " does not exist in " + packageName);
13383                    } else {
13384                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
13385                                + className + " does not exist in " + packageName);
13386                    }
13387                }
13388                switch (newState) {
13389                case COMPONENT_ENABLED_STATE_ENABLED:
13390                    if (!pkgSetting.enableComponentLPw(className, userId)) {
13391                        return;
13392                    }
13393                    break;
13394                case COMPONENT_ENABLED_STATE_DISABLED:
13395                    if (!pkgSetting.disableComponentLPw(className, userId)) {
13396                        return;
13397                    }
13398                    break;
13399                case COMPONENT_ENABLED_STATE_DEFAULT:
13400                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
13401                        return;
13402                    }
13403                    break;
13404                default:
13405                    Slog.e(TAG, "Invalid new component state: " + newState);
13406                    return;
13407                }
13408            }
13409            scheduleWritePackageRestrictionsLocked(userId);
13410            components = mPendingBroadcasts.get(userId, packageName);
13411            final boolean newPackage = components == null;
13412            if (newPackage) {
13413                components = new ArrayList<String>();
13414            }
13415            if (!components.contains(componentName)) {
13416                components.add(componentName);
13417            }
13418            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
13419                sendNow = true;
13420                // Purge entry from pending broadcast list if another one exists already
13421                // since we are sending one right away.
13422                mPendingBroadcasts.remove(userId, packageName);
13423            } else {
13424                if (newPackage) {
13425                    mPendingBroadcasts.put(userId, packageName, components);
13426                }
13427                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
13428                    // Schedule a message
13429                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
13430                }
13431            }
13432        }
13433
13434        long callingId = Binder.clearCallingIdentity();
13435        try {
13436            if (sendNow) {
13437                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
13438                sendPackageChangedBroadcast(packageName,
13439                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
13440            }
13441        } finally {
13442            Binder.restoreCallingIdentity(callingId);
13443        }
13444    }
13445
13446    private void sendPackageChangedBroadcast(String packageName,
13447            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
13448        if (DEBUG_INSTALL)
13449            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
13450                    + componentNames);
13451        Bundle extras = new Bundle(4);
13452        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
13453        String nameList[] = new String[componentNames.size()];
13454        componentNames.toArray(nameList);
13455        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
13456        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
13457        extras.putInt(Intent.EXTRA_UID, packageUid);
13458        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
13459                new int[] {UserHandle.getUserId(packageUid)});
13460    }
13461
13462    @Override
13463    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
13464        if (!sUserManager.exists(userId)) return;
13465        final int uid = Binder.getCallingUid();
13466        final int permission = mContext.checkCallingOrSelfPermission(
13467                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13468        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13469        enforceCrossUserPermission(uid, userId, true, true, "stop package");
13470        // writer
13471        synchronized (mPackages) {
13472            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
13473                    allowedByPermission, uid, userId)) {
13474                scheduleWritePackageRestrictionsLocked(userId);
13475            }
13476        }
13477    }
13478
13479    @Override
13480    public String getInstallerPackageName(String packageName) {
13481        // reader
13482        synchronized (mPackages) {
13483            return mSettings.getInstallerPackageNameLPr(packageName);
13484        }
13485    }
13486
13487    @Override
13488    public int getApplicationEnabledSetting(String packageName, int userId) {
13489        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13490        int uid = Binder.getCallingUid();
13491        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
13492        // reader
13493        synchronized (mPackages) {
13494            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
13495        }
13496    }
13497
13498    @Override
13499    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
13500        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13501        int uid = Binder.getCallingUid();
13502        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
13503        // reader
13504        synchronized (mPackages) {
13505            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
13506        }
13507    }
13508
13509    @Override
13510    public void enterSafeMode() {
13511        enforceSystemOrRoot("Only the system can request entering safe mode");
13512
13513        if (!mSystemReady) {
13514            mSafeMode = true;
13515        }
13516    }
13517
13518    @Override
13519    public void systemReady() {
13520        mSystemReady = true;
13521
13522        // Read the compatibilty setting when the system is ready.
13523        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
13524                mContext.getContentResolver(),
13525                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
13526        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
13527        if (DEBUG_SETTINGS) {
13528            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
13529        }
13530
13531        synchronized (mPackages) {
13532            // Verify that all of the preferred activity components actually
13533            // exist.  It is possible for applications to be updated and at
13534            // that point remove a previously declared activity component that
13535            // had been set as a preferred activity.  We try to clean this up
13536            // the next time we encounter that preferred activity, but it is
13537            // possible for the user flow to never be able to return to that
13538            // situation so here we do a sanity check to make sure we haven't
13539            // left any junk around.
13540            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
13541            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13542                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13543                removed.clear();
13544                for (PreferredActivity pa : pir.filterSet()) {
13545                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
13546                        removed.add(pa);
13547                    }
13548                }
13549                if (removed.size() > 0) {
13550                    for (int r=0; r<removed.size(); r++) {
13551                        PreferredActivity pa = removed.get(r);
13552                        Slog.w(TAG, "Removing dangling preferred activity: "
13553                                + pa.mPref.mComponent);
13554                        pir.removeFilter(pa);
13555                    }
13556                    mSettings.writePackageRestrictionsLPr(
13557                            mSettings.mPreferredActivities.keyAt(i));
13558                }
13559            }
13560        }
13561        sUserManager.systemReady();
13562
13563        // Kick off any messages waiting for system ready
13564        if (mPostSystemReadyMessages != null) {
13565            for (Message msg : mPostSystemReadyMessages) {
13566                msg.sendToTarget();
13567            }
13568            mPostSystemReadyMessages = null;
13569        }
13570
13571        // Watch for external volumes that come and go over time
13572        final StorageManager storage = mContext.getSystemService(StorageManager.class);
13573        storage.registerListener(mStorageListener);
13574
13575        mInstallerService.systemReady();
13576        mPackageDexOptimizer.systemReady();
13577    }
13578
13579    @Override
13580    public boolean isSafeMode() {
13581        return mSafeMode;
13582    }
13583
13584    @Override
13585    public boolean hasSystemUidErrors() {
13586        return mHasSystemUidErrors;
13587    }
13588
13589    static String arrayToString(int[] array) {
13590        StringBuffer buf = new StringBuffer(128);
13591        buf.append('[');
13592        if (array != null) {
13593            for (int i=0; i<array.length; i++) {
13594                if (i > 0) buf.append(", ");
13595                buf.append(array[i]);
13596            }
13597        }
13598        buf.append(']');
13599        return buf.toString();
13600    }
13601
13602    static class DumpState {
13603        public static final int DUMP_LIBS = 1 << 0;
13604        public static final int DUMP_FEATURES = 1 << 1;
13605        public static final int DUMP_RESOLVERS = 1 << 2;
13606        public static final int DUMP_PERMISSIONS = 1 << 3;
13607        public static final int DUMP_PACKAGES = 1 << 4;
13608        public static final int DUMP_SHARED_USERS = 1 << 5;
13609        public static final int DUMP_MESSAGES = 1 << 6;
13610        public static final int DUMP_PROVIDERS = 1 << 7;
13611        public static final int DUMP_VERIFIERS = 1 << 8;
13612        public static final int DUMP_PREFERRED = 1 << 9;
13613        public static final int DUMP_PREFERRED_XML = 1 << 10;
13614        public static final int DUMP_KEYSETS = 1 << 11;
13615        public static final int DUMP_VERSION = 1 << 12;
13616        public static final int DUMP_INSTALLS = 1 << 13;
13617        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
13618        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
13619
13620        public static final int OPTION_SHOW_FILTERS = 1 << 0;
13621
13622        private int mTypes;
13623
13624        private int mOptions;
13625
13626        private boolean mTitlePrinted;
13627
13628        private SharedUserSetting mSharedUser;
13629
13630        public boolean isDumping(int type) {
13631            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
13632                return true;
13633            }
13634
13635            return (mTypes & type) != 0;
13636        }
13637
13638        public void setDump(int type) {
13639            mTypes |= type;
13640        }
13641
13642        public boolean isOptionEnabled(int option) {
13643            return (mOptions & option) != 0;
13644        }
13645
13646        public void setOptionEnabled(int option) {
13647            mOptions |= option;
13648        }
13649
13650        public boolean onTitlePrinted() {
13651            final boolean printed = mTitlePrinted;
13652            mTitlePrinted = true;
13653            return printed;
13654        }
13655
13656        public boolean getTitlePrinted() {
13657            return mTitlePrinted;
13658        }
13659
13660        public void setTitlePrinted(boolean enabled) {
13661            mTitlePrinted = enabled;
13662        }
13663
13664        public SharedUserSetting getSharedUser() {
13665            return mSharedUser;
13666        }
13667
13668        public void setSharedUser(SharedUserSetting user) {
13669            mSharedUser = user;
13670        }
13671    }
13672
13673    @Override
13674    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
13675        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
13676                != PackageManager.PERMISSION_GRANTED) {
13677            pw.println("Permission Denial: can't dump ActivityManager from from pid="
13678                    + Binder.getCallingPid()
13679                    + ", uid=" + Binder.getCallingUid()
13680                    + " without permission "
13681                    + android.Manifest.permission.DUMP);
13682            return;
13683        }
13684
13685        DumpState dumpState = new DumpState();
13686        boolean fullPreferred = false;
13687        boolean checkin = false;
13688
13689        String packageName = null;
13690
13691        int opti = 0;
13692        while (opti < args.length) {
13693            String opt = args[opti];
13694            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
13695                break;
13696            }
13697            opti++;
13698
13699            if ("-a".equals(opt)) {
13700                // Right now we only know how to print all.
13701            } else if ("-h".equals(opt)) {
13702                pw.println("Package manager dump options:");
13703                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
13704                pw.println("    --checkin: dump for a checkin");
13705                pw.println("    -f: print details of intent filters");
13706                pw.println("    -h: print this help");
13707                pw.println("  cmd may be one of:");
13708                pw.println("    l[ibraries]: list known shared libraries");
13709                pw.println("    f[ibraries]: list device features");
13710                pw.println("    k[eysets]: print known keysets");
13711                pw.println("    r[esolvers]: dump intent resolvers");
13712                pw.println("    perm[issions]: dump permissions");
13713                pw.println("    pref[erred]: print preferred package settings");
13714                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
13715                pw.println("    prov[iders]: dump content providers");
13716                pw.println("    p[ackages]: dump installed packages");
13717                pw.println("    s[hared-users]: dump shared user IDs");
13718                pw.println("    m[essages]: print collected runtime messages");
13719                pw.println("    v[erifiers]: print package verifier info");
13720                pw.println("    version: print database version info");
13721                pw.println("    write: write current settings now");
13722                pw.println("    <package.name>: info about given package");
13723                pw.println("    installs: details about install sessions");
13724                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
13725                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
13726                return;
13727            } else if ("--checkin".equals(opt)) {
13728                checkin = true;
13729            } else if ("-f".equals(opt)) {
13730                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
13731            } else {
13732                pw.println("Unknown argument: " + opt + "; use -h for help");
13733            }
13734        }
13735
13736        // Is the caller requesting to dump a particular piece of data?
13737        if (opti < args.length) {
13738            String cmd = args[opti];
13739            opti++;
13740            // Is this a package name?
13741            if ("android".equals(cmd) || cmd.contains(".")) {
13742                packageName = cmd;
13743                // When dumping a single package, we always dump all of its
13744                // filter information since the amount of data will be reasonable.
13745                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
13746            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
13747                dumpState.setDump(DumpState.DUMP_LIBS);
13748            } else if ("f".equals(cmd) || "features".equals(cmd)) {
13749                dumpState.setDump(DumpState.DUMP_FEATURES);
13750            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
13751                dumpState.setDump(DumpState.DUMP_RESOLVERS);
13752            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
13753                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
13754            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
13755                dumpState.setDump(DumpState.DUMP_PREFERRED);
13756            } else if ("preferred-xml".equals(cmd)) {
13757                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
13758                if (opti < args.length && "--full".equals(args[opti])) {
13759                    fullPreferred = true;
13760                    opti++;
13761                }
13762            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
13763                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
13764            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
13765                dumpState.setDump(DumpState.DUMP_PACKAGES);
13766            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
13767                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
13768            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
13769                dumpState.setDump(DumpState.DUMP_PROVIDERS);
13770            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
13771                dumpState.setDump(DumpState.DUMP_MESSAGES);
13772            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
13773                dumpState.setDump(DumpState.DUMP_VERIFIERS);
13774            } else if ("i".equals(cmd) || "ifv".equals(cmd)
13775                    || "intent-filter-verifiers".equals(cmd)) {
13776                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
13777            } else if ("version".equals(cmd)) {
13778                dumpState.setDump(DumpState.DUMP_VERSION);
13779            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
13780                dumpState.setDump(DumpState.DUMP_KEYSETS);
13781            } else if ("installs".equals(cmd)) {
13782                dumpState.setDump(DumpState.DUMP_INSTALLS);
13783            } else if ("write".equals(cmd)) {
13784                synchronized (mPackages) {
13785                    mSettings.writeLPr();
13786                    pw.println("Settings written.");
13787                    return;
13788                }
13789            }
13790        }
13791
13792        if (checkin) {
13793            pw.println("vers,1");
13794        }
13795
13796        // reader
13797        synchronized (mPackages) {
13798            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
13799                if (!checkin) {
13800                    if (dumpState.onTitlePrinted())
13801                        pw.println();
13802                    pw.println("Database versions:");
13803                    pw.print("  SDK Version:");
13804                    pw.print(" internal=");
13805                    pw.print(mSettings.mInternalSdkPlatform);
13806                    pw.print(" external=");
13807                    pw.println(mSettings.mExternalSdkPlatform);
13808                    pw.print("  DB Version:");
13809                    pw.print(" internal=");
13810                    pw.print(mSettings.mInternalDatabaseVersion);
13811                    pw.print(" external=");
13812                    pw.println(mSettings.mExternalDatabaseVersion);
13813                }
13814            }
13815
13816            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
13817                if (!checkin) {
13818                    if (dumpState.onTitlePrinted())
13819                        pw.println();
13820                    pw.println("Verifiers:");
13821                    pw.print("  Required: ");
13822                    pw.print(mRequiredVerifierPackage);
13823                    pw.print(" (uid=");
13824                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
13825                    pw.println(")");
13826                } else if (mRequiredVerifierPackage != null) {
13827                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
13828                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
13829                }
13830            }
13831
13832            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
13833                    packageName == null) {
13834                if (mIntentFilterVerifierComponent != null) {
13835                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
13836                    if (!checkin) {
13837                        if (dumpState.onTitlePrinted())
13838                            pw.println();
13839                        pw.println("Intent Filter Verifier:");
13840                        pw.print("  Using: ");
13841                        pw.print(verifierPackageName);
13842                        pw.print(" (uid=");
13843                        pw.print(getPackageUid(verifierPackageName, 0));
13844                        pw.println(")");
13845                    } else if (verifierPackageName != null) {
13846                        pw.print("ifv,"); pw.print(verifierPackageName);
13847                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
13848                    }
13849                } else {
13850                    pw.println();
13851                    pw.println("No Intent Filter Verifier available!");
13852                }
13853            }
13854
13855            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
13856                boolean printedHeader = false;
13857                final Iterator<String> it = mSharedLibraries.keySet().iterator();
13858                while (it.hasNext()) {
13859                    String name = it.next();
13860                    SharedLibraryEntry ent = mSharedLibraries.get(name);
13861                    if (!checkin) {
13862                        if (!printedHeader) {
13863                            if (dumpState.onTitlePrinted())
13864                                pw.println();
13865                            pw.println("Libraries:");
13866                            printedHeader = true;
13867                        }
13868                        pw.print("  ");
13869                    } else {
13870                        pw.print("lib,");
13871                    }
13872                    pw.print(name);
13873                    if (!checkin) {
13874                        pw.print(" -> ");
13875                    }
13876                    if (ent.path != null) {
13877                        if (!checkin) {
13878                            pw.print("(jar) ");
13879                            pw.print(ent.path);
13880                        } else {
13881                            pw.print(",jar,");
13882                            pw.print(ent.path);
13883                        }
13884                    } else {
13885                        if (!checkin) {
13886                            pw.print("(apk) ");
13887                            pw.print(ent.apk);
13888                        } else {
13889                            pw.print(",apk,");
13890                            pw.print(ent.apk);
13891                        }
13892                    }
13893                    pw.println();
13894                }
13895            }
13896
13897            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
13898                if (dumpState.onTitlePrinted())
13899                    pw.println();
13900                if (!checkin) {
13901                    pw.println("Features:");
13902                }
13903                Iterator<String> it = mAvailableFeatures.keySet().iterator();
13904                while (it.hasNext()) {
13905                    String name = it.next();
13906                    if (!checkin) {
13907                        pw.print("  ");
13908                    } else {
13909                        pw.print("feat,");
13910                    }
13911                    pw.println(name);
13912                }
13913            }
13914
13915            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
13916                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
13917                        : "Activity Resolver Table:", "  ", packageName,
13918                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13919                    dumpState.setTitlePrinted(true);
13920                }
13921                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
13922                        : "Receiver Resolver Table:", "  ", packageName,
13923                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13924                    dumpState.setTitlePrinted(true);
13925                }
13926                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
13927                        : "Service Resolver Table:", "  ", packageName,
13928                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13929                    dumpState.setTitlePrinted(true);
13930                }
13931                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
13932                        : "Provider Resolver Table:", "  ", packageName,
13933                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13934                    dumpState.setTitlePrinted(true);
13935                }
13936            }
13937
13938            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
13939                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13940                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13941                    int user = mSettings.mPreferredActivities.keyAt(i);
13942                    if (pir.dump(pw,
13943                            dumpState.getTitlePrinted()
13944                                ? "\nPreferred Activities User " + user + ":"
13945                                : "Preferred Activities User " + user + ":", "  ",
13946                            packageName, true, false)) {
13947                        dumpState.setTitlePrinted(true);
13948                    }
13949                }
13950            }
13951
13952            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
13953                pw.flush();
13954                FileOutputStream fout = new FileOutputStream(fd);
13955                BufferedOutputStream str = new BufferedOutputStream(fout);
13956                XmlSerializer serializer = new FastXmlSerializer();
13957                try {
13958                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
13959                    serializer.startDocument(null, true);
13960                    serializer.setFeature(
13961                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
13962                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
13963                    serializer.endDocument();
13964                    serializer.flush();
13965                } catch (IllegalArgumentException e) {
13966                    pw.println("Failed writing: " + e);
13967                } catch (IllegalStateException e) {
13968                    pw.println("Failed writing: " + e);
13969                } catch (IOException e) {
13970                    pw.println("Failed writing: " + e);
13971                }
13972            }
13973
13974            if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) {
13975                pw.println();
13976                int count = mSettings.mPackages.size();
13977                if (count == 0) {
13978                    pw.println("No domain preferred apps!");
13979                    pw.println();
13980                } else {
13981                    final String prefix = "  ";
13982                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
13983                    if (allPackageSettings.size() == 0) {
13984                        pw.println("No domain preferred apps!");
13985                        pw.println();
13986                    } else {
13987                        pw.println("Domain preferred apps status:");
13988                        pw.println();
13989                        count = 0;
13990                        for (PackageSetting ps : allPackageSettings) {
13991                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
13992                            if (ivi == null || ivi.getPackageName() == null) continue;
13993                            pw.println(prefix + "Package Name: " + ivi.getPackageName());
13994                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
13995                            pw.println(prefix + "Status: " + ivi.getStatusString());
13996                            pw.println();
13997                            count++;
13998                        }
13999                        if (count == 0) {
14000                            pw.println(prefix + "No domain preferred app status!");
14001                            pw.println();
14002                        }
14003                        for (int userId : sUserManager.getUserIds()) {
14004                            pw.println("Domain preferred apps for User " + userId + ":");
14005                            pw.println();
14006                            count = 0;
14007                            for (PackageSetting ps : allPackageSettings) {
14008                                IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14009                                if (ivi == null || ivi.getPackageName() == null) {
14010                                    continue;
14011                                }
14012                                final int status = ps.getDomainVerificationStatusForUser(userId);
14013                                if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
14014                                    continue;
14015                                }
14016                                pw.println(prefix + "Package Name: " + ivi.getPackageName());
14017                                pw.println(prefix + "Domains: " + ivi.getDomainsString());
14018                                String statusStr = IntentFilterVerificationInfo.
14019                                        getStatusStringFromValue(status);
14020                                pw.println(prefix + "Status: " + statusStr);
14021                                pw.println();
14022                                count++;
14023                            }
14024                            if (count == 0) {
14025                                pw.println(prefix + "No domain preferred apps!");
14026                                pw.println();
14027                            }
14028                        }
14029                    }
14030                }
14031            }
14032
14033            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
14034                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
14035                if (packageName == null) {
14036                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
14037                        if (iperm == 0) {
14038                            if (dumpState.onTitlePrinted())
14039                                pw.println();
14040                            pw.println("AppOp Permissions:");
14041                        }
14042                        pw.print("  AppOp Permission ");
14043                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
14044                        pw.println(":");
14045                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
14046                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
14047                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
14048                        }
14049                    }
14050                }
14051            }
14052
14053            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
14054                boolean printedSomething = false;
14055                for (PackageParser.Provider p : mProviders.mProviders.values()) {
14056                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14057                        continue;
14058                    }
14059                    if (!printedSomething) {
14060                        if (dumpState.onTitlePrinted())
14061                            pw.println();
14062                        pw.println("Registered ContentProviders:");
14063                        printedSomething = true;
14064                    }
14065                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
14066                    pw.print("    "); pw.println(p.toString());
14067                }
14068                printedSomething = false;
14069                for (Map.Entry<String, PackageParser.Provider> entry :
14070                        mProvidersByAuthority.entrySet()) {
14071                    PackageParser.Provider p = entry.getValue();
14072                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14073                        continue;
14074                    }
14075                    if (!printedSomething) {
14076                        if (dumpState.onTitlePrinted())
14077                            pw.println();
14078                        pw.println("ContentProvider Authorities:");
14079                        printedSomething = true;
14080                    }
14081                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
14082                    pw.print("    "); pw.println(p.toString());
14083                    if (p.info != null && p.info.applicationInfo != null) {
14084                        final String appInfo = p.info.applicationInfo.toString();
14085                        pw.print("      applicationInfo="); pw.println(appInfo);
14086                    }
14087                }
14088            }
14089
14090            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
14091                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
14092            }
14093
14094            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
14095                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
14096            }
14097
14098            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
14099                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin);
14100            }
14101
14102            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
14103                // XXX should handle packageName != null by dumping only install data that
14104                // the given package is involved with.
14105                if (dumpState.onTitlePrinted()) pw.println();
14106                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
14107            }
14108
14109            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
14110                if (dumpState.onTitlePrinted()) pw.println();
14111                mSettings.dumpReadMessagesLPr(pw, dumpState);
14112
14113                pw.println();
14114                pw.println("Package warning messages:");
14115                BufferedReader in = null;
14116                String line = null;
14117                try {
14118                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14119                    while ((line = in.readLine()) != null) {
14120                        if (line.contains("ignored: updated version")) continue;
14121                        pw.println(line);
14122                    }
14123                } catch (IOException ignored) {
14124                } finally {
14125                    IoUtils.closeQuietly(in);
14126                }
14127            }
14128
14129            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
14130                BufferedReader in = null;
14131                String line = null;
14132                try {
14133                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14134                    while ((line = in.readLine()) != null) {
14135                        if (line.contains("ignored: updated version")) continue;
14136                        pw.print("msg,");
14137                        pw.println(line);
14138                    }
14139                } catch (IOException ignored) {
14140                } finally {
14141                    IoUtils.closeQuietly(in);
14142                }
14143            }
14144        }
14145    }
14146
14147    // ------- apps on sdcard specific code -------
14148    static final boolean DEBUG_SD_INSTALL = false;
14149
14150    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
14151
14152    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
14153
14154    private boolean mMediaMounted = false;
14155
14156    static String getEncryptKey() {
14157        try {
14158            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
14159                    SD_ENCRYPTION_KEYSTORE_NAME);
14160            if (sdEncKey == null) {
14161                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
14162                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
14163                if (sdEncKey == null) {
14164                    Slog.e(TAG, "Failed to create encryption keys");
14165                    return null;
14166                }
14167            }
14168            return sdEncKey;
14169        } catch (NoSuchAlgorithmException nsae) {
14170            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
14171            return null;
14172        } catch (IOException ioe) {
14173            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
14174            return null;
14175        }
14176    }
14177
14178    /*
14179     * Update media status on PackageManager.
14180     */
14181    @Override
14182    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
14183        int callingUid = Binder.getCallingUid();
14184        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
14185            throw new SecurityException("Media status can only be updated by the system");
14186        }
14187        // reader; this apparently protects mMediaMounted, but should probably
14188        // be a different lock in that case.
14189        synchronized (mPackages) {
14190            Log.i(TAG, "Updating external media status from "
14191                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
14192                    + (mediaStatus ? "mounted" : "unmounted"));
14193            if (DEBUG_SD_INSTALL)
14194                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
14195                        + ", mMediaMounted=" + mMediaMounted);
14196            if (mediaStatus == mMediaMounted) {
14197                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
14198                        : 0, -1);
14199                mHandler.sendMessage(msg);
14200                return;
14201            }
14202            mMediaMounted = mediaStatus;
14203        }
14204        // Queue up an async operation since the package installation may take a
14205        // little while.
14206        mHandler.post(new Runnable() {
14207            public void run() {
14208                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
14209            }
14210        });
14211    }
14212
14213    /**
14214     * Called by MountService when the initial ASECs to scan are available.
14215     * Should block until all the ASEC containers are finished being scanned.
14216     */
14217    public void scanAvailableAsecs() {
14218        updateExternalMediaStatusInner(true, false, false);
14219        if (mShouldRestoreconData) {
14220            SELinuxMMAC.setRestoreconDone();
14221            mShouldRestoreconData = false;
14222        }
14223    }
14224
14225    /*
14226     * Collect information of applications on external media, map them against
14227     * existing containers and update information based on current mount status.
14228     * Please note that we always have to report status if reportStatus has been
14229     * set to true especially when unloading packages.
14230     */
14231    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
14232            boolean externalStorage) {
14233        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
14234        int[] uidArr = EmptyArray.INT;
14235
14236        final String[] list = PackageHelper.getSecureContainerList();
14237        if (ArrayUtils.isEmpty(list)) {
14238            Log.i(TAG, "No secure containers found");
14239        } else {
14240            // Process list of secure containers and categorize them
14241            // as active or stale based on their package internal state.
14242
14243            // reader
14244            synchronized (mPackages) {
14245                for (String cid : list) {
14246                    // Leave stages untouched for now; installer service owns them
14247                    if (PackageInstallerService.isStageName(cid)) continue;
14248
14249                    if (DEBUG_SD_INSTALL)
14250                        Log.i(TAG, "Processing container " + cid);
14251                    String pkgName = getAsecPackageName(cid);
14252                    if (pkgName == null) {
14253                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
14254                        continue;
14255                    }
14256                    if (DEBUG_SD_INSTALL)
14257                        Log.i(TAG, "Looking for pkg : " + pkgName);
14258
14259                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
14260                    if (ps == null) {
14261                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
14262                        continue;
14263                    }
14264
14265                    /*
14266                     * Skip packages that are not external if we're unmounting
14267                     * external storage.
14268                     */
14269                    if (externalStorage && !isMounted && !isExternal(ps)) {
14270                        continue;
14271                    }
14272
14273                    final AsecInstallArgs args = new AsecInstallArgs(cid,
14274                            getAppDexInstructionSets(ps), ps.isForwardLocked());
14275                    // The package status is changed only if the code path
14276                    // matches between settings and the container id.
14277                    if (ps.codePathString != null
14278                            && ps.codePathString.startsWith(args.getCodePath())) {
14279                        if (DEBUG_SD_INSTALL) {
14280                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
14281                                    + " at code path: " + ps.codePathString);
14282                        }
14283
14284                        // We do have a valid package installed on sdcard
14285                        processCids.put(args, ps.codePathString);
14286                        final int uid = ps.appId;
14287                        if (uid != -1) {
14288                            uidArr = ArrayUtils.appendInt(uidArr, uid);
14289                        }
14290                    } else {
14291                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
14292                                + ps.codePathString);
14293                    }
14294                }
14295            }
14296
14297            Arrays.sort(uidArr);
14298        }
14299
14300        // Process packages with valid entries.
14301        if (isMounted) {
14302            if (DEBUG_SD_INSTALL)
14303                Log.i(TAG, "Loading packages");
14304            loadMediaPackages(processCids, uidArr);
14305            startCleaningPackages();
14306            mInstallerService.onSecureContainersAvailable();
14307        } else {
14308            if (DEBUG_SD_INSTALL)
14309                Log.i(TAG, "Unloading packages");
14310            unloadMediaPackages(processCids, uidArr, reportStatus);
14311        }
14312    }
14313
14314    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14315            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
14316        final int size = infos.size();
14317        final String[] packageNames = new String[size];
14318        final int[] packageUids = new int[size];
14319        for (int i = 0; i < size; i++) {
14320            final ApplicationInfo info = infos.get(i);
14321            packageNames[i] = info.packageName;
14322            packageUids[i] = info.uid;
14323        }
14324        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
14325                finishedReceiver);
14326    }
14327
14328    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14329            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14330        sendResourcesChangedBroadcast(mediaStatus, replacing,
14331                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
14332    }
14333
14334    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14335            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14336        int size = pkgList.length;
14337        if (size > 0) {
14338            // Send broadcasts here
14339            Bundle extras = new Bundle();
14340            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14341            if (uidArr != null) {
14342                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
14343            }
14344            if (replacing) {
14345                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
14346            }
14347            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
14348                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
14349            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
14350        }
14351    }
14352
14353   /*
14354     * Look at potentially valid container ids from processCids If package
14355     * information doesn't match the one on record or package scanning fails,
14356     * the cid is added to list of removeCids. We currently don't delete stale
14357     * containers.
14358     */
14359    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
14360        ArrayList<String> pkgList = new ArrayList<String>();
14361        Set<AsecInstallArgs> keys = processCids.keySet();
14362
14363        for (AsecInstallArgs args : keys) {
14364            String codePath = processCids.get(args);
14365            if (DEBUG_SD_INSTALL)
14366                Log.i(TAG, "Loading container : " + args.cid);
14367            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14368            try {
14369                // Make sure there are no container errors first.
14370                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
14371                    Slog.e(TAG, "Failed to mount cid : " + args.cid
14372                            + " when installing from sdcard");
14373                    continue;
14374                }
14375                // Check code path here.
14376                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
14377                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
14378                            + " does not match one in settings " + codePath);
14379                    continue;
14380                }
14381                // Parse package
14382                int parseFlags = mDefParseFlags;
14383                if (args.isExternalAsec()) {
14384                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
14385                }
14386                if (args.isFwdLocked()) {
14387                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
14388                }
14389
14390                synchronized (mInstallLock) {
14391                    PackageParser.Package pkg = null;
14392                    try {
14393                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
14394                    } catch (PackageManagerException e) {
14395                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
14396                    }
14397                    // Scan the package
14398                    if (pkg != null) {
14399                        /*
14400                         * TODO why is the lock being held? doPostInstall is
14401                         * called in other places without the lock. This needs
14402                         * to be straightened out.
14403                         */
14404                        // writer
14405                        synchronized (mPackages) {
14406                            retCode = PackageManager.INSTALL_SUCCEEDED;
14407                            pkgList.add(pkg.packageName);
14408                            // Post process args
14409                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
14410                                    pkg.applicationInfo.uid);
14411                        }
14412                    } else {
14413                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
14414                    }
14415                }
14416
14417            } finally {
14418                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
14419                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
14420                }
14421            }
14422        }
14423        // writer
14424        synchronized (mPackages) {
14425            // If the platform SDK has changed since the last time we booted,
14426            // we need to re-grant app permission to catch any new ones that
14427            // appear. This is really a hack, and means that apps can in some
14428            // cases get permissions that the user didn't initially explicitly
14429            // allow... it would be nice to have some better way to handle
14430            // this situation.
14431            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
14432            if (regrantPermissions)
14433                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
14434                        + mSdkVersion + "; regranting permissions for external storage");
14435            mSettings.mExternalSdkPlatform = mSdkVersion;
14436
14437            // Make sure group IDs have been assigned, and any permission
14438            // changes in other apps are accounted for
14439            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
14440                    | (regrantPermissions
14441                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
14442                            : 0));
14443
14444            mSettings.updateExternalDatabaseVersion();
14445
14446            // can downgrade to reader
14447            // Persist settings
14448            mSettings.writeLPr();
14449        }
14450        // Send a broadcast to let everyone know we are done processing
14451        if (pkgList.size() > 0) {
14452            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
14453        }
14454    }
14455
14456   /*
14457     * Utility method to unload a list of specified containers
14458     */
14459    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
14460        // Just unmount all valid containers.
14461        for (AsecInstallArgs arg : cidArgs) {
14462            synchronized (mInstallLock) {
14463                arg.doPostDeleteLI(false);
14464           }
14465       }
14466   }
14467
14468    /*
14469     * Unload packages mounted on external media. This involves deleting package
14470     * data from internal structures, sending broadcasts about diabled packages,
14471     * gc'ing to free up references, unmounting all secure containers
14472     * corresponding to packages on external media, and posting a
14473     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
14474     * that we always have to post this message if status has been requested no
14475     * matter what.
14476     */
14477    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
14478            final boolean reportStatus) {
14479        if (DEBUG_SD_INSTALL)
14480            Log.i(TAG, "unloading media packages");
14481        ArrayList<String> pkgList = new ArrayList<String>();
14482        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
14483        final Set<AsecInstallArgs> keys = processCids.keySet();
14484        for (AsecInstallArgs args : keys) {
14485            String pkgName = args.getPackageName();
14486            if (DEBUG_SD_INSTALL)
14487                Log.i(TAG, "Trying to unload pkg : " + pkgName);
14488            // Delete package internally
14489            PackageRemovedInfo outInfo = new PackageRemovedInfo();
14490            synchronized (mInstallLock) {
14491                boolean res = deletePackageLI(pkgName, null, false, null, null,
14492                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
14493                if (res) {
14494                    pkgList.add(pkgName);
14495                } else {
14496                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
14497                    failedList.add(args);
14498                }
14499            }
14500        }
14501
14502        // reader
14503        synchronized (mPackages) {
14504            // We didn't update the settings after removing each package;
14505            // write them now for all packages.
14506            mSettings.writeLPr();
14507        }
14508
14509        // We have to absolutely send UPDATED_MEDIA_STATUS only
14510        // after confirming that all the receivers processed the ordered
14511        // broadcast when packages get disabled, force a gc to clean things up.
14512        // and unload all the containers.
14513        if (pkgList.size() > 0) {
14514            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
14515                    new IIntentReceiver.Stub() {
14516                public void performReceive(Intent intent, int resultCode, String data,
14517                        Bundle extras, boolean ordered, boolean sticky,
14518                        int sendingUser) throws RemoteException {
14519                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
14520                            reportStatus ? 1 : 0, 1, keys);
14521                    mHandler.sendMessage(msg);
14522                }
14523            });
14524        } else {
14525            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
14526                    keys);
14527            mHandler.sendMessage(msg);
14528        }
14529    }
14530
14531    private void loadPrivatePackages(VolumeInfo vol) {
14532        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
14533        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
14534        synchronized (mInstallLock) {
14535        synchronized (mPackages) {
14536            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14537            for (PackageSetting ps : packages) {
14538                final PackageParser.Package pkg;
14539                try {
14540                    pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null);
14541                    loaded.add(pkg.applicationInfo);
14542                } catch (PackageManagerException e) {
14543                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
14544                }
14545            }
14546
14547            // TODO: regrant any permissions that changed based since original install
14548
14549            mSettings.writeLPr();
14550        }
14551        }
14552
14553        Slog.d(TAG, "Loaded packages " + loaded);
14554        sendResourcesChangedBroadcast(true, false, loaded, null);
14555    }
14556
14557    private void unloadPrivatePackages(VolumeInfo vol) {
14558        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
14559        synchronized (mInstallLock) {
14560        synchronized (mPackages) {
14561            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14562            for (PackageSetting ps : packages) {
14563                if (ps.pkg == null) continue;
14564
14565                final ApplicationInfo info = ps.pkg.applicationInfo;
14566                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
14567                if (deletePackageLI(ps.name, null, false, null, null,
14568                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
14569                    unloaded.add(info);
14570                } else {
14571                    Slog.w(TAG, "Failed to unload " + ps.codePath);
14572                }
14573            }
14574
14575            mSettings.writeLPr();
14576        }
14577        }
14578
14579        Slog.d(TAG, "Unloaded packages " + unloaded);
14580        sendResourcesChangedBroadcast(false, false, unloaded, null);
14581    }
14582
14583    private void unfreezePackage(String packageName) {
14584        synchronized (mPackages) {
14585            final PackageSetting ps = mSettings.mPackages.get(packageName);
14586            if (ps != null) {
14587                ps.frozen = false;
14588            }
14589        }
14590    }
14591
14592    @Override
14593    public int movePackage(final String packageName, final String volumeUuid) {
14594        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
14595
14596        final int moveId = mNextMoveId.getAndIncrement();
14597        try {
14598            movePackageInternal(packageName, volumeUuid, moveId);
14599        } catch (PackageManagerException e) {
14600            Slog.d(TAG, "Failed to move " + packageName, e);
14601            mMoveCallbacks.notifyStatusChanged(moveId,
14602                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
14603        }
14604        return moveId;
14605    }
14606
14607    private void movePackageInternal(final String packageName, final String volumeUuid,
14608            final int moveId) throws PackageManagerException {
14609        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
14610        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14611        final PackageManager pm = mContext.getPackageManager();
14612
14613        final boolean currentAsec;
14614        final String currentVolumeUuid;
14615        final File codeFile;
14616        final String installerPackageName;
14617        final String packageAbiOverride;
14618        final int appId;
14619        final String seinfo;
14620        final String label;
14621
14622        // reader
14623        synchronized (mPackages) {
14624            final PackageParser.Package pkg = mPackages.get(packageName);
14625            final PackageSetting ps = mSettings.mPackages.get(packageName);
14626            if (pkg == null || ps == null) {
14627                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
14628            }
14629
14630            if (pkg.applicationInfo.isSystemApp()) {
14631                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
14632                        "Cannot move system application");
14633            }
14634
14635            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
14636                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14637                        "Package already moved to " + volumeUuid);
14638            }
14639
14640            final File probe = new File(pkg.codePath);
14641            final File probeOat = new File(probe, "oat");
14642            if (!probe.isDirectory() || !probeOat.isDirectory()) {
14643                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14644                        "Move only supported for modern cluster style installs");
14645            }
14646
14647            if (ps.frozen) {
14648                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
14649                        "Failed to move already frozen package");
14650            }
14651            ps.frozen = true;
14652
14653            currentAsec = pkg.applicationInfo.isForwardLocked()
14654                    || pkg.applicationInfo.isExternalAsec();
14655            currentVolumeUuid = ps.volumeUuid;
14656            codeFile = new File(pkg.codePath);
14657            installerPackageName = ps.installerPackageName;
14658            packageAbiOverride = ps.cpuAbiOverrideString;
14659            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
14660            seinfo = pkg.applicationInfo.seinfo;
14661            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
14662        }
14663
14664        // Now that we're guarded by frozen state, kill app during move
14665        killApplication(packageName, appId, "move pkg");
14666
14667        final Bundle extras = new Bundle();
14668        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
14669        extras.putString(Intent.EXTRA_TITLE, label);
14670        mMoveCallbacks.notifyCreated(moveId, extras);
14671
14672        int installFlags;
14673        final boolean moveCompleteApp;
14674        final File measurePath;
14675
14676        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
14677            installFlags = INSTALL_INTERNAL;
14678            moveCompleteApp = !currentAsec;
14679            measurePath = Environment.getDataAppDirectory(volumeUuid);
14680        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
14681            installFlags = INSTALL_EXTERNAL;
14682            moveCompleteApp = false;
14683            measurePath = storage.getPrimaryPhysicalVolume().getPath();
14684        } else {
14685            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
14686            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
14687                    || !volume.isMountedWritable()) {
14688                unfreezePackage(packageName);
14689                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14690                        "Move location not mounted private volume");
14691            }
14692
14693            Preconditions.checkState(!currentAsec);
14694
14695            installFlags = INSTALL_INTERNAL;
14696            moveCompleteApp = true;
14697            measurePath = Environment.getDataAppDirectory(volumeUuid);
14698        }
14699
14700        final PackageStats stats = new PackageStats(null, -1);
14701        synchronized (mInstaller) {
14702            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
14703                unfreezePackage(packageName);
14704                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14705                        "Failed to measure package size");
14706            }
14707        }
14708
14709        Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " + stats.dataSize);
14710
14711        final long startFreeBytes = measurePath.getFreeSpace();
14712        final long sizeBytes;
14713        if (moveCompleteApp) {
14714            sizeBytes = stats.codeSize + stats.dataSize;
14715        } else {
14716            sizeBytes = stats.codeSize;
14717        }
14718
14719        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
14720            unfreezePackage(packageName);
14721            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14722                    "Not enough free space to move");
14723        }
14724
14725        mMoveCallbacks.notifyStatusChanged(moveId, 10);
14726
14727        final CountDownLatch installedLatch = new CountDownLatch(1);
14728        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
14729            @Override
14730            public void onUserActionRequired(Intent intent) throws RemoteException {
14731                throw new IllegalStateException();
14732            }
14733
14734            @Override
14735            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
14736                    Bundle extras) throws RemoteException {
14737                Slog.d(TAG, "Install result for move: "
14738                        + PackageManager.installStatusToString(returnCode, msg));
14739
14740                installedLatch.countDown();
14741
14742                // Regardless of success or failure of the move operation,
14743                // always unfreeze the package
14744                unfreezePackage(packageName);
14745
14746                final int status = PackageManager.installStatusToPublicStatus(returnCode);
14747                switch (status) {
14748                    case PackageInstaller.STATUS_SUCCESS:
14749                        mMoveCallbacks.notifyStatusChanged(moveId,
14750                                PackageManager.MOVE_SUCCEEDED);
14751                        break;
14752                    case PackageInstaller.STATUS_FAILURE_STORAGE:
14753                        mMoveCallbacks.notifyStatusChanged(moveId,
14754                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
14755                        break;
14756                    default:
14757                        mMoveCallbacks.notifyStatusChanged(moveId,
14758                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
14759                        break;
14760                }
14761            }
14762        };
14763
14764        final MoveInfo move;
14765        if (moveCompleteApp) {
14766            // Kick off a thread to report progress estimates
14767            new Thread() {
14768                @Override
14769                public void run() {
14770                    while (true) {
14771                        try {
14772                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
14773                                break;
14774                            }
14775                        } catch (InterruptedException ignored) {
14776                        }
14777
14778                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
14779                        final int progress = 10 + (int) MathUtils.constrain(
14780                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
14781                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
14782                    }
14783                }
14784            }.start();
14785
14786            final String dataAppName = codeFile.getName();
14787            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
14788                    dataAppName, appId, seinfo);
14789        } else {
14790            move = null;
14791        }
14792
14793        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
14794
14795        final Message msg = mHandler.obtainMessage(INIT_COPY);
14796        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
14797        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
14798                installerPackageName, volumeUuid, null, user, packageAbiOverride);
14799        mHandler.sendMessage(msg);
14800    }
14801
14802    @Override
14803    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
14804        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
14805
14806        final int realMoveId = mNextMoveId.getAndIncrement();
14807        final Bundle extras = new Bundle();
14808        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
14809        mMoveCallbacks.notifyCreated(realMoveId, extras);
14810
14811        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
14812            @Override
14813            public void onCreated(int moveId, Bundle extras) {
14814                // Ignored
14815            }
14816
14817            @Override
14818            public void onStatusChanged(int moveId, int status, long estMillis) {
14819                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
14820            }
14821        };
14822
14823        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14824        storage.setPrimaryStorageUuid(volumeUuid, callback);
14825        return realMoveId;
14826    }
14827
14828    @Override
14829    public int getMoveStatus(int moveId) {
14830        mContext.enforceCallingOrSelfPermission(
14831                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
14832        return mMoveCallbacks.mLastStatus.get(moveId);
14833    }
14834
14835    @Override
14836    public void registerMoveCallback(IPackageMoveObserver callback) {
14837        mContext.enforceCallingOrSelfPermission(
14838                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
14839        mMoveCallbacks.register(callback);
14840    }
14841
14842    @Override
14843    public void unregisterMoveCallback(IPackageMoveObserver callback) {
14844        mContext.enforceCallingOrSelfPermission(
14845                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
14846        mMoveCallbacks.unregister(callback);
14847    }
14848
14849    @Override
14850    public boolean setInstallLocation(int loc) {
14851        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
14852                null);
14853        if (getInstallLocation() == loc) {
14854            return true;
14855        }
14856        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
14857                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
14858            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
14859                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
14860            return true;
14861        }
14862        return false;
14863   }
14864
14865    @Override
14866    public int getInstallLocation() {
14867        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14868                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
14869                PackageHelper.APP_INSTALL_AUTO);
14870    }
14871
14872    /** Called by UserManagerService */
14873    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
14874        mDirtyUsers.remove(userHandle);
14875        mSettings.removeUserLPw(userHandle);
14876        mPendingBroadcasts.remove(userHandle);
14877        if (mInstaller != null) {
14878            // Technically, we shouldn't be doing this with the package lock
14879            // held.  However, this is very rare, and there is already so much
14880            // other disk I/O going on, that we'll let it slide for now.
14881            final StorageManager storage = StorageManager.from(mContext);
14882            final List<VolumeInfo> vols = storage.getVolumes();
14883            for (VolumeInfo vol : vols) {
14884                if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) {
14885                    final String volumeUuid = vol.getFsUuid();
14886                    Slog.d(TAG, "Removing user data on volume " + volumeUuid);
14887                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
14888                }
14889            }
14890        }
14891        mUserNeedsBadging.delete(userHandle);
14892        removeUnusedPackagesLILPw(userManager, userHandle);
14893    }
14894
14895    /**
14896     * We're removing userHandle and would like to remove any downloaded packages
14897     * that are no longer in use by any other user.
14898     * @param userHandle the user being removed
14899     */
14900    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
14901        final boolean DEBUG_CLEAN_APKS = false;
14902        int [] users = userManager.getUserIdsLPr();
14903        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
14904        while (psit.hasNext()) {
14905            PackageSetting ps = psit.next();
14906            if (ps.pkg == null) {
14907                continue;
14908            }
14909            final String packageName = ps.pkg.packageName;
14910            // Skip over if system app
14911            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14912                continue;
14913            }
14914            if (DEBUG_CLEAN_APKS) {
14915                Slog.i(TAG, "Checking package " + packageName);
14916            }
14917            boolean keep = false;
14918            for (int i = 0; i < users.length; i++) {
14919                if (users[i] != userHandle && ps.getInstalled(users[i])) {
14920                    keep = true;
14921                    if (DEBUG_CLEAN_APKS) {
14922                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
14923                                + users[i]);
14924                    }
14925                    break;
14926                }
14927            }
14928            if (!keep) {
14929                if (DEBUG_CLEAN_APKS) {
14930                    Slog.i(TAG, "  Removing package " + packageName);
14931                }
14932                mHandler.post(new Runnable() {
14933                    public void run() {
14934                        deletePackageX(packageName, userHandle, 0);
14935                    } //end run
14936                });
14937            }
14938        }
14939    }
14940
14941    /** Called by UserManagerService */
14942    void createNewUserLILPw(int userHandle, File path) {
14943        if (mInstaller != null) {
14944            mInstaller.createUserConfig(userHandle);
14945            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
14946        }
14947    }
14948
14949    void newUserCreatedLILPw(int userHandle) {
14950        // Adding a user requires updating runtime permissions for system apps.
14951        updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
14952    }
14953
14954    @Override
14955    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
14956        mContext.enforceCallingOrSelfPermission(
14957                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14958                "Only package verification agents can read the verifier device identity");
14959
14960        synchronized (mPackages) {
14961            return mSettings.getVerifierDeviceIdentityLPw();
14962        }
14963    }
14964
14965    @Override
14966    public void setPermissionEnforced(String permission, boolean enforced) {
14967        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
14968        if (READ_EXTERNAL_STORAGE.equals(permission)) {
14969            synchronized (mPackages) {
14970                if (mSettings.mReadExternalStorageEnforced == null
14971                        || mSettings.mReadExternalStorageEnforced != enforced) {
14972                    mSettings.mReadExternalStorageEnforced = enforced;
14973                    mSettings.writeLPr();
14974                }
14975            }
14976            // kill any non-foreground processes so we restart them and
14977            // grant/revoke the GID.
14978            final IActivityManager am = ActivityManagerNative.getDefault();
14979            if (am != null) {
14980                final long token = Binder.clearCallingIdentity();
14981                try {
14982                    am.killProcessesBelowForeground("setPermissionEnforcement");
14983                } catch (RemoteException e) {
14984                } finally {
14985                    Binder.restoreCallingIdentity(token);
14986                }
14987            }
14988        } else {
14989            throw new IllegalArgumentException("No selective enforcement for " + permission);
14990        }
14991    }
14992
14993    @Override
14994    @Deprecated
14995    public boolean isPermissionEnforced(String permission) {
14996        return true;
14997    }
14998
14999    @Override
15000    public boolean isStorageLow() {
15001        final long token = Binder.clearCallingIdentity();
15002        try {
15003            final DeviceStorageMonitorInternal
15004                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
15005            if (dsm != null) {
15006                return dsm.isMemoryLow();
15007            } else {
15008                return false;
15009            }
15010        } finally {
15011            Binder.restoreCallingIdentity(token);
15012        }
15013    }
15014
15015    @Override
15016    public IPackageInstaller getPackageInstaller() {
15017        return mInstallerService;
15018    }
15019
15020    private boolean userNeedsBadging(int userId) {
15021        int index = mUserNeedsBadging.indexOfKey(userId);
15022        if (index < 0) {
15023            final UserInfo userInfo;
15024            final long token = Binder.clearCallingIdentity();
15025            try {
15026                userInfo = sUserManager.getUserInfo(userId);
15027            } finally {
15028                Binder.restoreCallingIdentity(token);
15029            }
15030            final boolean b;
15031            if (userInfo != null && userInfo.isManagedProfile()) {
15032                b = true;
15033            } else {
15034                b = false;
15035            }
15036            mUserNeedsBadging.put(userId, b);
15037            return b;
15038        }
15039        return mUserNeedsBadging.valueAt(index);
15040    }
15041
15042    @Override
15043    public KeySet getKeySetByAlias(String packageName, String alias) {
15044        if (packageName == null || alias == null) {
15045            return null;
15046        }
15047        synchronized(mPackages) {
15048            final PackageParser.Package pkg = mPackages.get(packageName);
15049            if (pkg == null) {
15050                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15051                throw new IllegalArgumentException("Unknown package: " + packageName);
15052            }
15053            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15054            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
15055        }
15056    }
15057
15058    @Override
15059    public KeySet getSigningKeySet(String packageName) {
15060        if (packageName == null) {
15061            return null;
15062        }
15063        synchronized(mPackages) {
15064            final PackageParser.Package pkg = mPackages.get(packageName);
15065            if (pkg == null) {
15066                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15067                throw new IllegalArgumentException("Unknown package: " + packageName);
15068            }
15069            if (pkg.applicationInfo.uid != Binder.getCallingUid()
15070                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
15071                throw new SecurityException("May not access signing KeySet of other apps.");
15072            }
15073            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15074            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
15075        }
15076    }
15077
15078    @Override
15079    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
15080        if (packageName == null || ks == null) {
15081            return false;
15082        }
15083        synchronized(mPackages) {
15084            final PackageParser.Package pkg = mPackages.get(packageName);
15085            if (pkg == null) {
15086                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15087                throw new IllegalArgumentException("Unknown package: " + packageName);
15088            }
15089            IBinder ksh = ks.getToken();
15090            if (ksh instanceof KeySetHandle) {
15091                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15092                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
15093            }
15094            return false;
15095        }
15096    }
15097
15098    @Override
15099    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
15100        if (packageName == null || ks == null) {
15101            return false;
15102        }
15103        synchronized(mPackages) {
15104            final PackageParser.Package pkg = mPackages.get(packageName);
15105            if (pkg == null) {
15106                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15107                throw new IllegalArgumentException("Unknown package: " + packageName);
15108            }
15109            IBinder ksh = ks.getToken();
15110            if (ksh instanceof KeySetHandle) {
15111                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15112                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
15113            }
15114            return false;
15115        }
15116    }
15117
15118    public void getUsageStatsIfNoPackageUsageInfo() {
15119        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
15120            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
15121            if (usm == null) {
15122                throw new IllegalStateException("UsageStatsManager must be initialized");
15123            }
15124            long now = System.currentTimeMillis();
15125            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
15126            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
15127                String packageName = entry.getKey();
15128                PackageParser.Package pkg = mPackages.get(packageName);
15129                if (pkg == null) {
15130                    continue;
15131                }
15132                UsageStats usage = entry.getValue();
15133                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
15134                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
15135            }
15136        }
15137    }
15138
15139    /**
15140     * Check and throw if the given before/after packages would be considered a
15141     * downgrade.
15142     */
15143    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
15144            throws PackageManagerException {
15145        if (after.versionCode < before.mVersionCode) {
15146            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15147                    "Update version code " + after.versionCode + " is older than current "
15148                    + before.mVersionCode);
15149        } else if (after.versionCode == before.mVersionCode) {
15150            if (after.baseRevisionCode < before.baseRevisionCode) {
15151                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15152                        "Update base revision code " + after.baseRevisionCode
15153                        + " is older than current " + before.baseRevisionCode);
15154            }
15155
15156            if (!ArrayUtils.isEmpty(after.splitNames)) {
15157                for (int i = 0; i < after.splitNames.length; i++) {
15158                    final String splitName = after.splitNames[i];
15159                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
15160                    if (j != -1) {
15161                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
15162                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15163                                    "Update split " + splitName + " revision code "
15164                                    + after.splitRevisionCodes[i] + " is older than current "
15165                                    + before.splitRevisionCodes[j]);
15166                        }
15167                    }
15168                }
15169            }
15170        }
15171    }
15172
15173    private static class MoveCallbacks extends Handler {
15174        private static final int MSG_CREATED = 1;
15175        private static final int MSG_STATUS_CHANGED = 2;
15176
15177        private final RemoteCallbackList<IPackageMoveObserver>
15178                mCallbacks = new RemoteCallbackList<>();
15179
15180        private final SparseIntArray mLastStatus = new SparseIntArray();
15181
15182        public MoveCallbacks(Looper looper) {
15183            super(looper);
15184        }
15185
15186        public void register(IPackageMoveObserver callback) {
15187            mCallbacks.register(callback);
15188        }
15189
15190        public void unregister(IPackageMoveObserver callback) {
15191            mCallbacks.unregister(callback);
15192        }
15193
15194        @Override
15195        public void handleMessage(Message msg) {
15196            final SomeArgs args = (SomeArgs) msg.obj;
15197            final int n = mCallbacks.beginBroadcast();
15198            for (int i = 0; i < n; i++) {
15199                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
15200                try {
15201                    invokeCallback(callback, msg.what, args);
15202                } catch (RemoteException ignored) {
15203                }
15204            }
15205            mCallbacks.finishBroadcast();
15206            args.recycle();
15207        }
15208
15209        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
15210                throws RemoteException {
15211            switch (what) {
15212                case MSG_CREATED: {
15213                    callback.onCreated(args.argi1, (Bundle) args.arg2);
15214                    break;
15215                }
15216                case MSG_STATUS_CHANGED: {
15217                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
15218                    break;
15219                }
15220            }
15221        }
15222
15223        private void notifyCreated(int moveId, Bundle extras) {
15224            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
15225
15226            final SomeArgs args = SomeArgs.obtain();
15227            args.argi1 = moveId;
15228            args.arg2 = extras;
15229            obtainMessage(MSG_CREATED, args).sendToTarget();
15230        }
15231
15232        private void notifyStatusChanged(int moveId, int status) {
15233            notifyStatusChanged(moveId, status, -1);
15234        }
15235
15236        private void notifyStatusChanged(int moveId, int status, long estMillis) {
15237            Slog.v(TAG, "Move " + moveId + " status " + status);
15238
15239            final SomeArgs args = SomeArgs.obtain();
15240            args.argi1 = moveId;
15241            args.argi2 = status;
15242            args.arg3 = estMillis;
15243            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
15244
15245            synchronized (mLastStatus) {
15246                mLastStatus.put(moveId, status);
15247            }
15248        }
15249    }
15250}
15251