PackageManagerService.java revision ab4bb9d1fec685dab0fce9232c9a3477fab356b3
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    private static final boolean DEBUG_DOMAIN_VERIFICATION = false;
282
283    private static final int RADIO_UID = Process.PHONE_UID;
284    private static final int LOG_UID = Process.LOG_UID;
285    private static final int NFC_UID = Process.NFC_UID;
286    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
287    private static final int SHELL_UID = Process.SHELL_UID;
288
289    // Cap the size of permission trees that 3rd party apps can define
290    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
291
292    // Suffix used during package installation when copying/moving
293    // package apks to install directory.
294    private static final String INSTALL_PACKAGE_SUFFIX = "-";
295
296    static final int SCAN_NO_DEX = 1<<1;
297    static final int SCAN_FORCE_DEX = 1<<2;
298    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
299    static final int SCAN_NEW_INSTALL = 1<<4;
300    static final int SCAN_NO_PATHS = 1<<5;
301    static final int SCAN_UPDATE_TIME = 1<<6;
302    static final int SCAN_DEFER_DEX = 1<<7;
303    static final int SCAN_BOOTING = 1<<8;
304    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
305    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
306    static final int SCAN_REQUIRE_KNOWN = 1<<12;
307    static final int SCAN_MOVE = 1<<13;
308
309    static final int REMOVE_CHATTY = 1<<16;
310
311    private static final int[] EMPTY_INT_ARRAY = new int[0];
312
313    /**
314     * Timeout (in milliseconds) after which the watchdog should declare that
315     * our handler thread is wedged.  The usual default for such things is one
316     * minute but we sometimes do very lengthy I/O operations on this thread,
317     * such as installing multi-gigabyte applications, so ours needs to be longer.
318     */
319    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
320
321    /**
322     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
323     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
324     * settings entry if available, otherwise we use the hardcoded default.  If it's been
325     * more than this long since the last fstrim, we force one during the boot sequence.
326     *
327     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
328     * one gets run at the next available charging+idle time.  This final mandatory
329     * no-fstrim check kicks in only of the other scheduling criteria is never met.
330     */
331    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
332
333    /**
334     * Whether verification is enabled by default.
335     */
336    private static final boolean DEFAULT_VERIFY_ENABLE = true;
337
338    /**
339     * The default maximum time to wait for the verification agent to return in
340     * milliseconds.
341     */
342    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
343
344    /**
345     * The default response for package verification timeout.
346     *
347     * This can be either PackageManager.VERIFICATION_ALLOW or
348     * PackageManager.VERIFICATION_REJECT.
349     */
350    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
351
352    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
353
354    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
355            DEFAULT_CONTAINER_PACKAGE,
356            "com.android.defcontainer.DefaultContainerService");
357
358    private static final String KILL_APP_REASON_GIDS_CHANGED =
359            "permission grant or revoke changed gids";
360
361    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
362            "permissions revoked";
363
364    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
365
366    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
367
368    /** Permission grant: not grant the permission. */
369    private static final int GRANT_DENIED = 1;
370
371    /** Permission grant: grant the permission as an install permission. */
372    private static final int GRANT_INSTALL = 2;
373
374    /** Permission grant: grant the permission as an install permission for a legacy app. */
375    private static final int GRANT_INSTALL_LEGACY = 3;
376
377    /** Permission grant: grant the permission as a runtime one. */
378    private static final int GRANT_RUNTIME = 4;
379
380    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
381    private static final int GRANT_UPGRADE = 5;
382
383    final ServiceThread mHandlerThread;
384
385    final PackageHandler mHandler;
386
387    /**
388     * Messages for {@link #mHandler} that need to wait for system ready before
389     * being dispatched.
390     */
391    private ArrayList<Message> mPostSystemReadyMessages;
392
393    final int mSdkVersion = Build.VERSION.SDK_INT;
394
395    final Context mContext;
396    final boolean mFactoryTest;
397    final boolean mOnlyCore;
398    final boolean mLazyDexOpt;
399    final long mDexOptLRUThresholdInMills;
400    final DisplayMetrics mMetrics;
401    final int mDefParseFlags;
402    final String[] mSeparateProcesses;
403    final boolean mIsUpgrade;
404
405    // This is where all application persistent data goes.
406    final File mAppDataDir;
407
408    // This is where all application persistent data goes for secondary users.
409    final File mUserAppDataDir;
410
411    /** The location for ASEC container files on internal storage. */
412    final String mAsecInternalPath;
413
414    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
415    // LOCK HELD.  Can be called with mInstallLock held.
416    final Installer mInstaller;
417
418    /** Directory where installed third-party apps stored */
419    final File mAppInstallDir;
420
421    /**
422     * Directory to which applications installed internally have their
423     * 32 bit native libraries copied.
424     */
425    private File mAppLib32InstallDir;
426
427    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
428    // apps.
429    final File mDrmAppPrivateInstallDir;
430
431    // ----------------------------------------------------------------
432
433    // Lock for state used when installing and doing other long running
434    // operations.  Methods that must be called with this lock held have
435    // the suffix "LI".
436    final Object mInstallLock = new Object();
437
438    // ----------------------------------------------------------------
439
440    // Keys are String (package name), values are Package.  This also serves
441    // as the lock for the global state.  Methods that must be called with
442    // this lock held have the prefix "LP".
443    final ArrayMap<String, PackageParser.Package> mPackages =
444            new ArrayMap<String, PackageParser.Package>();
445
446    // Tracks available target package names -> overlay package paths.
447    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
448        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
449
450    final Settings mSettings;
451    boolean mRestoredSettings;
452
453    // System configuration read by SystemConfig.
454    final int[] mGlobalGids;
455    final SparseArray<ArraySet<String>> mSystemPermissions;
456    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
457
458    // If mac_permissions.xml was found for seinfo labeling.
459    boolean mFoundPolicyFile;
460
461    // If a recursive restorecon of /data/data/<pkg> is needed.
462    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
463
464    public static final class SharedLibraryEntry {
465        public final String path;
466        public final String apk;
467
468        SharedLibraryEntry(String _path, String _apk) {
469            path = _path;
470            apk = _apk;
471        }
472    }
473
474    // Currently known shared libraries.
475    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
476            new ArrayMap<String, SharedLibraryEntry>();
477
478    // All available activities, for your resolving pleasure.
479    final ActivityIntentResolver mActivities =
480            new ActivityIntentResolver();
481
482    // All available receivers, for your resolving pleasure.
483    final ActivityIntentResolver mReceivers =
484            new ActivityIntentResolver();
485
486    // All available services, for your resolving pleasure.
487    final ServiceIntentResolver mServices = new ServiceIntentResolver();
488
489    // All available providers, for your resolving pleasure.
490    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
491
492    // Mapping from provider base names (first directory in content URI codePath)
493    // to the provider information.
494    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
495            new ArrayMap<String, PackageParser.Provider>();
496
497    // Mapping from instrumentation class names to info about them.
498    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
499            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
500
501    // Mapping from permission names to info about them.
502    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
503            new ArrayMap<String, PackageParser.PermissionGroup>();
504
505    // Packages whose data we have transfered into another package, thus
506    // should no longer exist.
507    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
508
509    // Broadcast actions that are only available to the system.
510    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
511
512    /** List of packages waiting for verification. */
513    final SparseArray<PackageVerificationState> mPendingVerification
514            = new SparseArray<PackageVerificationState>();
515
516    /** Set of packages associated with each app op permission. */
517    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
518
519    final PackageInstallerService mInstallerService;
520
521    private final PackageDexOptimizer mPackageDexOptimizer;
522
523    private AtomicInteger mNextMoveId = new AtomicInteger();
524    private final MoveCallbacks mMoveCallbacks;
525
526    // Cache of users who need badging.
527    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
528
529    /** Token for keys in mPendingVerification. */
530    private int mPendingVerificationToken = 0;
531
532    volatile boolean mSystemReady;
533    volatile boolean mSafeMode;
534    volatile boolean mHasSystemUidErrors;
535
536    ApplicationInfo mAndroidApplication;
537    final ActivityInfo mResolveActivity = new ActivityInfo();
538    final ResolveInfo mResolveInfo = new ResolveInfo();
539    ComponentName mResolveComponentName;
540    PackageParser.Package mPlatformPackage;
541    ComponentName mCustomResolverComponentName;
542
543    boolean mResolverReplaced = false;
544
545    private final ComponentName mIntentFilterVerifierComponent;
546    private int mIntentFilterVerificationToken = 0;
547
548    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
549            = new SparseArray<IntentFilterVerificationState>();
550
551    private interface IntentFilterVerifier<T extends IntentFilter> {
552        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
553                                               T filter, String packageName);
554        void startVerifications(int userId);
555        void receiveVerificationResponse(int verificationId);
556    }
557
558    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
559        private Context mContext;
560        private ComponentName mIntentFilterVerifierComponent;
561        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
562
563        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
564            mContext = context;
565            mIntentFilterVerifierComponent = verifierComponent;
566        }
567
568        private String getDefaultScheme() {
569            // TODO: replace SCHEME_HTTP with SCHEME_HTTPS
570            return IntentFilter.SCHEME_HTTP;
571        }
572
573        @Override
574        public void startVerifications(int userId) {
575            // Launch verifications requests
576            int count = mCurrentIntentFilterVerifications.size();
577            for (int n=0; n<count; n++) {
578                int verificationId = mCurrentIntentFilterVerifications.get(n);
579                final IntentFilterVerificationState ivs =
580                        mIntentFilterVerificationStates.get(verificationId);
581
582                String packageName = ivs.getPackageName();
583
584                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
585                final int filterCount = filters.size();
586                ArraySet<String> domainsSet = new ArraySet<>();
587                for (int m=0; m<filterCount; m++) {
588                    PackageParser.ActivityIntentInfo filter = filters.get(m);
589                    domainsSet.addAll(filter.getHostsList());
590                }
591                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
592                synchronized (mPackages) {
593                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
594                            packageName, domainsList) != null) {
595                        scheduleWriteSettingsLocked();
596                    }
597                }
598                sendVerificationRequest(userId, verificationId, ivs);
599            }
600            mCurrentIntentFilterVerifications.clear();
601        }
602
603        private void sendVerificationRequest(int userId, int verificationId,
604                IntentFilterVerificationState ivs) {
605
606            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
607            verificationIntent.putExtra(
608                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
609                    verificationId);
610            verificationIntent.putExtra(
611                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
612                    getDefaultScheme());
613            verificationIntent.putExtra(
614                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
615                    ivs.getHostsString());
616            verificationIntent.putExtra(
617                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
618                    ivs.getPackageName());
619            verificationIntent.setComponent(mIntentFilterVerifierComponent);
620            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
621
622            UserHandle user = new UserHandle(userId);
623            mContext.sendBroadcastAsUser(verificationIntent, user);
624            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
625                    "Sending IntenFilter verification broadcast");
626        }
627
628        public void receiveVerificationResponse(int verificationId) {
629            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
630
631            final boolean verified = ivs.isVerified();
632
633            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
634            final int count = filters.size();
635            for (int n=0; n<count; n++) {
636                PackageParser.ActivityIntentInfo filter = filters.get(n);
637                filter.setVerified(verified);
638
639                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
640                        + " verified with result:" + verified + " and hosts:"
641                        + ivs.getHostsString());
642            }
643
644            mIntentFilterVerificationStates.remove(verificationId);
645
646            final String packageName = ivs.getPackageName();
647            IntentFilterVerificationInfo ivi = null;
648
649            synchronized (mPackages) {
650                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
651            }
652            if (ivi == null) {
653                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
654                        + verificationId + " packageName:" + packageName);
655                return;
656            }
657            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
658                    "Updating IntentFilterVerificationInfo for verificationId:" + verificationId);
659
660            synchronized (mPackages) {
661                if (verified) {
662                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
663                } else {
664                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
665                }
666                scheduleWriteSettingsLocked();
667
668                final int userId = ivs.getUserId();
669                if (userId != UserHandle.USER_ALL) {
670                    final int userStatus =
671                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
672
673                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
674                    boolean needUpdate = false;
675
676                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
677                    // already been set by the User thru the Disambiguation dialog
678                    switch (userStatus) {
679                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
680                            if (verified) {
681                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
682                            } else {
683                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
684                            }
685                            needUpdate = true;
686                            break;
687
688                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
689                            if (verified) {
690                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
691                                needUpdate = true;
692                            }
693                            break;
694
695                        default:
696                            // Nothing to do
697                    }
698
699                    if (needUpdate) {
700                        mSettings.updateIntentFilterVerificationStatusLPw(
701                                packageName, updatedStatus, userId);
702                        scheduleWritePackageRestrictionsLocked(userId);
703                    }
704                }
705            }
706        }
707
708        @Override
709        public boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
710                    ActivityIntentInfo filter, String packageName) {
711            if (!(filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
712                    filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
713                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
714                        "IntentFilter does not contain HTTP nor HTTPS data scheme");
715                return false;
716            }
717            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
718            if (ivs == null) {
719                ivs = createDomainVerificationState(verifierId, userId, verificationId,
720                        packageName);
721            }
722            if (!hasValidDomains(filter)) {
723                return false;
724            }
725            ivs.addFilter(filter);
726            return true;
727        }
728
729        private IntentFilterVerificationState createDomainVerificationState(int verifierId,
730                int userId, int verificationId, String packageName) {
731            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
732                    verifierId, userId, packageName);
733            ivs.setPendingState();
734            synchronized (mPackages) {
735                mIntentFilterVerificationStates.append(verificationId, ivs);
736                mCurrentIntentFilterVerifications.add(verificationId);
737            }
738            return ivs;
739        }
740    }
741
742    private static boolean hasValidDomains(ActivityIntentInfo filter) {
743        boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
744                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS);
745        if (!hasHTTPorHTTPS) {
746            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
747                    "IntentFilter does not contain any HTTP or HTTPS data scheme");
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                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1518                            "Processing IntentFilter verification with token:"
1519                            + verificationId + " and userId:" + userId);
1520
1521                    final IntentFilterVerificationResponse response =
1522                            (IntentFilterVerificationResponse) msg.obj;
1523
1524                    state.setVerifierResponse(response.callerUid, response.code);
1525
1526                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1527                            "IntentFilter verification with token:" + verificationId
1528                            + " and userId:" + userId
1529                            + " is settings verifier response with response code:"
1530                            + response.code);
1531
1532                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1533                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1534                                + response.getFailedDomainsString());
1535                    }
1536
1537                    if (state.isVerificationComplete()) {
1538                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1539                    } else {
1540                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1541                                "IntentFilter verification with token:" + verificationId
1542                                + " was not said to be complete");
1543                    }
1544
1545                    break;
1546                }
1547            }
1548        }
1549    }
1550
1551    private StorageEventListener mStorageListener = new StorageEventListener() {
1552        @Override
1553        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1554            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1555                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1556                    // TODO: ensure that private directories exist for all active users
1557                    // TODO: remove user data whose serial number doesn't match
1558                    loadPrivatePackages(vol);
1559                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1560                    unloadPrivatePackages(vol);
1561                }
1562            }
1563
1564            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1565                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1566                    updateExternalMediaStatus(true, false);
1567                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1568                    updateExternalMediaStatus(false, false);
1569                }
1570            }
1571        }
1572
1573        @Override
1574        public void onVolumeForgotten(String fsUuid) {
1575            // TODO: remove all packages hosted on this uuid
1576        }
1577    };
1578
1579    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) {
1580        if (userId >= UserHandle.USER_OWNER) {
1581            grantRequestedRuntimePermissionsForUser(pkg, userId);
1582        } else if (userId == UserHandle.USER_ALL) {
1583            for (int someUserId : UserManagerService.getInstance().getUserIds()) {
1584                grantRequestedRuntimePermissionsForUser(pkg, someUserId);
1585            }
1586        }
1587    }
1588
1589    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) {
1590        SettingBase sb = (SettingBase) pkg.mExtras;
1591        if (sb == null) {
1592            return;
1593        }
1594
1595        PermissionsState permissionsState = sb.getPermissionsState();
1596
1597        for (String permission : pkg.requestedPermissions) {
1598            BasePermission bp = mSettings.mPermissions.get(permission);
1599            if (bp != null && bp.isRuntime()) {
1600                permissionsState.grantRuntimePermission(bp, userId);
1601            }
1602        }
1603    }
1604
1605    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1606        Bundle extras = null;
1607        switch (res.returnCode) {
1608            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1609                extras = new Bundle();
1610                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1611                        res.origPermission);
1612                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1613                        res.origPackage);
1614                break;
1615            }
1616            case PackageManager.INSTALL_SUCCEEDED: {
1617                extras = new Bundle();
1618                extras.putBoolean(Intent.EXTRA_REPLACING,
1619                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1620                break;
1621            }
1622        }
1623        return extras;
1624    }
1625
1626    void scheduleWriteSettingsLocked() {
1627        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1628            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1629        }
1630    }
1631
1632    void scheduleWritePackageRestrictionsLocked(int userId) {
1633        if (!sUserManager.exists(userId)) return;
1634        mDirtyUsers.add(userId);
1635        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1636            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1637        }
1638    }
1639
1640    public static PackageManagerService main(Context context, Installer installer,
1641            boolean factoryTest, boolean onlyCore) {
1642        PackageManagerService m = new PackageManagerService(context, installer,
1643                factoryTest, onlyCore);
1644        ServiceManager.addService("package", m);
1645        return m;
1646    }
1647
1648    static String[] splitString(String str, char sep) {
1649        int count = 1;
1650        int i = 0;
1651        while ((i=str.indexOf(sep, i)) >= 0) {
1652            count++;
1653            i++;
1654        }
1655
1656        String[] res = new String[count];
1657        i=0;
1658        count = 0;
1659        int lastI=0;
1660        while ((i=str.indexOf(sep, i)) >= 0) {
1661            res[count] = str.substring(lastI, i);
1662            count++;
1663            i++;
1664            lastI = i;
1665        }
1666        res[count] = str.substring(lastI, str.length());
1667        return res;
1668    }
1669
1670    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1671        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1672                Context.DISPLAY_SERVICE);
1673        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1674    }
1675
1676    public PackageManagerService(Context context, Installer installer,
1677            boolean factoryTest, boolean onlyCore) {
1678        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1679                SystemClock.uptimeMillis());
1680
1681        if (mSdkVersion <= 0) {
1682            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1683        }
1684
1685        mContext = context;
1686        mFactoryTest = factoryTest;
1687        mOnlyCore = onlyCore;
1688        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1689        mMetrics = new DisplayMetrics();
1690        mSettings = new Settings(mPackages);
1691        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1692                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1693        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1694                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1695        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1696                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1697        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1698                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1699        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1700                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1701        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1702                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1703
1704        // TODO: add a property to control this?
1705        long dexOptLRUThresholdInMinutes;
1706        if (mLazyDexOpt) {
1707            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1708        } else {
1709            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1710        }
1711        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1712
1713        String separateProcesses = SystemProperties.get("debug.separate_processes");
1714        if (separateProcesses != null && separateProcesses.length() > 0) {
1715            if ("*".equals(separateProcesses)) {
1716                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1717                mSeparateProcesses = null;
1718                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1719            } else {
1720                mDefParseFlags = 0;
1721                mSeparateProcesses = separateProcesses.split(",");
1722                Slog.w(TAG, "Running with debug.separate_processes: "
1723                        + separateProcesses);
1724            }
1725        } else {
1726            mDefParseFlags = 0;
1727            mSeparateProcesses = null;
1728        }
1729
1730        mInstaller = installer;
1731        mPackageDexOptimizer = new PackageDexOptimizer(this);
1732        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1733
1734        getDefaultDisplayMetrics(context, mMetrics);
1735
1736        SystemConfig systemConfig = SystemConfig.getInstance();
1737        mGlobalGids = systemConfig.getGlobalGids();
1738        mSystemPermissions = systemConfig.getSystemPermissions();
1739        mAvailableFeatures = systemConfig.getAvailableFeatures();
1740
1741        synchronized (mInstallLock) {
1742        // writer
1743        synchronized (mPackages) {
1744            mHandlerThread = new ServiceThread(TAG,
1745                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1746            mHandlerThread.start();
1747            mHandler = new PackageHandler(mHandlerThread.getLooper());
1748            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1749
1750            File dataDir = Environment.getDataDirectory();
1751            mAppDataDir = new File(dataDir, "data");
1752            mAppInstallDir = new File(dataDir, "app");
1753            mAppLib32InstallDir = new File(dataDir, "app-lib");
1754            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1755            mUserAppDataDir = new File(dataDir, "user");
1756            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1757
1758            sUserManager = new UserManagerService(context, this,
1759                    mInstallLock, mPackages);
1760
1761            // Propagate permission configuration in to package manager.
1762            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1763                    = systemConfig.getPermissions();
1764            for (int i=0; i<permConfig.size(); i++) {
1765                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1766                BasePermission bp = mSettings.mPermissions.get(perm.name);
1767                if (bp == null) {
1768                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1769                    mSettings.mPermissions.put(perm.name, bp);
1770                }
1771                if (perm.gids != null) {
1772                    bp.setGids(perm.gids, perm.perUser);
1773                }
1774            }
1775
1776            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1777            for (int i=0; i<libConfig.size(); i++) {
1778                mSharedLibraries.put(libConfig.keyAt(i),
1779                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1780            }
1781
1782            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1783
1784            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1785                    mSdkVersion, mOnlyCore);
1786
1787            String customResolverActivity = Resources.getSystem().getString(
1788                    R.string.config_customResolverActivity);
1789            if (TextUtils.isEmpty(customResolverActivity)) {
1790                customResolverActivity = null;
1791            } else {
1792                mCustomResolverComponentName = ComponentName.unflattenFromString(
1793                        customResolverActivity);
1794            }
1795
1796            long startTime = SystemClock.uptimeMillis();
1797
1798            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1799                    startTime);
1800
1801            // Set flag to monitor and not change apk file paths when
1802            // scanning install directories.
1803            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1804
1805            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1806
1807            /**
1808             * Add everything in the in the boot class path to the
1809             * list of process files because dexopt will have been run
1810             * if necessary during zygote startup.
1811             */
1812            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1813            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1814
1815            if (bootClassPath != null) {
1816                String[] bootClassPathElements = splitString(bootClassPath, ':');
1817                for (String element : bootClassPathElements) {
1818                    alreadyDexOpted.add(element);
1819                }
1820            } else {
1821                Slog.w(TAG, "No BOOTCLASSPATH found!");
1822            }
1823
1824            if (systemServerClassPath != null) {
1825                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1826                for (String element : systemServerClassPathElements) {
1827                    alreadyDexOpted.add(element);
1828                }
1829            } else {
1830                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1831            }
1832
1833            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1834            final String[] dexCodeInstructionSets =
1835                    getDexCodeInstructionSets(
1836                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1837
1838            /**
1839             * Ensure all external libraries have had dexopt run on them.
1840             */
1841            if (mSharedLibraries.size() > 0) {
1842                // NOTE: For now, we're compiling these system "shared libraries"
1843                // (and framework jars) into all available architectures. It's possible
1844                // to compile them only when we come across an app that uses them (there's
1845                // already logic for that in scanPackageLI) but that adds some complexity.
1846                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1847                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1848                        final String lib = libEntry.path;
1849                        if (lib == null) {
1850                            continue;
1851                        }
1852
1853                        try {
1854                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1855                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1856                                alreadyDexOpted.add(lib);
1857                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1858                            }
1859                        } catch (FileNotFoundException e) {
1860                            Slog.w(TAG, "Library not found: " + lib);
1861                        } catch (IOException e) {
1862                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1863                                    + e.getMessage());
1864                        }
1865                    }
1866                }
1867            }
1868
1869            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1870
1871            // Gross hack for now: we know this file doesn't contain any
1872            // code, so don't dexopt it to avoid the resulting log spew.
1873            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1874
1875            // Gross hack for now: we know this file is only part of
1876            // the boot class path for art, so don't dexopt it to
1877            // avoid the resulting log spew.
1878            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1879
1880            /**
1881             * There are a number of commands implemented in Java, which
1882             * we currently need to do the dexopt on so that they can be
1883             * run from a non-root shell.
1884             */
1885            String[] frameworkFiles = frameworkDir.list();
1886            if (frameworkFiles != null) {
1887                // TODO: We could compile these only for the most preferred ABI. We should
1888                // first double check that the dex files for these commands are not referenced
1889                // by other system apps.
1890                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1891                    for (int i=0; i<frameworkFiles.length; i++) {
1892                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1893                        String path = libPath.getPath();
1894                        // Skip the file if we already did it.
1895                        if (alreadyDexOpted.contains(path)) {
1896                            continue;
1897                        }
1898                        // Skip the file if it is not a type we want to dexopt.
1899                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1900                            continue;
1901                        }
1902                        try {
1903                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
1904                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1905                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1906                            }
1907                        } catch (FileNotFoundException e) {
1908                            Slog.w(TAG, "Jar not found: " + path);
1909                        } catch (IOException e) {
1910                            Slog.w(TAG, "Exception reading jar: " + path, e);
1911                        }
1912                    }
1913                }
1914            }
1915
1916            // Collect vendor overlay packages.
1917            // (Do this before scanning any apps.)
1918            // For security and version matching reason, only consider
1919            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1920            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1921            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1922                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1923
1924            // Find base frameworks (resource packages without code).
1925            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1926                    | PackageParser.PARSE_IS_SYSTEM_DIR
1927                    | PackageParser.PARSE_IS_PRIVILEGED,
1928                    scanFlags | SCAN_NO_DEX, 0);
1929
1930            // Collected privileged system packages.
1931            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1932            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1933                    | PackageParser.PARSE_IS_SYSTEM_DIR
1934                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1935
1936            // Collect ordinary system packages.
1937            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
1938            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1939                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1940
1941            // Collect all vendor packages.
1942            File vendorAppDir = new File("/vendor/app");
1943            try {
1944                vendorAppDir = vendorAppDir.getCanonicalFile();
1945            } catch (IOException e) {
1946                // failed to look up canonical path, continue with original one
1947            }
1948            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1949                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1950
1951            // Collect all OEM packages.
1952            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
1953            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1954                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1955
1956            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1957            mInstaller.moveFiles();
1958
1959            // Prune any system packages that no longer exist.
1960            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1961            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
1962            if (!mOnlyCore) {
1963                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1964                while (psit.hasNext()) {
1965                    PackageSetting ps = psit.next();
1966
1967                    /*
1968                     * If this is not a system app, it can't be a
1969                     * disable system app.
1970                     */
1971                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1972                        continue;
1973                    }
1974
1975                    /*
1976                     * If the package is scanned, it's not erased.
1977                     */
1978                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1979                    if (scannedPkg != null) {
1980                        /*
1981                         * If the system app is both scanned and in the
1982                         * disabled packages list, then it must have been
1983                         * added via OTA. Remove it from the currently
1984                         * scanned package so the previously user-installed
1985                         * application can be scanned.
1986                         */
1987                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1988                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
1989                                    + ps.name + "; removing system app.  Last known codePath="
1990                                    + ps.codePathString + ", installStatus=" + ps.installStatus
1991                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
1992                                    + scannedPkg.mVersionCode);
1993                            removePackageLI(ps, true);
1994                            expectingBetter.put(ps.name, ps.codePath);
1995                        }
1996
1997                        continue;
1998                    }
1999
2000                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2001                        psit.remove();
2002                        logCriticalInfo(Log.WARN, "System package " + ps.name
2003                                + " no longer exists; wiping its data");
2004                        removeDataDirsLI(null, ps.name);
2005                    } else {
2006                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2007                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2008                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2009                        }
2010                    }
2011                }
2012            }
2013
2014            //look for any incomplete package installations
2015            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2016            //clean up list
2017            for(int i = 0; i < deletePkgsList.size(); i++) {
2018                //clean up here
2019                cleanupInstallFailedPackage(deletePkgsList.get(i));
2020            }
2021            //delete tmp files
2022            deleteTempPackageFiles();
2023
2024            // Remove any shared userIDs that have no associated packages
2025            mSettings.pruneSharedUsersLPw();
2026
2027            if (!mOnlyCore) {
2028                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2029                        SystemClock.uptimeMillis());
2030                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2031
2032                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2033                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2034
2035                /**
2036                 * Remove disable package settings for any updated system
2037                 * apps that were removed via an OTA. If they're not a
2038                 * previously-updated app, remove them completely.
2039                 * Otherwise, just revoke their system-level permissions.
2040                 */
2041                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2042                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2043                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2044
2045                    String msg;
2046                    if (deletedPkg == null) {
2047                        msg = "Updated system package " + deletedAppName
2048                                + " no longer exists; wiping its data";
2049                        removeDataDirsLI(null, deletedAppName);
2050                    } else {
2051                        msg = "Updated system app + " + deletedAppName
2052                                + " no longer present; removing system privileges for "
2053                                + deletedAppName;
2054
2055                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2056
2057                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2058                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2059                    }
2060                    logCriticalInfo(Log.WARN, msg);
2061                }
2062
2063                /**
2064                 * Make sure all system apps that we expected to appear on
2065                 * the userdata partition actually showed up. If they never
2066                 * appeared, crawl back and revive the system version.
2067                 */
2068                for (int i = 0; i < expectingBetter.size(); i++) {
2069                    final String packageName = expectingBetter.keyAt(i);
2070                    if (!mPackages.containsKey(packageName)) {
2071                        final File scanFile = expectingBetter.valueAt(i);
2072
2073                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2074                                + " but never showed up; reverting to system");
2075
2076                        final int reparseFlags;
2077                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2078                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2079                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2080                                    | PackageParser.PARSE_IS_PRIVILEGED;
2081                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2082                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2083                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2084                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2085                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2086                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2087                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2088                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2089                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2090                        } else {
2091                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2092                            continue;
2093                        }
2094
2095                        mSettings.enableSystemPackageLPw(packageName);
2096
2097                        try {
2098                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2099                        } catch (PackageManagerException e) {
2100                            Slog.e(TAG, "Failed to parse original system package: "
2101                                    + e.getMessage());
2102                        }
2103                    }
2104                }
2105            }
2106
2107            // Now that we know all of the shared libraries, update all clients to have
2108            // the correct library paths.
2109            updateAllSharedLibrariesLPw();
2110
2111            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2112                // NOTE: We ignore potential failures here during a system scan (like
2113                // the rest of the commands above) because there's precious little we
2114                // can do about it. A settings error is reported, though.
2115                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2116                        false /* force dexopt */, false /* defer dexopt */);
2117            }
2118
2119            // Now that we know all the packages we are keeping,
2120            // read and update their last usage times.
2121            mPackageUsage.readLP();
2122
2123            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2124                    SystemClock.uptimeMillis());
2125            Slog.i(TAG, "Time to scan packages: "
2126                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2127                    + " seconds");
2128
2129            // If the platform SDK has changed since the last time we booted,
2130            // we need to re-grant app permission to catch any new ones that
2131            // appear.  This is really a hack, and means that apps can in some
2132            // cases get permissions that the user didn't initially explicitly
2133            // allow...  it would be nice to have some better way to handle
2134            // this situation.
2135            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
2136                    != mSdkVersion;
2137            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
2138                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
2139                    + "; regranting permissions for internal storage");
2140            mSettings.mInternalSdkPlatform = mSdkVersion;
2141
2142            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
2143                    | (regrantPermissions
2144                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
2145                            : 0));
2146
2147            // If this is the first boot, and it is a normal boot, then
2148            // we need to initialize the default preferred apps.
2149            if (!mRestoredSettings && !onlyCore) {
2150                mSettings.readDefaultPreferredAppsLPw(this, 0);
2151            }
2152
2153            // If this is first boot after an OTA, and a normal boot, then
2154            // we need to clear code cache directories.
2155            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
2156            if (mIsUpgrade && !onlyCore) {
2157                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2158                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2159                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2160                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2161                }
2162                mSettings.mFingerprint = Build.FINGERPRINT;
2163            }
2164
2165            primeDomainVerificationsLPw();
2166            checkDefaultBrowser();
2167
2168            // All the changes are done during package scanning.
2169            mSettings.updateInternalDatabaseVersion();
2170
2171            // can downgrade to reader
2172            mSettings.writeLPr();
2173
2174            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2175                    SystemClock.uptimeMillis());
2176
2177            mRequiredVerifierPackage = getRequiredVerifierLPr();
2178
2179            mInstallerService = new PackageInstallerService(context, this);
2180
2181            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2182            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2183                    mIntentFilterVerifierComponent);
2184
2185        } // synchronized (mPackages)
2186        } // synchronized (mInstallLock)
2187
2188        // Now after opening every single application zip, make sure they
2189        // are all flushed.  Not really needed, but keeps things nice and
2190        // tidy.
2191        Runtime.getRuntime().gc();
2192    }
2193
2194    @Override
2195    public boolean isFirstBoot() {
2196        return !mRestoredSettings;
2197    }
2198
2199    @Override
2200    public boolean isOnlyCoreApps() {
2201        return mOnlyCore;
2202    }
2203
2204    @Override
2205    public boolean isUpgrade() {
2206        return mIsUpgrade;
2207    }
2208
2209    private String getRequiredVerifierLPr() {
2210        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2211        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2212                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2213
2214        String requiredVerifier = null;
2215
2216        final int N = receivers.size();
2217        for (int i = 0; i < N; i++) {
2218            final ResolveInfo info = receivers.get(i);
2219
2220            if (info.activityInfo == null) {
2221                continue;
2222            }
2223
2224            final String packageName = info.activityInfo.packageName;
2225
2226            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2227                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2228                continue;
2229            }
2230
2231            if (requiredVerifier != null) {
2232                throw new RuntimeException("There can be only one required verifier");
2233            }
2234
2235            requiredVerifier = packageName;
2236        }
2237
2238        return requiredVerifier;
2239    }
2240
2241    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2242        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2243        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2244                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2245
2246        ComponentName verifierComponentName = null;
2247
2248        int priority = -1000;
2249        final int N = receivers.size();
2250        for (int i = 0; i < N; i++) {
2251            final ResolveInfo info = receivers.get(i);
2252
2253            if (info.activityInfo == null) {
2254                continue;
2255            }
2256
2257            final String packageName = info.activityInfo.packageName;
2258
2259            final PackageSetting ps = mSettings.mPackages.get(packageName);
2260            if (ps == null) {
2261                continue;
2262            }
2263
2264            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2265                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2266                continue;
2267            }
2268
2269            // Select the IntentFilterVerifier with the highest priority
2270            if (priority < info.priority) {
2271                priority = info.priority;
2272                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2273                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2274                        + verifierComponentName + " with priority: " + info.priority);
2275            }
2276        }
2277
2278        return verifierComponentName;
2279    }
2280
2281    private void primeDomainVerificationsLPw() {
2282        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications");
2283        boolean updated = false;
2284        ArraySet<String> allHostsSet = new ArraySet<>();
2285        for (PackageParser.Package pkg : mPackages.values()) {
2286            final String packageName = pkg.packageName;
2287            if (!hasDomainURLs(pkg)) {
2288                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " +
2289                            "package with no domain URLs: " + packageName);
2290                continue;
2291            }
2292            if (!pkg.isSystemApp()) {
2293                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2294                        "No priming domain verifications for a non system package : " +
2295                                packageName);
2296                continue;
2297            }
2298            for (PackageParser.Activity a : pkg.activities) {
2299                for (ActivityIntentInfo filter : a.intents) {
2300                    if (hasValidDomains(filter)) {
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                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2313                        "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 (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2320                        "No priming domain verifications for package: " + packageName);
2321            }
2322            allHostsSet.clear();
2323        }
2324        if (updated) {
2325            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2326                    "Will need to write primed domain verifications");
2327        }
2328        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications");
2329    }
2330
2331    private void checkDefaultBrowser() {
2332        final int myUserId = UserHandle.myUserId();
2333        final String packageName = getDefaultBrowserPackageName(myUserId);
2334        PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2335        if (info == null) {
2336            Slog.w(TAG, "Clearing default Browser as its package is no more installed: " +
2337                    packageName);
2338            setDefaultBrowserPackageName(null, myUserId);
2339        }
2340    }
2341
2342    @Override
2343    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2344            throws RemoteException {
2345        try {
2346            return super.onTransact(code, data, reply, flags);
2347        } catch (RuntimeException e) {
2348            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2349                Slog.wtf(TAG, "Package Manager Crash", e);
2350            }
2351            throw e;
2352        }
2353    }
2354
2355    void cleanupInstallFailedPackage(PackageSetting ps) {
2356        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2357
2358        removeDataDirsLI(ps.volumeUuid, ps.name);
2359        if (ps.codePath != null) {
2360            if (ps.codePath.isDirectory()) {
2361                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2362            } else {
2363                ps.codePath.delete();
2364            }
2365        }
2366        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2367            if (ps.resourcePath.isDirectory()) {
2368                FileUtils.deleteContents(ps.resourcePath);
2369            }
2370            ps.resourcePath.delete();
2371        }
2372        mSettings.removePackageLPw(ps.name);
2373    }
2374
2375    static int[] appendInts(int[] cur, int[] add) {
2376        if (add == null) return cur;
2377        if (cur == null) return add;
2378        final int N = add.length;
2379        for (int i=0; i<N; i++) {
2380            cur = appendInt(cur, add[i]);
2381        }
2382        return cur;
2383    }
2384
2385    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2386        if (!sUserManager.exists(userId)) return null;
2387        final PackageSetting ps = (PackageSetting) p.mExtras;
2388        if (ps == null) {
2389            return null;
2390        }
2391
2392        final PermissionsState permissionsState = ps.getPermissionsState();
2393
2394        final int[] gids = permissionsState.computeGids(userId);
2395        final Set<String> permissions = permissionsState.getPermissions(userId);
2396        final PackageUserState state = ps.readUserState(userId);
2397
2398        return PackageParser.generatePackageInfo(p, gids, flags,
2399                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2400    }
2401
2402    @Override
2403    public boolean isPackageFrozen(String packageName) {
2404        synchronized (mPackages) {
2405            final PackageSetting ps = mSettings.mPackages.get(packageName);
2406            if (ps != null) {
2407                return ps.frozen;
2408            }
2409        }
2410        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2411        return true;
2412    }
2413
2414    @Override
2415    public boolean isPackageAvailable(String packageName, int userId) {
2416        if (!sUserManager.exists(userId)) return false;
2417        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2418        synchronized (mPackages) {
2419            PackageParser.Package p = mPackages.get(packageName);
2420            if (p != null) {
2421                final PackageSetting ps = (PackageSetting) p.mExtras;
2422                if (ps != null) {
2423                    final PackageUserState state = ps.readUserState(userId);
2424                    if (state != null) {
2425                        return PackageParser.isAvailable(state);
2426                    }
2427                }
2428            }
2429        }
2430        return false;
2431    }
2432
2433    @Override
2434    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2435        if (!sUserManager.exists(userId)) return null;
2436        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2437        // reader
2438        synchronized (mPackages) {
2439            PackageParser.Package p = mPackages.get(packageName);
2440            if (DEBUG_PACKAGE_INFO)
2441                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2442            if (p != null) {
2443                return generatePackageInfo(p, flags, userId);
2444            }
2445            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2446                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2447            }
2448        }
2449        return null;
2450    }
2451
2452    @Override
2453    public String[] currentToCanonicalPackageNames(String[] names) {
2454        String[] out = new String[names.length];
2455        // reader
2456        synchronized (mPackages) {
2457            for (int i=names.length-1; i>=0; i--) {
2458                PackageSetting ps = mSettings.mPackages.get(names[i]);
2459                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2460            }
2461        }
2462        return out;
2463    }
2464
2465    @Override
2466    public String[] canonicalToCurrentPackageNames(String[] names) {
2467        String[] out = new String[names.length];
2468        // reader
2469        synchronized (mPackages) {
2470            for (int i=names.length-1; i>=0; i--) {
2471                String cur = mSettings.mRenamedPackages.get(names[i]);
2472                out[i] = cur != null ? cur : names[i];
2473            }
2474        }
2475        return out;
2476    }
2477
2478    @Override
2479    public int getPackageUid(String packageName, int userId) {
2480        if (!sUserManager.exists(userId)) return -1;
2481        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2482
2483        // reader
2484        synchronized (mPackages) {
2485            PackageParser.Package p = mPackages.get(packageName);
2486            if(p != null) {
2487                return UserHandle.getUid(userId, p.applicationInfo.uid);
2488            }
2489            PackageSetting ps = mSettings.mPackages.get(packageName);
2490            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2491                return -1;
2492            }
2493            p = ps.pkg;
2494            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2495        }
2496    }
2497
2498    @Override
2499    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2500        if (!sUserManager.exists(userId)) {
2501            return null;
2502        }
2503
2504        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2505                "getPackageGids");
2506
2507        // reader
2508        synchronized (mPackages) {
2509            PackageParser.Package p = mPackages.get(packageName);
2510            if (DEBUG_PACKAGE_INFO) {
2511                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2512            }
2513            if (p != null) {
2514                PackageSetting ps = (PackageSetting) p.mExtras;
2515                return ps.getPermissionsState().computeGids(userId);
2516            }
2517        }
2518
2519        return null;
2520    }
2521
2522    static PermissionInfo generatePermissionInfo(
2523            BasePermission bp, int flags) {
2524        if (bp.perm != null) {
2525            return PackageParser.generatePermissionInfo(bp.perm, flags);
2526        }
2527        PermissionInfo pi = new PermissionInfo();
2528        pi.name = bp.name;
2529        pi.packageName = bp.sourcePackage;
2530        pi.nonLocalizedLabel = bp.name;
2531        pi.protectionLevel = bp.protectionLevel;
2532        return pi;
2533    }
2534
2535    @Override
2536    public PermissionInfo getPermissionInfo(String name, int flags) {
2537        // reader
2538        synchronized (mPackages) {
2539            final BasePermission p = mSettings.mPermissions.get(name);
2540            if (p != null) {
2541                return generatePermissionInfo(p, flags);
2542            }
2543            return null;
2544        }
2545    }
2546
2547    @Override
2548    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2549        // reader
2550        synchronized (mPackages) {
2551            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2552            for (BasePermission p : mSettings.mPermissions.values()) {
2553                if (group == null) {
2554                    if (p.perm == null || p.perm.info.group == null) {
2555                        out.add(generatePermissionInfo(p, flags));
2556                    }
2557                } else {
2558                    if (p.perm != null && group.equals(p.perm.info.group)) {
2559                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2560                    }
2561                }
2562            }
2563
2564            if (out.size() > 0) {
2565                return out;
2566            }
2567            return mPermissionGroups.containsKey(group) ? out : null;
2568        }
2569    }
2570
2571    @Override
2572    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2573        // reader
2574        synchronized (mPackages) {
2575            return PackageParser.generatePermissionGroupInfo(
2576                    mPermissionGroups.get(name), flags);
2577        }
2578    }
2579
2580    @Override
2581    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2582        // reader
2583        synchronized (mPackages) {
2584            final int N = mPermissionGroups.size();
2585            ArrayList<PermissionGroupInfo> out
2586                    = new ArrayList<PermissionGroupInfo>(N);
2587            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2588                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2589            }
2590            return out;
2591        }
2592    }
2593
2594    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2595            int userId) {
2596        if (!sUserManager.exists(userId)) return null;
2597        PackageSetting ps = mSettings.mPackages.get(packageName);
2598        if (ps != null) {
2599            if (ps.pkg == null) {
2600                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2601                        flags, userId);
2602                if (pInfo != null) {
2603                    return pInfo.applicationInfo;
2604                }
2605                return null;
2606            }
2607            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2608                    ps.readUserState(userId), userId);
2609        }
2610        return null;
2611    }
2612
2613    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2614            int userId) {
2615        if (!sUserManager.exists(userId)) return null;
2616        PackageSetting ps = mSettings.mPackages.get(packageName);
2617        if (ps != null) {
2618            PackageParser.Package pkg = ps.pkg;
2619            if (pkg == null) {
2620                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2621                    return null;
2622                }
2623                // Only data remains, so we aren't worried about code paths
2624                pkg = new PackageParser.Package(packageName);
2625                pkg.applicationInfo.packageName = packageName;
2626                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2627                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2628                pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid,
2629                        packageName, userId).getAbsolutePath();
2630                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2631                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2632            }
2633            return generatePackageInfo(pkg, flags, userId);
2634        }
2635        return null;
2636    }
2637
2638    @Override
2639    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2640        if (!sUserManager.exists(userId)) return null;
2641        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2642        // writer
2643        synchronized (mPackages) {
2644            PackageParser.Package p = mPackages.get(packageName);
2645            if (DEBUG_PACKAGE_INFO) Log.v(
2646                    TAG, "getApplicationInfo " + packageName
2647                    + ": " + p);
2648            if (p != null) {
2649                PackageSetting ps = mSettings.mPackages.get(packageName);
2650                if (ps == null) return null;
2651                // Note: isEnabledLP() does not apply here - always return info
2652                return PackageParser.generateApplicationInfo(
2653                        p, flags, ps.readUserState(userId), userId);
2654            }
2655            if ("android".equals(packageName)||"system".equals(packageName)) {
2656                return mAndroidApplication;
2657            }
2658            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2659                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2660            }
2661        }
2662        return null;
2663    }
2664
2665    @Override
2666    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2667            final IPackageDataObserver observer) {
2668        mContext.enforceCallingOrSelfPermission(
2669                android.Manifest.permission.CLEAR_APP_CACHE, null);
2670        // Queue up an async operation since clearing cache may take a little while.
2671        mHandler.post(new Runnable() {
2672            public void run() {
2673                mHandler.removeCallbacks(this);
2674                int retCode = -1;
2675                synchronized (mInstallLock) {
2676                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2677                    if (retCode < 0) {
2678                        Slog.w(TAG, "Couldn't clear application caches");
2679                    }
2680                }
2681                if (observer != null) {
2682                    try {
2683                        observer.onRemoveCompleted(null, (retCode >= 0));
2684                    } catch (RemoteException e) {
2685                        Slog.w(TAG, "RemoveException when invoking call back");
2686                    }
2687                }
2688            }
2689        });
2690    }
2691
2692    @Override
2693    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2694            final IntentSender pi) {
2695        mContext.enforceCallingOrSelfPermission(
2696                android.Manifest.permission.CLEAR_APP_CACHE, null);
2697        // Queue up an async operation since clearing cache may take a little while.
2698        mHandler.post(new Runnable() {
2699            public void run() {
2700                mHandler.removeCallbacks(this);
2701                int retCode = -1;
2702                synchronized (mInstallLock) {
2703                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2704                    if (retCode < 0) {
2705                        Slog.w(TAG, "Couldn't clear application caches");
2706                    }
2707                }
2708                if(pi != null) {
2709                    try {
2710                        // Callback via pending intent
2711                        int code = (retCode >= 0) ? 1 : 0;
2712                        pi.sendIntent(null, code, null,
2713                                null, null);
2714                    } catch (SendIntentException e1) {
2715                        Slog.i(TAG, "Failed to send pending intent");
2716                    }
2717                }
2718            }
2719        });
2720    }
2721
2722    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2723        synchronized (mInstallLock) {
2724            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2725                throw new IOException("Failed to free enough space");
2726            }
2727        }
2728    }
2729
2730    @Override
2731    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2732        if (!sUserManager.exists(userId)) return null;
2733        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2734        synchronized (mPackages) {
2735            PackageParser.Activity a = mActivities.mActivities.get(component);
2736
2737            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2738            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2739                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2740                if (ps == null) return null;
2741                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2742                        userId);
2743            }
2744            if (mResolveComponentName.equals(component)) {
2745                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2746                        new PackageUserState(), userId);
2747            }
2748        }
2749        return null;
2750    }
2751
2752    @Override
2753    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2754            String resolvedType) {
2755        synchronized (mPackages) {
2756            PackageParser.Activity a = mActivities.mActivities.get(component);
2757            if (a == null) {
2758                return false;
2759            }
2760            for (int i=0; i<a.intents.size(); i++) {
2761                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2762                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2763                    return true;
2764                }
2765            }
2766            return false;
2767        }
2768    }
2769
2770    @Override
2771    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2772        if (!sUserManager.exists(userId)) return null;
2773        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2774        synchronized (mPackages) {
2775            PackageParser.Activity a = mReceivers.mActivities.get(component);
2776            if (DEBUG_PACKAGE_INFO) Log.v(
2777                TAG, "getReceiverInfo " + component + ": " + a);
2778            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2779                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2780                if (ps == null) return null;
2781                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2782                        userId);
2783            }
2784        }
2785        return null;
2786    }
2787
2788    @Override
2789    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2790        if (!sUserManager.exists(userId)) return null;
2791        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2792        synchronized (mPackages) {
2793            PackageParser.Service s = mServices.mServices.get(component);
2794            if (DEBUG_PACKAGE_INFO) Log.v(
2795                TAG, "getServiceInfo " + component + ": " + s);
2796            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2797                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2798                if (ps == null) return null;
2799                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2800                        userId);
2801            }
2802        }
2803        return null;
2804    }
2805
2806    @Override
2807    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2808        if (!sUserManager.exists(userId)) return null;
2809        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2810        synchronized (mPackages) {
2811            PackageParser.Provider p = mProviders.mProviders.get(component);
2812            if (DEBUG_PACKAGE_INFO) Log.v(
2813                TAG, "getProviderInfo " + component + ": " + p);
2814            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2815                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2816                if (ps == null) return null;
2817                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2818                        userId);
2819            }
2820        }
2821        return null;
2822    }
2823
2824    @Override
2825    public String[] getSystemSharedLibraryNames() {
2826        Set<String> libSet;
2827        synchronized (mPackages) {
2828            libSet = mSharedLibraries.keySet();
2829            int size = libSet.size();
2830            if (size > 0) {
2831                String[] libs = new String[size];
2832                libSet.toArray(libs);
2833                return libs;
2834            }
2835        }
2836        return null;
2837    }
2838
2839    /**
2840     * @hide
2841     */
2842    PackageParser.Package findSharedNonSystemLibrary(String libName) {
2843        synchronized (mPackages) {
2844            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
2845            if (lib != null && lib.apk != null) {
2846                return mPackages.get(lib.apk);
2847            }
2848        }
2849        return null;
2850    }
2851
2852    @Override
2853    public FeatureInfo[] getSystemAvailableFeatures() {
2854        Collection<FeatureInfo> featSet;
2855        synchronized (mPackages) {
2856            featSet = mAvailableFeatures.values();
2857            int size = featSet.size();
2858            if (size > 0) {
2859                FeatureInfo[] features = new FeatureInfo[size+1];
2860                featSet.toArray(features);
2861                FeatureInfo fi = new FeatureInfo();
2862                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2863                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2864                features[size] = fi;
2865                return features;
2866            }
2867        }
2868        return null;
2869    }
2870
2871    @Override
2872    public boolean hasSystemFeature(String name) {
2873        synchronized (mPackages) {
2874            return mAvailableFeatures.containsKey(name);
2875        }
2876    }
2877
2878    private void checkValidCaller(int uid, int userId) {
2879        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2880            return;
2881
2882        throw new SecurityException("Caller uid=" + uid
2883                + " is not privileged to communicate with user=" + userId);
2884    }
2885
2886    @Override
2887    public int checkPermission(String permName, String pkgName, int userId) {
2888        if (!sUserManager.exists(userId)) {
2889            return PackageManager.PERMISSION_DENIED;
2890        }
2891
2892        synchronized (mPackages) {
2893            final PackageParser.Package p = mPackages.get(pkgName);
2894            if (p != null && p.mExtras != null) {
2895                final PackageSetting ps = (PackageSetting) p.mExtras;
2896                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2897                    return PackageManager.PERMISSION_GRANTED;
2898                }
2899            }
2900        }
2901
2902        return PackageManager.PERMISSION_DENIED;
2903    }
2904
2905    @Override
2906    public int checkUidPermission(String permName, int uid) {
2907        final int userId = UserHandle.getUserId(uid);
2908
2909        if (!sUserManager.exists(userId)) {
2910            return PackageManager.PERMISSION_DENIED;
2911        }
2912
2913        synchronized (mPackages) {
2914            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2915            if (obj != null) {
2916                final SettingBase ps = (SettingBase) obj;
2917                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2918                    return PackageManager.PERMISSION_GRANTED;
2919                }
2920            } else {
2921                ArraySet<String> perms = mSystemPermissions.get(uid);
2922                if (perms != null && perms.contains(permName)) {
2923                    return PackageManager.PERMISSION_GRANTED;
2924                }
2925            }
2926        }
2927
2928        return PackageManager.PERMISSION_DENIED;
2929    }
2930
2931    /**
2932     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2933     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2934     * @param checkShell TODO(yamasani):
2935     * @param message the message to log on security exception
2936     */
2937    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2938            boolean checkShell, String message) {
2939        if (userId < 0) {
2940            throw new IllegalArgumentException("Invalid userId " + userId);
2941        }
2942        if (checkShell) {
2943            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
2944        }
2945        if (userId == UserHandle.getUserId(callingUid)) return;
2946        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2947            if (requireFullPermission) {
2948                mContext.enforceCallingOrSelfPermission(
2949                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2950            } else {
2951                try {
2952                    mContext.enforceCallingOrSelfPermission(
2953                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2954                } catch (SecurityException se) {
2955                    mContext.enforceCallingOrSelfPermission(
2956                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2957                }
2958            }
2959        }
2960    }
2961
2962    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
2963        if (callingUid == Process.SHELL_UID) {
2964            if (userHandle >= 0
2965                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
2966                throw new SecurityException("Shell does not have permission to access user "
2967                        + userHandle);
2968            } else if (userHandle < 0) {
2969                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
2970                        + Debug.getCallers(3));
2971            }
2972        }
2973    }
2974
2975    private BasePermission findPermissionTreeLP(String permName) {
2976        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2977            if (permName.startsWith(bp.name) &&
2978                    permName.length() > bp.name.length() &&
2979                    permName.charAt(bp.name.length()) == '.') {
2980                return bp;
2981            }
2982        }
2983        return null;
2984    }
2985
2986    private BasePermission checkPermissionTreeLP(String permName) {
2987        if (permName != null) {
2988            BasePermission bp = findPermissionTreeLP(permName);
2989            if (bp != null) {
2990                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2991                    return bp;
2992                }
2993                throw new SecurityException("Calling uid "
2994                        + Binder.getCallingUid()
2995                        + " is not allowed to add to permission tree "
2996                        + bp.name + " owned by uid " + bp.uid);
2997            }
2998        }
2999        throw new SecurityException("No permission tree found for " + permName);
3000    }
3001
3002    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3003        if (s1 == null) {
3004            return s2 == null;
3005        }
3006        if (s2 == null) {
3007            return false;
3008        }
3009        if (s1.getClass() != s2.getClass()) {
3010            return false;
3011        }
3012        return s1.equals(s2);
3013    }
3014
3015    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3016        if (pi1.icon != pi2.icon) return false;
3017        if (pi1.logo != pi2.logo) return false;
3018        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3019        if (!compareStrings(pi1.name, pi2.name)) return false;
3020        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3021        // We'll take care of setting this one.
3022        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3023        // These are not currently stored in settings.
3024        //if (!compareStrings(pi1.group, pi2.group)) return false;
3025        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3026        //if (pi1.labelRes != pi2.labelRes) return false;
3027        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3028        return true;
3029    }
3030
3031    int permissionInfoFootprint(PermissionInfo info) {
3032        int size = info.name.length();
3033        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3034        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3035        return size;
3036    }
3037
3038    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3039        int size = 0;
3040        for (BasePermission perm : mSettings.mPermissions.values()) {
3041            if (perm.uid == tree.uid) {
3042                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3043            }
3044        }
3045        return size;
3046    }
3047
3048    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3049        // We calculate the max size of permissions defined by this uid and throw
3050        // if that plus the size of 'info' would exceed our stated maximum.
3051        if (tree.uid != Process.SYSTEM_UID) {
3052            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3053            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3054                throw new SecurityException("Permission tree size cap exceeded");
3055            }
3056        }
3057    }
3058
3059    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3060        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3061            throw new SecurityException("Label must be specified in permission");
3062        }
3063        BasePermission tree = checkPermissionTreeLP(info.name);
3064        BasePermission bp = mSettings.mPermissions.get(info.name);
3065        boolean added = bp == null;
3066        boolean changed = true;
3067        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3068        if (added) {
3069            enforcePermissionCapLocked(info, tree);
3070            bp = new BasePermission(info.name, tree.sourcePackage,
3071                    BasePermission.TYPE_DYNAMIC);
3072        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3073            throw new SecurityException(
3074                    "Not allowed to modify non-dynamic permission "
3075                    + info.name);
3076        } else {
3077            if (bp.protectionLevel == fixedLevel
3078                    && bp.perm.owner.equals(tree.perm.owner)
3079                    && bp.uid == tree.uid
3080                    && comparePermissionInfos(bp.perm.info, info)) {
3081                changed = false;
3082            }
3083        }
3084        bp.protectionLevel = fixedLevel;
3085        info = new PermissionInfo(info);
3086        info.protectionLevel = fixedLevel;
3087        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3088        bp.perm.info.packageName = tree.perm.info.packageName;
3089        bp.uid = tree.uid;
3090        if (added) {
3091            mSettings.mPermissions.put(info.name, bp);
3092        }
3093        if (changed) {
3094            if (!async) {
3095                mSettings.writeLPr();
3096            } else {
3097                scheduleWriteSettingsLocked();
3098            }
3099        }
3100        return added;
3101    }
3102
3103    @Override
3104    public boolean addPermission(PermissionInfo info) {
3105        synchronized (mPackages) {
3106            return addPermissionLocked(info, false);
3107        }
3108    }
3109
3110    @Override
3111    public boolean addPermissionAsync(PermissionInfo info) {
3112        synchronized (mPackages) {
3113            return addPermissionLocked(info, true);
3114        }
3115    }
3116
3117    @Override
3118    public void removePermission(String name) {
3119        synchronized (mPackages) {
3120            checkPermissionTreeLP(name);
3121            BasePermission bp = mSettings.mPermissions.get(name);
3122            if (bp != null) {
3123                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3124                    throw new SecurityException(
3125                            "Not allowed to modify non-dynamic permission "
3126                            + name);
3127                }
3128                mSettings.mPermissions.remove(name);
3129                mSettings.writeLPr();
3130            }
3131        }
3132    }
3133
3134    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3135            BasePermission bp) {
3136        int index = pkg.requestedPermissions.indexOf(bp.name);
3137        if (index == -1) {
3138            throw new SecurityException("Package " + pkg.packageName
3139                    + " has not requested permission " + bp.name);
3140        }
3141        if (!bp.isRuntime()) {
3142            throw new SecurityException("Permission " + bp.name
3143                    + " is not a changeable permission type");
3144        }
3145    }
3146
3147    @Override
3148    public void grantRuntimePermission(String packageName, String name, int userId) {
3149        if (!sUserManager.exists(userId)) {
3150            Log.e(TAG, "No such user:" + userId);
3151            return;
3152        }
3153
3154        mContext.enforceCallingOrSelfPermission(
3155                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3156                "grantRuntimePermission");
3157
3158        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3159                "grantRuntimePermission");
3160
3161        boolean gidsChanged = false;
3162        final SettingBase sb;
3163
3164        synchronized (mPackages) {
3165            final PackageParser.Package pkg = mPackages.get(packageName);
3166            if (pkg == null) {
3167                throw new IllegalArgumentException("Unknown package: " + packageName);
3168            }
3169
3170            final BasePermission bp = mSettings.mPermissions.get(name);
3171            if (bp == null) {
3172                throw new IllegalArgumentException("Unknown permission: " + name);
3173            }
3174
3175            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3176
3177            sb = (SettingBase) pkg.mExtras;
3178            if (sb == null) {
3179                throw new IllegalArgumentException("Unknown package: " + packageName);
3180            }
3181
3182            final PermissionsState permissionsState = sb.getPermissionsState();
3183
3184            final int flags = permissionsState.getPermissionFlags(name, userId);
3185            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3186                throw new SecurityException("Cannot grant system fixed permission: "
3187                        + name + " for package: " + packageName);
3188            }
3189
3190            final int result = permissionsState.grantRuntimePermission(bp, userId);
3191            switch (result) {
3192                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3193                    return;
3194                }
3195
3196                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3197                    gidsChanged = true;
3198                }
3199                break;
3200            }
3201
3202            // Not critical if that is lost - app has to request again.
3203            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3204        }
3205
3206        if (gidsChanged) {
3207            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3208        }
3209    }
3210
3211    @Override
3212    public void revokeRuntimePermission(String packageName, String name, int userId) {
3213        if (!sUserManager.exists(userId)) {
3214            Log.e(TAG, "No such user:" + userId);
3215            return;
3216        }
3217
3218        mContext.enforceCallingOrSelfPermission(
3219                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3220                "revokeRuntimePermission");
3221
3222        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3223                "revokeRuntimePermission");
3224
3225        final SettingBase sb;
3226
3227        synchronized (mPackages) {
3228            final PackageParser.Package pkg = mPackages.get(packageName);
3229            if (pkg == null) {
3230                throw new IllegalArgumentException("Unknown package: " + packageName);
3231            }
3232
3233            final BasePermission bp = mSettings.mPermissions.get(name);
3234            if (bp == null) {
3235                throw new IllegalArgumentException("Unknown permission: " + name);
3236            }
3237
3238            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3239
3240            sb = (SettingBase) pkg.mExtras;
3241            if (sb == null) {
3242                throw new IllegalArgumentException("Unknown package: " + packageName);
3243            }
3244
3245            final PermissionsState permissionsState = sb.getPermissionsState();
3246
3247            final int flags = permissionsState.getPermissionFlags(name, userId);
3248            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3249                throw new SecurityException("Cannot revoke system fixed permission: "
3250                        + name + " for package: " + packageName);
3251            }
3252
3253            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3254                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3255                return;
3256            }
3257
3258            // Critical, after this call app should never have the permission.
3259            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3260        }
3261
3262        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3263    }
3264
3265    @Override
3266    public int getPermissionFlags(String name, String packageName, int userId) {
3267        if (!sUserManager.exists(userId)) {
3268            return 0;
3269        }
3270
3271        mContext.enforceCallingOrSelfPermission(
3272                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3273                "getPermissionFlags");
3274
3275        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3276                "getPermissionFlags");
3277
3278        synchronized (mPackages) {
3279            final PackageParser.Package pkg = mPackages.get(packageName);
3280            if (pkg == null) {
3281                throw new IllegalArgumentException("Unknown package: " + packageName);
3282            }
3283
3284            final BasePermission bp = mSettings.mPermissions.get(name);
3285            if (bp == null) {
3286                throw new IllegalArgumentException("Unknown permission: " + name);
3287            }
3288
3289            SettingBase sb = (SettingBase) pkg.mExtras;
3290            if (sb == null) {
3291                throw new IllegalArgumentException("Unknown package: " + packageName);
3292            }
3293
3294            PermissionsState permissionsState = sb.getPermissionsState();
3295            return permissionsState.getPermissionFlags(name, userId);
3296        }
3297    }
3298
3299    @Override
3300    public void updatePermissionFlags(String name, String packageName, int flagMask,
3301            int flagValues, int userId) {
3302        if (!sUserManager.exists(userId)) {
3303            return;
3304        }
3305
3306        mContext.enforceCallingOrSelfPermission(
3307                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3308                "updatePermissionFlags");
3309
3310        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3311                "updatePermissionFlags");
3312
3313        // Only the system can change policy flags.
3314        if (getCallingUid() != Process.SYSTEM_UID) {
3315            flagMask &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED;
3316            flagValues &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED;
3317        }
3318
3319        // Only the package manager can change system flags.
3320        flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3321        flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3322
3323        synchronized (mPackages) {
3324            final PackageParser.Package pkg = mPackages.get(packageName);
3325            if (pkg == null) {
3326                throw new IllegalArgumentException("Unknown package: " + packageName);
3327            }
3328
3329            final BasePermission bp = mSettings.mPermissions.get(name);
3330            if (bp == null) {
3331                throw new IllegalArgumentException("Unknown permission: " + name);
3332            }
3333
3334            SettingBase sb = (SettingBase) pkg.mExtras;
3335            if (sb == null) {
3336                throw new IllegalArgumentException("Unknown package: " + packageName);
3337            }
3338
3339            PermissionsState permissionsState = sb.getPermissionsState();
3340
3341            // Only the package manager can change flags for system component permissions.
3342            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3343            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3344                return;
3345            }
3346
3347            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3348                // Install and runtime permissions are stored in different places,
3349                // so figure out what permission changed and persist the change.
3350                if (permissionsState.getInstallPermissionState(name) != null) {
3351                    scheduleWriteSettingsLocked();
3352                } else if (permissionsState.getRuntimePermissionState(name, userId) != null) {
3353                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3354                }
3355            }
3356        }
3357    }
3358
3359    @Override
3360    public boolean shouldShowRequestPermissionRationale(String permissionName,
3361            String packageName, int userId) {
3362        if (UserHandle.getCallingUserId() != userId) {
3363            mContext.enforceCallingPermission(
3364                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3365                    "canShowRequestPermissionRationale for user " + userId);
3366        }
3367
3368        final int uid = getPackageUid(packageName, userId);
3369        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3370            return false;
3371        }
3372
3373        if (checkPermission(permissionName, packageName, userId)
3374                == PackageManager.PERMISSION_GRANTED) {
3375            return false;
3376        }
3377
3378        final int flags;
3379
3380        final long identity = Binder.clearCallingIdentity();
3381        try {
3382            flags = getPermissionFlags(permissionName,
3383                    packageName, userId);
3384        } finally {
3385            Binder.restoreCallingIdentity(identity);
3386        }
3387
3388        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3389                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3390                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3391
3392        if ((flags & fixedFlags) != 0) {
3393            return false;
3394        }
3395
3396        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3397    }
3398
3399    @Override
3400    public boolean isProtectedBroadcast(String actionName) {
3401        synchronized (mPackages) {
3402            return mProtectedBroadcasts.contains(actionName);
3403        }
3404    }
3405
3406    @Override
3407    public int checkSignatures(String pkg1, String pkg2) {
3408        synchronized (mPackages) {
3409            final PackageParser.Package p1 = mPackages.get(pkg1);
3410            final PackageParser.Package p2 = mPackages.get(pkg2);
3411            if (p1 == null || p1.mExtras == null
3412                    || p2 == null || p2.mExtras == null) {
3413                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3414            }
3415            return compareSignatures(p1.mSignatures, p2.mSignatures);
3416        }
3417    }
3418
3419    @Override
3420    public int checkUidSignatures(int uid1, int uid2) {
3421        // Map to base uids.
3422        uid1 = UserHandle.getAppId(uid1);
3423        uid2 = UserHandle.getAppId(uid2);
3424        // reader
3425        synchronized (mPackages) {
3426            Signature[] s1;
3427            Signature[] s2;
3428            Object obj = mSettings.getUserIdLPr(uid1);
3429            if (obj != null) {
3430                if (obj instanceof SharedUserSetting) {
3431                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3432                } else if (obj instanceof PackageSetting) {
3433                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3434                } else {
3435                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3436                }
3437            } else {
3438                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3439            }
3440            obj = mSettings.getUserIdLPr(uid2);
3441            if (obj != null) {
3442                if (obj instanceof SharedUserSetting) {
3443                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3444                } else if (obj instanceof PackageSetting) {
3445                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3446                } else {
3447                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3448                }
3449            } else {
3450                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3451            }
3452            return compareSignatures(s1, s2);
3453        }
3454    }
3455
3456    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3457        final long identity = Binder.clearCallingIdentity();
3458        try {
3459            if (sb instanceof SharedUserSetting) {
3460                SharedUserSetting sus = (SharedUserSetting) sb;
3461                final int packageCount = sus.packages.size();
3462                for (int i = 0; i < packageCount; i++) {
3463                    PackageSetting susPs = sus.packages.valueAt(i);
3464                    if (userId == UserHandle.USER_ALL) {
3465                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3466                    } else {
3467                        final int uid = UserHandle.getUid(userId, susPs.appId);
3468                        killUid(uid, reason);
3469                    }
3470                }
3471            } else if (sb instanceof PackageSetting) {
3472                PackageSetting ps = (PackageSetting) sb;
3473                if (userId == UserHandle.USER_ALL) {
3474                    killApplication(ps.pkg.packageName, ps.appId, reason);
3475                } else {
3476                    final int uid = UserHandle.getUid(userId, ps.appId);
3477                    killUid(uid, reason);
3478                }
3479            }
3480        } finally {
3481            Binder.restoreCallingIdentity(identity);
3482        }
3483    }
3484
3485    private static void killUid(int uid, String reason) {
3486        IActivityManager am = ActivityManagerNative.getDefault();
3487        if (am != null) {
3488            try {
3489                am.killUid(uid, reason);
3490            } catch (RemoteException e) {
3491                /* ignore - same process */
3492            }
3493        }
3494    }
3495
3496    /**
3497     * Compares two sets of signatures. Returns:
3498     * <br />
3499     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3500     * <br />
3501     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3502     * <br />
3503     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3504     * <br />
3505     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3506     * <br />
3507     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3508     */
3509    static int compareSignatures(Signature[] s1, Signature[] s2) {
3510        if (s1 == null) {
3511            return s2 == null
3512                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3513                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3514        }
3515
3516        if (s2 == null) {
3517            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3518        }
3519
3520        if (s1.length != s2.length) {
3521            return PackageManager.SIGNATURE_NO_MATCH;
3522        }
3523
3524        // Since both signature sets are of size 1, we can compare without HashSets.
3525        if (s1.length == 1) {
3526            return s1[0].equals(s2[0]) ?
3527                    PackageManager.SIGNATURE_MATCH :
3528                    PackageManager.SIGNATURE_NO_MATCH;
3529        }
3530
3531        ArraySet<Signature> set1 = new ArraySet<Signature>();
3532        for (Signature sig : s1) {
3533            set1.add(sig);
3534        }
3535        ArraySet<Signature> set2 = new ArraySet<Signature>();
3536        for (Signature sig : s2) {
3537            set2.add(sig);
3538        }
3539        // Make sure s2 contains all signatures in s1.
3540        if (set1.equals(set2)) {
3541            return PackageManager.SIGNATURE_MATCH;
3542        }
3543        return PackageManager.SIGNATURE_NO_MATCH;
3544    }
3545
3546    /**
3547     * If the database version for this type of package (internal storage or
3548     * external storage) is less than the version where package signatures
3549     * were updated, return true.
3550     */
3551    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3552        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3553                DatabaseVersion.SIGNATURE_END_ENTITY))
3554                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3555                        DatabaseVersion.SIGNATURE_END_ENTITY));
3556    }
3557
3558    /**
3559     * Used for backward compatibility to make sure any packages with
3560     * certificate chains get upgraded to the new style. {@code existingSigs}
3561     * will be in the old format (since they were stored on disk from before the
3562     * system upgrade) and {@code scannedSigs} will be in the newer format.
3563     */
3564    private int compareSignaturesCompat(PackageSignatures existingSigs,
3565            PackageParser.Package scannedPkg) {
3566        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3567            return PackageManager.SIGNATURE_NO_MATCH;
3568        }
3569
3570        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3571        for (Signature sig : existingSigs.mSignatures) {
3572            existingSet.add(sig);
3573        }
3574        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3575        for (Signature sig : scannedPkg.mSignatures) {
3576            try {
3577                Signature[] chainSignatures = sig.getChainSignatures();
3578                for (Signature chainSig : chainSignatures) {
3579                    scannedCompatSet.add(chainSig);
3580                }
3581            } catch (CertificateEncodingException e) {
3582                scannedCompatSet.add(sig);
3583            }
3584        }
3585        /*
3586         * Make sure the expanded scanned set contains all signatures in the
3587         * existing one.
3588         */
3589        if (scannedCompatSet.equals(existingSet)) {
3590            // Migrate the old signatures to the new scheme.
3591            existingSigs.assignSignatures(scannedPkg.mSignatures);
3592            // The new KeySets will be re-added later in the scanning process.
3593            synchronized (mPackages) {
3594                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3595            }
3596            return PackageManager.SIGNATURE_MATCH;
3597        }
3598        return PackageManager.SIGNATURE_NO_MATCH;
3599    }
3600
3601    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3602        if (isExternal(scannedPkg)) {
3603            return mSettings.isExternalDatabaseVersionOlderThan(
3604                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3605        } else {
3606            return mSettings.isInternalDatabaseVersionOlderThan(
3607                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3608        }
3609    }
3610
3611    private int compareSignaturesRecover(PackageSignatures existingSigs,
3612            PackageParser.Package scannedPkg) {
3613        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3614            return PackageManager.SIGNATURE_NO_MATCH;
3615        }
3616
3617        String msg = null;
3618        try {
3619            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3620                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3621                        + scannedPkg.packageName);
3622                return PackageManager.SIGNATURE_MATCH;
3623            }
3624        } catch (CertificateException e) {
3625            msg = e.getMessage();
3626        }
3627
3628        logCriticalInfo(Log.INFO,
3629                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3630        return PackageManager.SIGNATURE_NO_MATCH;
3631    }
3632
3633    @Override
3634    public String[] getPackagesForUid(int uid) {
3635        uid = UserHandle.getAppId(uid);
3636        // reader
3637        synchronized (mPackages) {
3638            Object obj = mSettings.getUserIdLPr(uid);
3639            if (obj instanceof SharedUserSetting) {
3640                final SharedUserSetting sus = (SharedUserSetting) obj;
3641                final int N = sus.packages.size();
3642                final String[] res = new String[N];
3643                final Iterator<PackageSetting> it = sus.packages.iterator();
3644                int i = 0;
3645                while (it.hasNext()) {
3646                    res[i++] = it.next().name;
3647                }
3648                return res;
3649            } else if (obj instanceof PackageSetting) {
3650                final PackageSetting ps = (PackageSetting) obj;
3651                return new String[] { ps.name };
3652            }
3653        }
3654        return null;
3655    }
3656
3657    @Override
3658    public String getNameForUid(int uid) {
3659        // reader
3660        synchronized (mPackages) {
3661            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3662            if (obj instanceof SharedUserSetting) {
3663                final SharedUserSetting sus = (SharedUserSetting) obj;
3664                return sus.name + ":" + sus.userId;
3665            } else if (obj instanceof PackageSetting) {
3666                final PackageSetting ps = (PackageSetting) obj;
3667                return ps.name;
3668            }
3669        }
3670        return null;
3671    }
3672
3673    @Override
3674    public int getUidForSharedUser(String sharedUserName) {
3675        if(sharedUserName == null) {
3676            return -1;
3677        }
3678        // reader
3679        synchronized (mPackages) {
3680            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
3681            if (suid == null) {
3682                return -1;
3683            }
3684            return suid.userId;
3685        }
3686    }
3687
3688    @Override
3689    public int getFlagsForUid(int uid) {
3690        synchronized (mPackages) {
3691            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3692            if (obj instanceof SharedUserSetting) {
3693                final SharedUserSetting sus = (SharedUserSetting) obj;
3694                return sus.pkgFlags;
3695            } else if (obj instanceof PackageSetting) {
3696                final PackageSetting ps = (PackageSetting) obj;
3697                return ps.pkgFlags;
3698            }
3699        }
3700        return 0;
3701    }
3702
3703    @Override
3704    public int getPrivateFlagsForUid(int uid) {
3705        synchronized (mPackages) {
3706            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3707            if (obj instanceof SharedUserSetting) {
3708                final SharedUserSetting sus = (SharedUserSetting) obj;
3709                return sus.pkgPrivateFlags;
3710            } else if (obj instanceof PackageSetting) {
3711                final PackageSetting ps = (PackageSetting) obj;
3712                return ps.pkgPrivateFlags;
3713            }
3714        }
3715        return 0;
3716    }
3717
3718    @Override
3719    public boolean isUidPrivileged(int uid) {
3720        uid = UserHandle.getAppId(uid);
3721        // reader
3722        synchronized (mPackages) {
3723            Object obj = mSettings.getUserIdLPr(uid);
3724            if (obj instanceof SharedUserSetting) {
3725                final SharedUserSetting sus = (SharedUserSetting) obj;
3726                final Iterator<PackageSetting> it = sus.packages.iterator();
3727                while (it.hasNext()) {
3728                    if (it.next().isPrivileged()) {
3729                        return true;
3730                    }
3731                }
3732            } else if (obj instanceof PackageSetting) {
3733                final PackageSetting ps = (PackageSetting) obj;
3734                return ps.isPrivileged();
3735            }
3736        }
3737        return false;
3738    }
3739
3740    @Override
3741    public String[] getAppOpPermissionPackages(String permissionName) {
3742        synchronized (mPackages) {
3743            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
3744            if (pkgs == null) {
3745                return null;
3746            }
3747            return pkgs.toArray(new String[pkgs.size()]);
3748        }
3749    }
3750
3751    @Override
3752    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3753            int flags, int userId) {
3754        if (!sUserManager.exists(userId)) return null;
3755        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
3756        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3757        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3758    }
3759
3760    @Override
3761    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3762            IntentFilter filter, int match, ComponentName activity) {
3763        final int userId = UserHandle.getCallingUserId();
3764        if (DEBUG_PREFERRED) {
3765            Log.v(TAG, "setLastChosenActivity intent=" + intent
3766                + " resolvedType=" + resolvedType
3767                + " flags=" + flags
3768                + " filter=" + filter
3769                + " match=" + match
3770                + " activity=" + activity);
3771            filter.dump(new PrintStreamPrinter(System.out), "    ");
3772        }
3773        intent.setComponent(null);
3774        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3775        // Find any earlier preferred or last chosen entries and nuke them
3776        findPreferredActivity(intent, resolvedType,
3777                flags, query, 0, false, true, false, userId);
3778        // Add the new activity as the last chosen for this filter
3779        addPreferredActivityInternal(filter, match, null, activity, false, userId,
3780                "Setting last chosen");
3781    }
3782
3783    @Override
3784    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
3785        final int userId = UserHandle.getCallingUserId();
3786        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
3787        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3788        return findPreferredActivity(intent, resolvedType, flags, query, 0,
3789                false, false, false, userId);
3790    }
3791
3792    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
3793            int flags, List<ResolveInfo> query, int userId) {
3794        if (query != null) {
3795            final int N = query.size();
3796            if (N == 1) {
3797                return query.get(0);
3798            } else if (N > 1) {
3799                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3800                // If there is more than one activity with the same priority,
3801                // then let the user decide between them.
3802                ResolveInfo r0 = query.get(0);
3803                ResolveInfo r1 = query.get(1);
3804                if (DEBUG_INTENT_MATCHING || debug) {
3805                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
3806                            + r1.activityInfo.name + "=" + r1.priority);
3807                }
3808                // If the first activity has a higher priority, or a different
3809                // default, then it is always desireable to pick it.
3810                if (r0.priority != r1.priority
3811                        || r0.preferredOrder != r1.preferredOrder
3812                        || r0.isDefault != r1.isDefault) {
3813                    return query.get(0);
3814                }
3815                // If we have saved a preference for a preferred activity for
3816                // this Intent, use that.
3817                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3818                        flags, query, r0.priority, true, false, debug, userId);
3819                if (ri != null) {
3820                    return ri;
3821                }
3822                if (userId != 0) {
3823                    ri = new ResolveInfo(mResolveInfo);
3824                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3825                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3826                            ri.activityInfo.applicationInfo);
3827                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3828                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3829                    return ri;
3830                }
3831                return mResolveInfo;
3832            }
3833        }
3834        return null;
3835    }
3836
3837    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3838            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3839        final int N = query.size();
3840        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3841                .get(userId);
3842        // Get the list of persistent preferred activities that handle the intent
3843        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3844        List<PersistentPreferredActivity> pprefs = ppir != null
3845                ? ppir.queryIntent(intent, resolvedType,
3846                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3847                : null;
3848        if (pprefs != null && pprefs.size() > 0) {
3849            final int M = pprefs.size();
3850            for (int i=0; i<M; i++) {
3851                final PersistentPreferredActivity ppa = pprefs.get(i);
3852                if (DEBUG_PREFERRED || debug) {
3853                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3854                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3855                            + "\n  component=" + ppa.mComponent);
3856                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3857                }
3858                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3859                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3860                if (DEBUG_PREFERRED || debug) {
3861                    Slog.v(TAG, "Found persistent preferred activity:");
3862                    if (ai != null) {
3863                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3864                    } else {
3865                        Slog.v(TAG, "  null");
3866                    }
3867                }
3868                if (ai == null) {
3869                    // This previously registered persistent preferred activity
3870                    // component is no longer known. Ignore it and do NOT remove it.
3871                    continue;
3872                }
3873                for (int j=0; j<N; j++) {
3874                    final ResolveInfo ri = query.get(j);
3875                    if (!ri.activityInfo.applicationInfo.packageName
3876                            .equals(ai.applicationInfo.packageName)) {
3877                        continue;
3878                    }
3879                    if (!ri.activityInfo.name.equals(ai.name)) {
3880                        continue;
3881                    }
3882                    //  Found a persistent preference that can handle the intent.
3883                    if (DEBUG_PREFERRED || debug) {
3884                        Slog.v(TAG, "Returning persistent preferred activity: " +
3885                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3886                    }
3887                    return ri;
3888                }
3889            }
3890        }
3891        return null;
3892    }
3893
3894    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3895            List<ResolveInfo> query, int priority, boolean always,
3896            boolean removeMatches, boolean debug, int userId) {
3897        if (!sUserManager.exists(userId)) return null;
3898        // writer
3899        synchronized (mPackages) {
3900            if (intent.getSelector() != null) {
3901                intent = intent.getSelector();
3902            }
3903            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3904
3905            // Try to find a matching persistent preferred activity.
3906            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3907                    debug, userId);
3908
3909            // If a persistent preferred activity matched, use it.
3910            if (pri != null) {
3911                return pri;
3912            }
3913
3914            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3915            // Get the list of preferred activities that handle the intent
3916            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3917            List<PreferredActivity> prefs = pir != null
3918                    ? pir.queryIntent(intent, resolvedType,
3919                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3920                    : null;
3921            if (prefs != null && prefs.size() > 0) {
3922                boolean changed = false;
3923                try {
3924                    // First figure out how good the original match set is.
3925                    // We will only allow preferred activities that came
3926                    // from the same match quality.
3927                    int match = 0;
3928
3929                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3930
3931                    final int N = query.size();
3932                    for (int j=0; j<N; j++) {
3933                        final ResolveInfo ri = query.get(j);
3934                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3935                                + ": 0x" + Integer.toHexString(match));
3936                        if (ri.match > match) {
3937                            match = ri.match;
3938                        }
3939                    }
3940
3941                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3942                            + Integer.toHexString(match));
3943
3944                    match &= IntentFilter.MATCH_CATEGORY_MASK;
3945                    final int M = prefs.size();
3946                    for (int i=0; i<M; i++) {
3947                        final PreferredActivity pa = prefs.get(i);
3948                        if (DEBUG_PREFERRED || debug) {
3949                            Slog.v(TAG, "Checking PreferredActivity ds="
3950                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3951                                    + "\n  component=" + pa.mPref.mComponent);
3952                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3953                        }
3954                        if (pa.mPref.mMatch != match) {
3955                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3956                                    + Integer.toHexString(pa.mPref.mMatch));
3957                            continue;
3958                        }
3959                        // If it's not an "always" type preferred activity and that's what we're
3960                        // looking for, skip it.
3961                        if (always && !pa.mPref.mAlways) {
3962                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3963                            continue;
3964                        }
3965                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3966                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3967                        if (DEBUG_PREFERRED || debug) {
3968                            Slog.v(TAG, "Found preferred activity:");
3969                            if (ai != null) {
3970                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3971                            } else {
3972                                Slog.v(TAG, "  null");
3973                            }
3974                        }
3975                        if (ai == null) {
3976                            // This previously registered preferred activity
3977                            // component is no longer known.  Most likely an update
3978                            // to the app was installed and in the new version this
3979                            // component no longer exists.  Clean it up by removing
3980                            // it from the preferred activities list, and skip it.
3981                            Slog.w(TAG, "Removing dangling preferred activity: "
3982                                    + pa.mPref.mComponent);
3983                            pir.removeFilter(pa);
3984                            changed = true;
3985                            continue;
3986                        }
3987                        for (int j=0; j<N; j++) {
3988                            final ResolveInfo ri = query.get(j);
3989                            if (!ri.activityInfo.applicationInfo.packageName
3990                                    .equals(ai.applicationInfo.packageName)) {
3991                                continue;
3992                            }
3993                            if (!ri.activityInfo.name.equals(ai.name)) {
3994                                continue;
3995                            }
3996
3997                            if (removeMatches) {
3998                                pir.removeFilter(pa);
3999                                changed = true;
4000                                if (DEBUG_PREFERRED) {
4001                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4002                                }
4003                                break;
4004                            }
4005
4006                            // Okay we found a previously set preferred or last chosen app.
4007                            // If the result set is different from when this
4008                            // was created, we need to clear it and re-ask the
4009                            // user their preference, if we're looking for an "always" type entry.
4010                            if (always && !pa.mPref.sameSet(query)) {
4011                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4012                                        + intent + " type " + resolvedType);
4013                                if (DEBUG_PREFERRED) {
4014                                    Slog.v(TAG, "Removing preferred activity since set changed "
4015                                            + pa.mPref.mComponent);
4016                                }
4017                                pir.removeFilter(pa);
4018                                // Re-add the filter as a "last chosen" entry (!always)
4019                                PreferredActivity lastChosen = new PreferredActivity(
4020                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4021                                pir.addFilter(lastChosen);
4022                                changed = true;
4023                                return null;
4024                            }
4025
4026                            // Yay! Either the set matched or we're looking for the last chosen
4027                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4028                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4029                            return ri;
4030                        }
4031                    }
4032                } finally {
4033                    if (changed) {
4034                        if (DEBUG_PREFERRED) {
4035                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4036                        }
4037                        scheduleWritePackageRestrictionsLocked(userId);
4038                    }
4039                }
4040            }
4041        }
4042        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4043        return null;
4044    }
4045
4046    /*
4047     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4048     */
4049    @Override
4050    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4051            int targetUserId) {
4052        mContext.enforceCallingOrSelfPermission(
4053                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4054        List<CrossProfileIntentFilter> matches =
4055                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4056        if (matches != null) {
4057            int size = matches.size();
4058            for (int i = 0; i < size; i++) {
4059                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4060            }
4061        }
4062        return false;
4063    }
4064
4065    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4066            String resolvedType, int userId) {
4067        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4068        if (resolver != null) {
4069            return resolver.queryIntent(intent, resolvedType, false, userId);
4070        }
4071        return null;
4072    }
4073
4074    @Override
4075    public List<ResolveInfo> queryIntentActivities(Intent intent,
4076            String resolvedType, int flags, int userId) {
4077        if (!sUserManager.exists(userId)) return Collections.emptyList();
4078        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4079        ComponentName comp = intent.getComponent();
4080        if (comp == null) {
4081            if (intent.getSelector() != null) {
4082                intent = intent.getSelector();
4083                comp = intent.getComponent();
4084            }
4085        }
4086
4087        if (comp != null) {
4088            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4089            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4090            if (ai != null) {
4091                final ResolveInfo ri = new ResolveInfo();
4092                ri.activityInfo = ai;
4093                list.add(ri);
4094            }
4095            return list;
4096        }
4097
4098        // reader
4099        synchronized (mPackages) {
4100            final String pkgName = intent.getPackage();
4101            if (pkgName == null) {
4102                List<CrossProfileIntentFilter> matchingFilters =
4103                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4104                // Check for results that need to skip the current profile.
4105                ResolveInfo resolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4106                        resolvedType, flags, userId);
4107                if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) {
4108                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4109                    result.add(resolveInfo);
4110                    return filterIfNotPrimaryUser(result, userId);
4111                }
4112
4113                // Check for results in the current profile.
4114                List<ResolveInfo> result = mActivities.queryIntent(
4115                        intent, resolvedType, flags, userId);
4116
4117                // Check for cross profile results.
4118                resolveInfo = queryCrossProfileIntents(
4119                        matchingFilters, intent, resolvedType, flags, userId);
4120                if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) {
4121                    result.add(resolveInfo);
4122                    Collections.sort(result, mResolvePrioritySorter);
4123                }
4124                result = filterIfNotPrimaryUser(result, userId);
4125                if (result.size() > 1 && hasWebURI(intent)) {
4126                    return filterCandidatesWithDomainPreferedActivitiesLPr(flags, result);
4127                }
4128                return result;
4129            }
4130            final PackageParser.Package pkg = mPackages.get(pkgName);
4131            if (pkg != null) {
4132                return filterIfNotPrimaryUser(
4133                        mActivities.queryIntentForPackage(
4134                                intent, resolvedType, flags, pkg.activities, userId),
4135                        userId);
4136            }
4137            return new ArrayList<ResolveInfo>();
4138        }
4139    }
4140
4141    private boolean isUserEnabled(int userId) {
4142        long callingId = Binder.clearCallingIdentity();
4143        try {
4144            UserInfo userInfo = sUserManager.getUserInfo(userId);
4145            return userInfo != null && userInfo.isEnabled();
4146        } finally {
4147            Binder.restoreCallingIdentity(callingId);
4148        }
4149    }
4150
4151    /**
4152     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4153     *
4154     * @return filtered list
4155     */
4156    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4157        if (userId == UserHandle.USER_OWNER) {
4158            return resolveInfos;
4159        }
4160        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4161            ResolveInfo info = resolveInfos.get(i);
4162            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4163                resolveInfos.remove(i);
4164            }
4165        }
4166        return resolveInfos;
4167    }
4168
4169    private static boolean hasWebURI(Intent intent) {
4170        if (intent.getData() == null) {
4171            return false;
4172        }
4173        final String scheme = intent.getScheme();
4174        if (TextUtils.isEmpty(scheme)) {
4175            return false;
4176        }
4177        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4178    }
4179
4180    private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPr(
4181            int flags, List<ResolveInfo> candidates) {
4182        if (DEBUG_PREFERRED) {
4183            Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " +
4184                    candidates.size());
4185        }
4186
4187        final int userId = UserHandle.getCallingUserId();
4188        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4189        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4190        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4191        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4192        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4193
4194        synchronized (mPackages) {
4195            final int count = candidates.size();
4196            // First, try to use the domain prefered App. Partition the candidates into four lists:
4197            // one for the final results, one for the "do not use ever", one for "undefined status"
4198            // and finally one for "Browser App type".
4199            for (int n=0; n<count; n++) {
4200                ResolveInfo info = candidates.get(n);
4201                String packageName = info.activityInfo.packageName;
4202                PackageSetting ps = mSettings.mPackages.get(packageName);
4203                if (ps != null) {
4204                    // Add to the special match all list (Browser use case)
4205                    if (info.handleAllWebDataURI) {
4206                        matchAllList.add(info);
4207                        continue;
4208                    }
4209                    // Try to get the status from User settings first
4210                    int status = getDomainVerificationStatusLPr(ps, userId);
4211                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4212                        alwaysList.add(info);
4213                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4214                        neverList.add(info);
4215                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4216                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4217                        undefinedList.add(info);
4218                    }
4219                }
4220            }
4221            // First try to add the "always" if there is any
4222            if (alwaysList.size() > 0) {
4223                result.addAll(alwaysList);
4224            } else {
4225                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4226                result.addAll(undefinedList);
4227                // Also add Browsers (all of them or only the default one)
4228                if ((flags & MATCH_ALL) != 0) {
4229                    result.addAll(matchAllList);
4230                } else {
4231                    // Try to add the Default Browser if we can
4232                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(
4233                            UserHandle.myUserId());
4234                    if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
4235                        boolean defaultBrowserFound = false;
4236                        final int browserCount = matchAllList.size();
4237                        for (int n=0; n<browserCount; n++) {
4238                            ResolveInfo browser = matchAllList.get(n);
4239                            if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4240                                result.add(browser);
4241                                defaultBrowserFound = true;
4242                                break;
4243                            }
4244                        }
4245                        if (!defaultBrowserFound) {
4246                            result.addAll(matchAllList);
4247                        }
4248                    } else {
4249                        result.addAll(matchAllList);
4250                    }
4251                }
4252
4253                // If there is nothing selected, add all candidates and remove the ones that the User
4254                // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4255                if (result.size() == 0) {
4256                    result.addAll(candidates);
4257                    result.removeAll(neverList);
4258                }
4259            }
4260        }
4261        if (DEBUG_PREFERRED) {
4262            Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " +
4263                    result.size());
4264        }
4265        return result;
4266    }
4267
4268    private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4269        int status = ps.getDomainVerificationStatusForUser(userId);
4270        // if none available, get the master status
4271        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4272            if (ps.getIntentFilterVerificationInfo() != null) {
4273                status = ps.getIntentFilterVerificationInfo().getStatus();
4274            }
4275        }
4276        return status;
4277    }
4278
4279    private ResolveInfo querySkipCurrentProfileIntents(
4280            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4281            int flags, int sourceUserId) {
4282        if (matchingFilters != null) {
4283            int size = matchingFilters.size();
4284            for (int i = 0; i < size; i ++) {
4285                CrossProfileIntentFilter filter = matchingFilters.get(i);
4286                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4287                    // Checking if there are activities in the target user that can handle the
4288                    // intent.
4289                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4290                            flags, sourceUserId);
4291                    if (resolveInfo != null) {
4292                        return resolveInfo;
4293                    }
4294                }
4295            }
4296        }
4297        return null;
4298    }
4299
4300    // Return matching ResolveInfo if any for skip current profile intent filters.
4301    private ResolveInfo queryCrossProfileIntents(
4302            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4303            int flags, int sourceUserId) {
4304        if (matchingFilters != null) {
4305            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4306            // match the same intent. For performance reasons, it is better not to
4307            // run queryIntent twice for the same userId
4308            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4309            int size = matchingFilters.size();
4310            for (int i = 0; i < size; i++) {
4311                CrossProfileIntentFilter filter = matchingFilters.get(i);
4312                int targetUserId = filter.getTargetUserId();
4313                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4314                        && !alreadyTriedUserIds.get(targetUserId)) {
4315                    // Checking if there are activities in the target user that can handle the
4316                    // intent.
4317                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4318                            flags, sourceUserId);
4319                    if (resolveInfo != null) return resolveInfo;
4320                    alreadyTriedUserIds.put(targetUserId, true);
4321                }
4322            }
4323        }
4324        return null;
4325    }
4326
4327    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4328            String resolvedType, int flags, int sourceUserId) {
4329        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4330                resolvedType, flags, filter.getTargetUserId());
4331        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4332            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4333        }
4334        return null;
4335    }
4336
4337    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4338            int sourceUserId, int targetUserId) {
4339        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4340        String className;
4341        if (targetUserId == UserHandle.USER_OWNER) {
4342            className = FORWARD_INTENT_TO_USER_OWNER;
4343        } else {
4344            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4345        }
4346        ComponentName forwardingActivityComponentName = new ComponentName(
4347                mAndroidApplication.packageName, className);
4348        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4349                sourceUserId);
4350        if (targetUserId == UserHandle.USER_OWNER) {
4351            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4352            forwardingResolveInfo.noResourceId = true;
4353        }
4354        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4355        forwardingResolveInfo.priority = 0;
4356        forwardingResolveInfo.preferredOrder = 0;
4357        forwardingResolveInfo.match = 0;
4358        forwardingResolveInfo.isDefault = true;
4359        forwardingResolveInfo.filter = filter;
4360        forwardingResolveInfo.targetUserId = targetUserId;
4361        return forwardingResolveInfo;
4362    }
4363
4364    @Override
4365    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4366            Intent[] specifics, String[] specificTypes, Intent intent,
4367            String resolvedType, int flags, int userId) {
4368        if (!sUserManager.exists(userId)) return Collections.emptyList();
4369        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4370                false, "query intent activity options");
4371        final String resultsAction = intent.getAction();
4372
4373        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4374                | PackageManager.GET_RESOLVED_FILTER, userId);
4375
4376        if (DEBUG_INTENT_MATCHING) {
4377            Log.v(TAG, "Query " + intent + ": " + results);
4378        }
4379
4380        int specificsPos = 0;
4381        int N;
4382
4383        // todo: note that the algorithm used here is O(N^2).  This
4384        // isn't a problem in our current environment, but if we start running
4385        // into situations where we have more than 5 or 10 matches then this
4386        // should probably be changed to something smarter...
4387
4388        // First we go through and resolve each of the specific items
4389        // that were supplied, taking care of removing any corresponding
4390        // duplicate items in the generic resolve list.
4391        if (specifics != null) {
4392            for (int i=0; i<specifics.length; i++) {
4393                final Intent sintent = specifics[i];
4394                if (sintent == null) {
4395                    continue;
4396                }
4397
4398                if (DEBUG_INTENT_MATCHING) {
4399                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4400                }
4401
4402                String action = sintent.getAction();
4403                if (resultsAction != null && resultsAction.equals(action)) {
4404                    // If this action was explicitly requested, then don't
4405                    // remove things that have it.
4406                    action = null;
4407                }
4408
4409                ResolveInfo ri = null;
4410                ActivityInfo ai = null;
4411
4412                ComponentName comp = sintent.getComponent();
4413                if (comp == null) {
4414                    ri = resolveIntent(
4415                        sintent,
4416                        specificTypes != null ? specificTypes[i] : null,
4417                            flags, userId);
4418                    if (ri == null) {
4419                        continue;
4420                    }
4421                    if (ri == mResolveInfo) {
4422                        // ACK!  Must do something better with this.
4423                    }
4424                    ai = ri.activityInfo;
4425                    comp = new ComponentName(ai.applicationInfo.packageName,
4426                            ai.name);
4427                } else {
4428                    ai = getActivityInfo(comp, flags, userId);
4429                    if (ai == null) {
4430                        continue;
4431                    }
4432                }
4433
4434                // Look for any generic query activities that are duplicates
4435                // of this specific one, and remove them from the results.
4436                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4437                N = results.size();
4438                int j;
4439                for (j=specificsPos; j<N; j++) {
4440                    ResolveInfo sri = results.get(j);
4441                    if ((sri.activityInfo.name.equals(comp.getClassName())
4442                            && sri.activityInfo.applicationInfo.packageName.equals(
4443                                    comp.getPackageName()))
4444                        || (action != null && sri.filter.matchAction(action))) {
4445                        results.remove(j);
4446                        if (DEBUG_INTENT_MATCHING) Log.v(
4447                            TAG, "Removing duplicate item from " + j
4448                            + " due to specific " + specificsPos);
4449                        if (ri == null) {
4450                            ri = sri;
4451                        }
4452                        j--;
4453                        N--;
4454                    }
4455                }
4456
4457                // Add this specific item to its proper place.
4458                if (ri == null) {
4459                    ri = new ResolveInfo();
4460                    ri.activityInfo = ai;
4461                }
4462                results.add(specificsPos, ri);
4463                ri.specificIndex = i;
4464                specificsPos++;
4465            }
4466        }
4467
4468        // Now we go through the remaining generic results and remove any
4469        // duplicate actions that are found here.
4470        N = results.size();
4471        for (int i=specificsPos; i<N-1; i++) {
4472            final ResolveInfo rii = results.get(i);
4473            if (rii.filter == null) {
4474                continue;
4475            }
4476
4477            // Iterate over all of the actions of this result's intent
4478            // filter...  typically this should be just one.
4479            final Iterator<String> it = rii.filter.actionsIterator();
4480            if (it == null) {
4481                continue;
4482            }
4483            while (it.hasNext()) {
4484                final String action = it.next();
4485                if (resultsAction != null && resultsAction.equals(action)) {
4486                    // If this action was explicitly requested, then don't
4487                    // remove things that have it.
4488                    continue;
4489                }
4490                for (int j=i+1; j<N; j++) {
4491                    final ResolveInfo rij = results.get(j);
4492                    if (rij.filter != null && rij.filter.hasAction(action)) {
4493                        results.remove(j);
4494                        if (DEBUG_INTENT_MATCHING) Log.v(
4495                            TAG, "Removing duplicate item from " + j
4496                            + " due to action " + action + " at " + i);
4497                        j--;
4498                        N--;
4499                    }
4500                }
4501            }
4502
4503            // If the caller didn't request filter information, drop it now
4504            // so we don't have to marshall/unmarshall it.
4505            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4506                rii.filter = null;
4507            }
4508        }
4509
4510        // Filter out the caller activity if so requested.
4511        if (caller != null) {
4512            N = results.size();
4513            for (int i=0; i<N; i++) {
4514                ActivityInfo ainfo = results.get(i).activityInfo;
4515                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
4516                        && caller.getClassName().equals(ainfo.name)) {
4517                    results.remove(i);
4518                    break;
4519                }
4520            }
4521        }
4522
4523        // If the caller didn't request filter information,
4524        // drop them now so we don't have to
4525        // marshall/unmarshall it.
4526        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4527            N = results.size();
4528            for (int i=0; i<N; i++) {
4529                results.get(i).filter = null;
4530            }
4531        }
4532
4533        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
4534        return results;
4535    }
4536
4537    @Override
4538    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
4539            int userId) {
4540        if (!sUserManager.exists(userId)) return Collections.emptyList();
4541        ComponentName comp = intent.getComponent();
4542        if (comp == null) {
4543            if (intent.getSelector() != null) {
4544                intent = intent.getSelector();
4545                comp = intent.getComponent();
4546            }
4547        }
4548        if (comp != null) {
4549            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4550            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
4551            if (ai != null) {
4552                ResolveInfo ri = new ResolveInfo();
4553                ri.activityInfo = ai;
4554                list.add(ri);
4555            }
4556            return list;
4557        }
4558
4559        // reader
4560        synchronized (mPackages) {
4561            String pkgName = intent.getPackage();
4562            if (pkgName == null) {
4563                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
4564            }
4565            final PackageParser.Package pkg = mPackages.get(pkgName);
4566            if (pkg != null) {
4567                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
4568                        userId);
4569            }
4570            return null;
4571        }
4572    }
4573
4574    @Override
4575    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
4576        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
4577        if (!sUserManager.exists(userId)) return null;
4578        if (query != null) {
4579            if (query.size() >= 1) {
4580                // If there is more than one service with the same priority,
4581                // just arbitrarily pick the first one.
4582                return query.get(0);
4583            }
4584        }
4585        return null;
4586    }
4587
4588    @Override
4589    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
4590            int userId) {
4591        if (!sUserManager.exists(userId)) return Collections.emptyList();
4592        ComponentName comp = intent.getComponent();
4593        if (comp == null) {
4594            if (intent.getSelector() != null) {
4595                intent = intent.getSelector();
4596                comp = intent.getComponent();
4597            }
4598        }
4599        if (comp != null) {
4600            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4601            final ServiceInfo si = getServiceInfo(comp, flags, userId);
4602            if (si != null) {
4603                final ResolveInfo ri = new ResolveInfo();
4604                ri.serviceInfo = si;
4605                list.add(ri);
4606            }
4607            return list;
4608        }
4609
4610        // reader
4611        synchronized (mPackages) {
4612            String pkgName = intent.getPackage();
4613            if (pkgName == null) {
4614                return mServices.queryIntent(intent, resolvedType, flags, userId);
4615            }
4616            final PackageParser.Package pkg = mPackages.get(pkgName);
4617            if (pkg != null) {
4618                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
4619                        userId);
4620            }
4621            return null;
4622        }
4623    }
4624
4625    @Override
4626    public List<ResolveInfo> queryIntentContentProviders(
4627            Intent intent, String resolvedType, int flags, int userId) {
4628        if (!sUserManager.exists(userId)) return Collections.emptyList();
4629        ComponentName comp = intent.getComponent();
4630        if (comp == null) {
4631            if (intent.getSelector() != null) {
4632                intent = intent.getSelector();
4633                comp = intent.getComponent();
4634            }
4635        }
4636        if (comp != null) {
4637            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4638            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
4639            if (pi != null) {
4640                final ResolveInfo ri = new ResolveInfo();
4641                ri.providerInfo = pi;
4642                list.add(ri);
4643            }
4644            return list;
4645        }
4646
4647        // reader
4648        synchronized (mPackages) {
4649            String pkgName = intent.getPackage();
4650            if (pkgName == null) {
4651                return mProviders.queryIntent(intent, resolvedType, flags, userId);
4652            }
4653            final PackageParser.Package pkg = mPackages.get(pkgName);
4654            if (pkg != null) {
4655                return mProviders.queryIntentForPackage(
4656                        intent, resolvedType, flags, pkg.providers, userId);
4657            }
4658            return null;
4659        }
4660    }
4661
4662    @Override
4663    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
4664        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4665
4666        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
4667
4668        // writer
4669        synchronized (mPackages) {
4670            ArrayList<PackageInfo> list;
4671            if (listUninstalled) {
4672                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
4673                for (PackageSetting ps : mSettings.mPackages.values()) {
4674                    PackageInfo pi;
4675                    if (ps.pkg != null) {
4676                        pi = generatePackageInfo(ps.pkg, flags, userId);
4677                    } else {
4678                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4679                    }
4680                    if (pi != null) {
4681                        list.add(pi);
4682                    }
4683                }
4684            } else {
4685                list = new ArrayList<PackageInfo>(mPackages.size());
4686                for (PackageParser.Package p : mPackages.values()) {
4687                    PackageInfo pi = generatePackageInfo(p, flags, userId);
4688                    if (pi != null) {
4689                        list.add(pi);
4690                    }
4691                }
4692            }
4693
4694            return new ParceledListSlice<PackageInfo>(list);
4695        }
4696    }
4697
4698    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
4699            String[] permissions, boolean[] tmp, int flags, int userId) {
4700        int numMatch = 0;
4701        final PermissionsState permissionsState = ps.getPermissionsState();
4702        for (int i=0; i<permissions.length; i++) {
4703            final String permission = permissions[i];
4704            if (permissionsState.hasPermission(permission, userId)) {
4705                tmp[i] = true;
4706                numMatch++;
4707            } else {
4708                tmp[i] = false;
4709            }
4710        }
4711        if (numMatch == 0) {
4712            return;
4713        }
4714        PackageInfo pi;
4715        if (ps.pkg != null) {
4716            pi = generatePackageInfo(ps.pkg, flags, userId);
4717        } else {
4718            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4719        }
4720        // The above might return null in cases of uninstalled apps or install-state
4721        // skew across users/profiles.
4722        if (pi != null) {
4723            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
4724                if (numMatch == permissions.length) {
4725                    pi.requestedPermissions = permissions;
4726                } else {
4727                    pi.requestedPermissions = new String[numMatch];
4728                    numMatch = 0;
4729                    for (int i=0; i<permissions.length; i++) {
4730                        if (tmp[i]) {
4731                            pi.requestedPermissions[numMatch] = permissions[i];
4732                            numMatch++;
4733                        }
4734                    }
4735                }
4736            }
4737            list.add(pi);
4738        }
4739    }
4740
4741    @Override
4742    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
4743            String[] permissions, int flags, int userId) {
4744        if (!sUserManager.exists(userId)) return null;
4745        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4746
4747        // writer
4748        synchronized (mPackages) {
4749            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
4750            boolean[] tmpBools = new boolean[permissions.length];
4751            if (listUninstalled) {
4752                for (PackageSetting ps : mSettings.mPackages.values()) {
4753                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
4754                }
4755            } else {
4756                for (PackageParser.Package pkg : mPackages.values()) {
4757                    PackageSetting ps = (PackageSetting)pkg.mExtras;
4758                    if (ps != null) {
4759                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
4760                                userId);
4761                    }
4762                }
4763            }
4764
4765            return new ParceledListSlice<PackageInfo>(list);
4766        }
4767    }
4768
4769    @Override
4770    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
4771        if (!sUserManager.exists(userId)) return null;
4772        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4773
4774        // writer
4775        synchronized (mPackages) {
4776            ArrayList<ApplicationInfo> list;
4777            if (listUninstalled) {
4778                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
4779                for (PackageSetting ps : mSettings.mPackages.values()) {
4780                    ApplicationInfo ai;
4781                    if (ps.pkg != null) {
4782                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4783                                ps.readUserState(userId), userId);
4784                    } else {
4785                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
4786                    }
4787                    if (ai != null) {
4788                        list.add(ai);
4789                    }
4790                }
4791            } else {
4792                list = new ArrayList<ApplicationInfo>(mPackages.size());
4793                for (PackageParser.Package p : mPackages.values()) {
4794                    if (p.mExtras != null) {
4795                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4796                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
4797                        if (ai != null) {
4798                            list.add(ai);
4799                        }
4800                    }
4801                }
4802            }
4803
4804            return new ParceledListSlice<ApplicationInfo>(list);
4805        }
4806    }
4807
4808    public List<ApplicationInfo> getPersistentApplications(int flags) {
4809        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
4810
4811        // reader
4812        synchronized (mPackages) {
4813            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
4814            final int userId = UserHandle.getCallingUserId();
4815            while (i.hasNext()) {
4816                final PackageParser.Package p = i.next();
4817                if (p.applicationInfo != null
4818                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
4819                        && (!mSafeMode || isSystemApp(p))) {
4820                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
4821                    if (ps != null) {
4822                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4823                                ps.readUserState(userId), userId);
4824                        if (ai != null) {
4825                            finalList.add(ai);
4826                        }
4827                    }
4828                }
4829            }
4830        }
4831
4832        return finalList;
4833    }
4834
4835    @Override
4836    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
4837        if (!sUserManager.exists(userId)) return null;
4838        // reader
4839        synchronized (mPackages) {
4840            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
4841            PackageSetting ps = provider != null
4842                    ? mSettings.mPackages.get(provider.owner.packageName)
4843                    : null;
4844            return ps != null
4845                    && mSettings.isEnabledLPr(provider.info, flags, userId)
4846                    && (!mSafeMode || (provider.info.applicationInfo.flags
4847                            &ApplicationInfo.FLAG_SYSTEM) != 0)
4848                    ? PackageParser.generateProviderInfo(provider, flags,
4849                            ps.readUserState(userId), userId)
4850                    : null;
4851        }
4852    }
4853
4854    /**
4855     * @deprecated
4856     */
4857    @Deprecated
4858    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
4859        // reader
4860        synchronized (mPackages) {
4861            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
4862                    .entrySet().iterator();
4863            final int userId = UserHandle.getCallingUserId();
4864            while (i.hasNext()) {
4865                Map.Entry<String, PackageParser.Provider> entry = i.next();
4866                PackageParser.Provider p = entry.getValue();
4867                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4868
4869                if (ps != null && p.syncable
4870                        && (!mSafeMode || (p.info.applicationInfo.flags
4871                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
4872                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
4873                            ps.readUserState(userId), userId);
4874                    if (info != null) {
4875                        outNames.add(entry.getKey());
4876                        outInfo.add(info);
4877                    }
4878                }
4879            }
4880        }
4881    }
4882
4883    @Override
4884    public List<ProviderInfo> queryContentProviders(String processName,
4885            int uid, int flags) {
4886        ArrayList<ProviderInfo> finalList = null;
4887        // reader
4888        synchronized (mPackages) {
4889            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
4890            final int userId = processName != null ?
4891                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
4892            while (i.hasNext()) {
4893                final PackageParser.Provider p = i.next();
4894                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4895                if (ps != null && p.info.authority != null
4896                        && (processName == null
4897                                || (p.info.processName.equals(processName)
4898                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
4899                        && mSettings.isEnabledLPr(p.info, flags, userId)
4900                        && (!mSafeMode
4901                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
4902                    if (finalList == null) {
4903                        finalList = new ArrayList<ProviderInfo>(3);
4904                    }
4905                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
4906                            ps.readUserState(userId), userId);
4907                    if (info != null) {
4908                        finalList.add(info);
4909                    }
4910                }
4911            }
4912        }
4913
4914        if (finalList != null) {
4915            Collections.sort(finalList, mProviderInitOrderSorter);
4916        }
4917
4918        return finalList;
4919    }
4920
4921    @Override
4922    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
4923            int flags) {
4924        // reader
4925        synchronized (mPackages) {
4926            final PackageParser.Instrumentation i = mInstrumentation.get(name);
4927            return PackageParser.generateInstrumentationInfo(i, flags);
4928        }
4929    }
4930
4931    @Override
4932    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4933            int flags) {
4934        ArrayList<InstrumentationInfo> finalList =
4935            new ArrayList<InstrumentationInfo>();
4936
4937        // reader
4938        synchronized (mPackages) {
4939            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4940            while (i.hasNext()) {
4941                final PackageParser.Instrumentation p = i.next();
4942                if (targetPackage == null
4943                        || targetPackage.equals(p.info.targetPackage)) {
4944                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4945                            flags);
4946                    if (ii != null) {
4947                        finalList.add(ii);
4948                    }
4949                }
4950            }
4951        }
4952
4953        return finalList;
4954    }
4955
4956    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4957        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4958        if (overlays == null) {
4959            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4960            return;
4961        }
4962        for (PackageParser.Package opkg : overlays.values()) {
4963            // Not much to do if idmap fails: we already logged the error
4964            // and we certainly don't want to abort installation of pkg simply
4965            // because an overlay didn't fit properly. For these reasons,
4966            // ignore the return value of createIdmapForPackagePairLI.
4967            createIdmapForPackagePairLI(pkg, opkg);
4968        }
4969    }
4970
4971    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4972            PackageParser.Package opkg) {
4973        if (!opkg.mTrustedOverlay) {
4974            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
4975                    opkg.baseCodePath + ": overlay not trusted");
4976            return false;
4977        }
4978        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4979        if (overlaySet == null) {
4980            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
4981                    opkg.baseCodePath + " but target package has no known overlays");
4982            return false;
4983        }
4984        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4985        // TODO: generate idmap for split APKs
4986        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
4987            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
4988                    + opkg.baseCodePath);
4989            return false;
4990        }
4991        PackageParser.Package[] overlayArray =
4992            overlaySet.values().toArray(new PackageParser.Package[0]);
4993        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4994            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4995                return p1.mOverlayPriority - p2.mOverlayPriority;
4996            }
4997        };
4998        Arrays.sort(overlayArray, cmp);
4999
5000        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5001        int i = 0;
5002        for (PackageParser.Package p : overlayArray) {
5003            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5004        }
5005        return true;
5006    }
5007
5008    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5009        final File[] files = dir.listFiles();
5010        if (ArrayUtils.isEmpty(files)) {
5011            Log.d(TAG, "No files in app dir " + dir);
5012            return;
5013        }
5014
5015        if (DEBUG_PACKAGE_SCANNING) {
5016            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5017                    + " flags=0x" + Integer.toHexString(parseFlags));
5018        }
5019
5020        for (File file : files) {
5021            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5022                    && !PackageInstallerService.isStageName(file.getName());
5023            if (!isPackage) {
5024                // Ignore entries which are not packages
5025                continue;
5026            }
5027            try {
5028                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5029                        scanFlags, currentTime, null);
5030            } catch (PackageManagerException e) {
5031                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5032
5033                // Delete invalid userdata apps
5034                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5035                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5036                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5037                    if (file.isDirectory()) {
5038                        mInstaller.rmPackageDir(file.getAbsolutePath());
5039                    } else {
5040                        file.delete();
5041                    }
5042                }
5043            }
5044        }
5045    }
5046
5047    private static File getSettingsProblemFile() {
5048        File dataDir = Environment.getDataDirectory();
5049        File systemDir = new File(dataDir, "system");
5050        File fname = new File(systemDir, "uiderrors.txt");
5051        return fname;
5052    }
5053
5054    static void reportSettingsProblem(int priority, String msg) {
5055        logCriticalInfo(priority, msg);
5056    }
5057
5058    static void logCriticalInfo(int priority, String msg) {
5059        Slog.println(priority, TAG, msg);
5060        EventLogTags.writePmCriticalInfo(msg);
5061        try {
5062            File fname = getSettingsProblemFile();
5063            FileOutputStream out = new FileOutputStream(fname, true);
5064            PrintWriter pw = new FastPrintWriter(out);
5065            SimpleDateFormat formatter = new SimpleDateFormat();
5066            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5067            pw.println(dateString + ": " + msg);
5068            pw.close();
5069            FileUtils.setPermissions(
5070                    fname.toString(),
5071                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5072                    -1, -1);
5073        } catch (java.io.IOException e) {
5074        }
5075    }
5076
5077    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5078            PackageParser.Package pkg, File srcFile, int parseFlags)
5079            throws PackageManagerException {
5080        if (ps != null
5081                && ps.codePath.equals(srcFile)
5082                && ps.timeStamp == srcFile.lastModified()
5083                && !isCompatSignatureUpdateNeeded(pkg)
5084                && !isRecoverSignatureUpdateNeeded(pkg)) {
5085            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5086            if (ps.signatures.mSignatures != null
5087                    && ps.signatures.mSignatures.length != 0
5088                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
5089                // Optimization: reuse the existing cached certificates
5090                // if the package appears to be unchanged.
5091                pkg.mSignatures = ps.signatures.mSignatures;
5092                KeySetManagerService ksms = mSettings.mKeySetManagerService;
5093                synchronized (mPackages) {
5094                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5095                }
5096                return;
5097            }
5098
5099            Slog.w(TAG, "PackageSetting for " + ps.name
5100                    + " is missing signatures.  Collecting certs again to recover them.");
5101        } else {
5102            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5103        }
5104
5105        try {
5106            pp.collectCertificates(pkg, parseFlags);
5107            pp.collectManifestDigest(pkg);
5108        } catch (PackageParserException e) {
5109            throw PackageManagerException.from(e);
5110        }
5111    }
5112
5113    /*
5114     *  Scan a package and return the newly parsed package.
5115     *  Returns null in case of errors and the error code is stored in mLastScanError
5116     */
5117    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5118            long currentTime, UserHandle user) throws PackageManagerException {
5119        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5120        parseFlags |= mDefParseFlags;
5121        PackageParser pp = new PackageParser();
5122        pp.setSeparateProcesses(mSeparateProcesses);
5123        pp.setOnlyCoreApps(mOnlyCore);
5124        pp.setDisplayMetrics(mMetrics);
5125
5126        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5127            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5128        }
5129
5130        final PackageParser.Package pkg;
5131        try {
5132            pkg = pp.parsePackage(scanFile, parseFlags);
5133        } catch (PackageParserException e) {
5134            throw PackageManagerException.from(e);
5135        }
5136
5137        PackageSetting ps = null;
5138        PackageSetting updatedPkg;
5139        // reader
5140        synchronized (mPackages) {
5141            // Look to see if we already know about this package.
5142            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5143            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5144                // This package has been renamed to its original name.  Let's
5145                // use that.
5146                ps = mSettings.peekPackageLPr(oldName);
5147            }
5148            // If there was no original package, see one for the real package name.
5149            if (ps == null) {
5150                ps = mSettings.peekPackageLPr(pkg.packageName);
5151            }
5152            // Check to see if this package could be hiding/updating a system
5153            // package.  Must look for it either under the original or real
5154            // package name depending on our state.
5155            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5156            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5157        }
5158        boolean updatedPkgBetter = false;
5159        // First check if this is a system package that may involve an update
5160        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5161            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5162            // it needs to drop FLAG_PRIVILEGED.
5163            if (locationIsPrivileged(scanFile)) {
5164                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5165            } else {
5166                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5167            }
5168
5169            if (ps != null && !ps.codePath.equals(scanFile)) {
5170                // The path has changed from what was last scanned...  check the
5171                // version of the new path against what we have stored to determine
5172                // what to do.
5173                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5174                if (pkg.mVersionCode <= ps.versionCode) {
5175                    // The system package has been updated and the code path does not match
5176                    // Ignore entry. Skip it.
5177                    Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5178                            + " ignored: updated version " + ps.versionCode
5179                            + " better than this " + pkg.mVersionCode);
5180                    if (!updatedPkg.codePath.equals(scanFile)) {
5181                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5182                                + ps.name + " changing from " + updatedPkg.codePathString
5183                                + " to " + scanFile);
5184                        updatedPkg.codePath = scanFile;
5185                        updatedPkg.codePathString = scanFile.toString();
5186                        updatedPkg.resourcePath = scanFile;
5187                        updatedPkg.resourcePathString = scanFile.toString();
5188                    }
5189                    updatedPkg.pkg = pkg;
5190                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
5191                } else {
5192                    // The current app on the system partition is better than
5193                    // what we have updated to on the data partition; switch
5194                    // back to the system partition version.
5195                    // At this point, its safely assumed that package installation for
5196                    // apps in system partition will go through. If not there won't be a working
5197                    // version of the app
5198                    // writer
5199                    synchronized (mPackages) {
5200                        // Just remove the loaded entries from package lists.
5201                        mPackages.remove(ps.name);
5202                    }
5203
5204                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5205                            + " reverting from " + ps.codePathString
5206                            + ": new version " + pkg.mVersionCode
5207                            + " better than installed " + ps.versionCode);
5208
5209                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5210                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5211                    synchronized (mInstallLock) {
5212                        args.cleanUpResourcesLI();
5213                    }
5214                    synchronized (mPackages) {
5215                        mSettings.enableSystemPackageLPw(ps.name);
5216                    }
5217                    updatedPkgBetter = true;
5218                }
5219            }
5220        }
5221
5222        if (updatedPkg != null) {
5223            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5224            // initially
5225            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5226
5227            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5228            // flag set initially
5229            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5230                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5231            }
5232        }
5233
5234        // Verify certificates against what was last scanned
5235        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5236
5237        /*
5238         * A new system app appeared, but we already had a non-system one of the
5239         * same name installed earlier.
5240         */
5241        boolean shouldHideSystemApp = false;
5242        if (updatedPkg == null && ps != null
5243                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5244            /*
5245             * Check to make sure the signatures match first. If they don't,
5246             * wipe the installed application and its data.
5247             */
5248            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5249                    != PackageManager.SIGNATURE_MATCH) {
5250                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5251                        + " signatures don't match existing userdata copy; removing");
5252                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5253                ps = null;
5254            } else {
5255                /*
5256                 * If the newly-added system app is an older version than the
5257                 * already installed version, hide it. It will be scanned later
5258                 * and re-added like an update.
5259                 */
5260                if (pkg.mVersionCode <= ps.versionCode) {
5261                    shouldHideSystemApp = true;
5262                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5263                            + " but new version " + pkg.mVersionCode + " better than installed "
5264                            + ps.versionCode + "; hiding system");
5265                } else {
5266                    /*
5267                     * The newly found system app is a newer version that the
5268                     * one previously installed. Simply remove the
5269                     * already-installed application and replace it with our own
5270                     * while keeping the application data.
5271                     */
5272                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5273                            + " reverting from " + ps.codePathString + ": new version "
5274                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5275                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5276                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5277                    synchronized (mInstallLock) {
5278                        args.cleanUpResourcesLI();
5279                    }
5280                }
5281            }
5282        }
5283
5284        // The apk is forward locked (not public) if its code and resources
5285        // are kept in different files. (except for app in either system or
5286        // vendor path).
5287        // TODO grab this value from PackageSettings
5288        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5289            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5290                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5291            }
5292        }
5293
5294        // TODO: extend to support forward-locked splits
5295        String resourcePath = null;
5296        String baseResourcePath = null;
5297        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5298            if (ps != null && ps.resourcePathString != null) {
5299                resourcePath = ps.resourcePathString;
5300                baseResourcePath = ps.resourcePathString;
5301            } else {
5302                // Should not happen at all. Just log an error.
5303                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5304            }
5305        } else {
5306            resourcePath = pkg.codePath;
5307            baseResourcePath = pkg.baseCodePath;
5308        }
5309
5310        // Set application objects path explicitly.
5311        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5312        pkg.applicationInfo.setCodePath(pkg.codePath);
5313        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5314        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5315        pkg.applicationInfo.setResourcePath(resourcePath);
5316        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5317        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5318
5319        // Note that we invoke the following method only if we are about to unpack an application
5320        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5321                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5322
5323        /*
5324         * If the system app should be overridden by a previously installed
5325         * data, hide the system app now and let the /data/app scan pick it up
5326         * again.
5327         */
5328        if (shouldHideSystemApp) {
5329            synchronized (mPackages) {
5330                /*
5331                 * We have to grant systems permissions before we hide, because
5332                 * grantPermissions will assume the package update is trying to
5333                 * expand its permissions.
5334                 */
5335                grantPermissionsLPw(pkg, true, pkg.packageName);
5336                mSettings.disableSystemPackageLPw(pkg.packageName);
5337            }
5338        }
5339
5340        return scannedPkg;
5341    }
5342
5343    private static String fixProcessName(String defProcessName,
5344            String processName, int uid) {
5345        if (processName == null) {
5346            return defProcessName;
5347        }
5348        return processName;
5349    }
5350
5351    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5352            throws PackageManagerException {
5353        if (pkgSetting.signatures.mSignatures != null) {
5354            // Already existing package. Make sure signatures match
5355            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5356                    == PackageManager.SIGNATURE_MATCH;
5357            if (!match) {
5358                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5359                        == PackageManager.SIGNATURE_MATCH;
5360            }
5361            if (!match) {
5362                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5363                        == PackageManager.SIGNATURE_MATCH;
5364            }
5365            if (!match) {
5366                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5367                        + pkg.packageName + " signatures do not match the "
5368                        + "previously installed version; ignoring!");
5369            }
5370        }
5371
5372        // Check for shared user signatures
5373        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5374            // Already existing package. Make sure signatures match
5375            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5376                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5377            if (!match) {
5378                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5379                        == PackageManager.SIGNATURE_MATCH;
5380            }
5381            if (!match) {
5382                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5383                        == PackageManager.SIGNATURE_MATCH;
5384            }
5385            if (!match) {
5386                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5387                        "Package " + pkg.packageName
5388                        + " has no signatures that match those in shared user "
5389                        + pkgSetting.sharedUser.name + "; ignoring!");
5390            }
5391        }
5392    }
5393
5394    /**
5395     * Enforces that only the system UID or root's UID can call a method exposed
5396     * via Binder.
5397     *
5398     * @param message used as message if SecurityException is thrown
5399     * @throws SecurityException if the caller is not system or root
5400     */
5401    private static final void enforceSystemOrRoot(String message) {
5402        final int uid = Binder.getCallingUid();
5403        if (uid != Process.SYSTEM_UID && uid != 0) {
5404            throw new SecurityException(message);
5405        }
5406    }
5407
5408    @Override
5409    public void performBootDexOpt() {
5410        enforceSystemOrRoot("Only the system can request dexopt be performed");
5411
5412        // Before everything else, see whether we need to fstrim.
5413        try {
5414            IMountService ms = PackageHelper.getMountService();
5415            if (ms != null) {
5416                final boolean isUpgrade = isUpgrade();
5417                boolean doTrim = isUpgrade;
5418                if (doTrim) {
5419                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5420                } else {
5421                    final long interval = android.provider.Settings.Global.getLong(
5422                            mContext.getContentResolver(),
5423                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5424                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5425                    if (interval > 0) {
5426                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5427                        if (timeSinceLast > interval) {
5428                            doTrim = true;
5429                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5430                                    + "; running immediately");
5431                        }
5432                    }
5433                }
5434                if (doTrim) {
5435                    if (!isFirstBoot()) {
5436                        try {
5437                            ActivityManagerNative.getDefault().showBootMessage(
5438                                    mContext.getResources().getString(
5439                                            R.string.android_upgrading_fstrim), true);
5440                        } catch (RemoteException e) {
5441                        }
5442                    }
5443                    ms.runMaintenance();
5444                }
5445            } else {
5446                Slog.e(TAG, "Mount service unavailable!");
5447            }
5448        } catch (RemoteException e) {
5449            // Can't happen; MountService is local
5450        }
5451
5452        final ArraySet<PackageParser.Package> pkgs;
5453        synchronized (mPackages) {
5454            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5455        }
5456
5457        if (pkgs != null) {
5458            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5459            // in case the device runs out of space.
5460            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5461            // Give priority to core apps.
5462            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5463                PackageParser.Package pkg = it.next();
5464                if (pkg.coreApp) {
5465                    if (DEBUG_DEXOPT) {
5466                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5467                    }
5468                    sortedPkgs.add(pkg);
5469                    it.remove();
5470                }
5471            }
5472            // Give priority to system apps that listen for pre boot complete.
5473            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5474            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
5475            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5476                PackageParser.Package pkg = it.next();
5477                if (pkgNames.contains(pkg.packageName)) {
5478                    if (DEBUG_DEXOPT) {
5479                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
5480                    }
5481                    sortedPkgs.add(pkg);
5482                    it.remove();
5483                }
5484            }
5485            // Give priority to system apps.
5486            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5487                PackageParser.Package pkg = it.next();
5488                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
5489                    if (DEBUG_DEXOPT) {
5490                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
5491                    }
5492                    sortedPkgs.add(pkg);
5493                    it.remove();
5494                }
5495            }
5496            // Give priority to updated system apps.
5497            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5498                PackageParser.Package pkg = it.next();
5499                if (pkg.isUpdatedSystemApp()) {
5500                    if (DEBUG_DEXOPT) {
5501                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
5502                    }
5503                    sortedPkgs.add(pkg);
5504                    it.remove();
5505                }
5506            }
5507            // Give priority to apps that listen for boot complete.
5508            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
5509            pkgNames = getPackageNamesForIntent(intent);
5510            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5511                PackageParser.Package pkg = it.next();
5512                if (pkgNames.contains(pkg.packageName)) {
5513                    if (DEBUG_DEXOPT) {
5514                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
5515                    }
5516                    sortedPkgs.add(pkg);
5517                    it.remove();
5518                }
5519            }
5520            // Filter out packages that aren't recently used.
5521            filterRecentlyUsedApps(pkgs);
5522            // Add all remaining apps.
5523            for (PackageParser.Package pkg : pkgs) {
5524                if (DEBUG_DEXOPT) {
5525                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
5526                }
5527                sortedPkgs.add(pkg);
5528            }
5529
5530            // If we want to be lazy, filter everything that wasn't recently used.
5531            if (mLazyDexOpt) {
5532                filterRecentlyUsedApps(sortedPkgs);
5533            }
5534
5535            int i = 0;
5536            int total = sortedPkgs.size();
5537            File dataDir = Environment.getDataDirectory();
5538            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
5539            if (lowThreshold == 0) {
5540                throw new IllegalStateException("Invalid low memory threshold");
5541            }
5542            for (PackageParser.Package pkg : sortedPkgs) {
5543                long usableSpace = dataDir.getUsableSpace();
5544                if (usableSpace < lowThreshold) {
5545                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
5546                    break;
5547                }
5548                performBootDexOpt(pkg, ++i, total);
5549            }
5550        }
5551    }
5552
5553    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
5554        // Filter out packages that aren't recently used.
5555        //
5556        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
5557        // should do a full dexopt.
5558        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
5559            int total = pkgs.size();
5560            int skipped = 0;
5561            long now = System.currentTimeMillis();
5562            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
5563                PackageParser.Package pkg = i.next();
5564                long then = pkg.mLastPackageUsageTimeInMills;
5565                if (then + mDexOptLRUThresholdInMills < now) {
5566                    if (DEBUG_DEXOPT) {
5567                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
5568                              ((then == 0) ? "never" : new Date(then)));
5569                    }
5570                    i.remove();
5571                    skipped++;
5572                }
5573            }
5574            if (DEBUG_DEXOPT) {
5575                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
5576            }
5577        }
5578    }
5579
5580    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
5581        List<ResolveInfo> ris = null;
5582        try {
5583            ris = AppGlobals.getPackageManager().queryIntentReceivers(
5584                    intent, null, 0, UserHandle.USER_OWNER);
5585        } catch (RemoteException e) {
5586        }
5587        ArraySet<String> pkgNames = new ArraySet<String>();
5588        if (ris != null) {
5589            for (ResolveInfo ri : ris) {
5590                pkgNames.add(ri.activityInfo.packageName);
5591            }
5592        }
5593        return pkgNames;
5594    }
5595
5596    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
5597        if (DEBUG_DEXOPT) {
5598            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
5599        }
5600        if (!isFirstBoot()) {
5601            try {
5602                ActivityManagerNative.getDefault().showBootMessage(
5603                        mContext.getResources().getString(R.string.android_upgrading_apk,
5604                                curr, total), true);
5605            } catch (RemoteException e) {
5606            }
5607        }
5608        PackageParser.Package p = pkg;
5609        synchronized (mInstallLock) {
5610            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
5611                    false /* force dex */, false /* defer */, true /* include dependencies */);
5612        }
5613    }
5614
5615    @Override
5616    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
5617        return performDexOpt(packageName, instructionSet, false);
5618    }
5619
5620    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
5621        boolean dexopt = mLazyDexOpt || backgroundDexopt;
5622        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
5623        if (!dexopt && !updateUsage) {
5624            // We aren't going to dexopt or update usage, so bail early.
5625            return false;
5626        }
5627        PackageParser.Package p;
5628        final String targetInstructionSet;
5629        synchronized (mPackages) {
5630            p = mPackages.get(packageName);
5631            if (p == null) {
5632                return false;
5633            }
5634            if (updateUsage) {
5635                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
5636            }
5637            mPackageUsage.write(false);
5638            if (!dexopt) {
5639                // We aren't going to dexopt, so bail early.
5640                return false;
5641            }
5642
5643            targetInstructionSet = instructionSet != null ? instructionSet :
5644                    getPrimaryInstructionSet(p.applicationInfo);
5645            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
5646                return false;
5647            }
5648        }
5649
5650        synchronized (mInstallLock) {
5651            final String[] instructionSets = new String[] { targetInstructionSet };
5652            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
5653                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
5654            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
5655        }
5656    }
5657
5658    public ArraySet<String> getPackagesThatNeedDexOpt() {
5659        ArraySet<String> pkgs = null;
5660        synchronized (mPackages) {
5661            for (PackageParser.Package p : mPackages.values()) {
5662                if (DEBUG_DEXOPT) {
5663                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
5664                }
5665                if (!p.mDexOptPerformed.isEmpty()) {
5666                    continue;
5667                }
5668                if (pkgs == null) {
5669                    pkgs = new ArraySet<String>();
5670                }
5671                pkgs.add(p.packageName);
5672            }
5673        }
5674        return pkgs;
5675    }
5676
5677    public void shutdown() {
5678        mPackageUsage.write(true);
5679    }
5680
5681    @Override
5682    public void forceDexOpt(String packageName) {
5683        enforceSystemOrRoot("forceDexOpt");
5684
5685        PackageParser.Package pkg;
5686        synchronized (mPackages) {
5687            pkg = mPackages.get(packageName);
5688            if (pkg == null) {
5689                throw new IllegalArgumentException("Missing package: " + packageName);
5690            }
5691        }
5692
5693        synchronized (mInstallLock) {
5694            final String[] instructionSets = new String[] {
5695                    getPrimaryInstructionSet(pkg.applicationInfo) };
5696            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
5697                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
5698            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
5699                throw new IllegalStateException("Failed to dexopt: " + res);
5700            }
5701        }
5702    }
5703
5704    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
5705        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
5706            Slog.w(TAG, "Unable to update from " + oldPkg.name
5707                    + " to " + newPkg.packageName
5708                    + ": old package not in system partition");
5709            return false;
5710        } else if (mPackages.get(oldPkg.name) != null) {
5711            Slog.w(TAG, "Unable to update from " + oldPkg.name
5712                    + " to " + newPkg.packageName
5713                    + ": old package still exists");
5714            return false;
5715        }
5716        return true;
5717    }
5718
5719    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
5720        int[] users = sUserManager.getUserIds();
5721        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
5722        if (res < 0) {
5723            return res;
5724        }
5725        for (int user : users) {
5726            if (user != 0) {
5727                res = mInstaller.createUserData(volumeUuid, packageName,
5728                        UserHandle.getUid(user, uid), user, seinfo);
5729                if (res < 0) {
5730                    return res;
5731                }
5732            }
5733        }
5734        return res;
5735    }
5736
5737    private int removeDataDirsLI(String volumeUuid, String packageName) {
5738        int[] users = sUserManager.getUserIds();
5739        int res = 0;
5740        for (int user : users) {
5741            int resInner = mInstaller.remove(volumeUuid, packageName, user);
5742            if (resInner < 0) {
5743                res = resInner;
5744            }
5745        }
5746
5747        return res;
5748    }
5749
5750    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
5751        int[] users = sUserManager.getUserIds();
5752        int res = 0;
5753        for (int user : users) {
5754            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
5755            if (resInner < 0) {
5756                res = resInner;
5757            }
5758        }
5759        return res;
5760    }
5761
5762    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
5763            PackageParser.Package changingLib) {
5764        if (file.path != null) {
5765            usesLibraryFiles.add(file.path);
5766            return;
5767        }
5768        PackageParser.Package p = mPackages.get(file.apk);
5769        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
5770            // If we are doing this while in the middle of updating a library apk,
5771            // then we need to make sure to use that new apk for determining the
5772            // dependencies here.  (We haven't yet finished committing the new apk
5773            // to the package manager state.)
5774            if (p == null || p.packageName.equals(changingLib.packageName)) {
5775                p = changingLib;
5776            }
5777        }
5778        if (p != null) {
5779            usesLibraryFiles.addAll(p.getAllCodePaths());
5780        }
5781    }
5782
5783    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
5784            PackageParser.Package changingLib) throws PackageManagerException {
5785        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
5786            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
5787            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
5788            for (int i=0; i<N; i++) {
5789                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
5790                if (file == null) {
5791                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
5792                            "Package " + pkg.packageName + " requires unavailable shared library "
5793                            + pkg.usesLibraries.get(i) + "; failing!");
5794                }
5795                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5796            }
5797            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
5798            for (int i=0; i<N; i++) {
5799                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
5800                if (file == null) {
5801                    Slog.w(TAG, "Package " + pkg.packageName
5802                            + " desires unavailable shared library "
5803                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
5804                } else {
5805                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5806                }
5807            }
5808            N = usesLibraryFiles.size();
5809            if (N > 0) {
5810                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
5811            } else {
5812                pkg.usesLibraryFiles = null;
5813            }
5814        }
5815    }
5816
5817    private static boolean hasString(List<String> list, List<String> which) {
5818        if (list == null) {
5819            return false;
5820        }
5821        for (int i=list.size()-1; i>=0; i--) {
5822            for (int j=which.size()-1; j>=0; j--) {
5823                if (which.get(j).equals(list.get(i))) {
5824                    return true;
5825                }
5826            }
5827        }
5828        return false;
5829    }
5830
5831    private void updateAllSharedLibrariesLPw() {
5832        for (PackageParser.Package pkg : mPackages.values()) {
5833            try {
5834                updateSharedLibrariesLPw(pkg, null);
5835            } catch (PackageManagerException e) {
5836                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5837            }
5838        }
5839    }
5840
5841    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
5842            PackageParser.Package changingPkg) {
5843        ArrayList<PackageParser.Package> res = null;
5844        for (PackageParser.Package pkg : mPackages.values()) {
5845            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
5846                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
5847                if (res == null) {
5848                    res = new ArrayList<PackageParser.Package>();
5849                }
5850                res.add(pkg);
5851                try {
5852                    updateSharedLibrariesLPw(pkg, changingPkg);
5853                } catch (PackageManagerException e) {
5854                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5855                }
5856            }
5857        }
5858        return res;
5859    }
5860
5861    /**
5862     * Derive the value of the {@code cpuAbiOverride} based on the provided
5863     * value and an optional stored value from the package settings.
5864     */
5865    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
5866        String cpuAbiOverride = null;
5867
5868        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
5869            cpuAbiOverride = null;
5870        } else if (abiOverride != null) {
5871            cpuAbiOverride = abiOverride;
5872        } else if (settings != null) {
5873            cpuAbiOverride = settings.cpuAbiOverrideString;
5874        }
5875
5876        return cpuAbiOverride;
5877    }
5878
5879    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
5880            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5881        boolean success = false;
5882        try {
5883            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
5884                    currentTime, user);
5885            success = true;
5886            return res;
5887        } finally {
5888            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5889                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
5890            }
5891        }
5892    }
5893
5894    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
5895            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5896        final File scanFile = new File(pkg.codePath);
5897        if (pkg.applicationInfo.getCodePath() == null ||
5898                pkg.applicationInfo.getResourcePath() == null) {
5899            // Bail out. The resource and code paths haven't been set.
5900            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
5901                    "Code and resource paths haven't been set correctly");
5902        }
5903
5904        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5905            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
5906        } else {
5907            // Only allow system apps to be flagged as core apps.
5908            pkg.coreApp = false;
5909        }
5910
5911        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5912            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5913        }
5914
5915        if (mCustomResolverComponentName != null &&
5916                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5917            setUpCustomResolverActivity(pkg);
5918        }
5919
5920        if (pkg.packageName.equals("android")) {
5921            synchronized (mPackages) {
5922                if (mAndroidApplication != null) {
5923                    Slog.w(TAG, "*************************************************");
5924                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5925                    Slog.w(TAG, " file=" + scanFile);
5926                    Slog.w(TAG, "*************************************************");
5927                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5928                            "Core android package being redefined.  Skipping.");
5929                }
5930
5931                // Set up information for our fall-back user intent resolution activity.
5932                mPlatformPackage = pkg;
5933                pkg.mVersionCode = mSdkVersion;
5934                mAndroidApplication = pkg.applicationInfo;
5935
5936                if (!mResolverReplaced) {
5937                    mResolveActivity.applicationInfo = mAndroidApplication;
5938                    mResolveActivity.name = ResolverActivity.class.getName();
5939                    mResolveActivity.packageName = mAndroidApplication.packageName;
5940                    mResolveActivity.processName = "system:ui";
5941                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5942                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5943                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5944                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5945                    mResolveActivity.exported = true;
5946                    mResolveActivity.enabled = true;
5947                    mResolveInfo.activityInfo = mResolveActivity;
5948                    mResolveInfo.priority = 0;
5949                    mResolveInfo.preferredOrder = 0;
5950                    mResolveInfo.match = 0;
5951                    mResolveComponentName = new ComponentName(
5952                            mAndroidApplication.packageName, mResolveActivity.name);
5953                }
5954            }
5955        }
5956
5957        if (DEBUG_PACKAGE_SCANNING) {
5958            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5959                Log.d(TAG, "Scanning package " + pkg.packageName);
5960        }
5961
5962        if (mPackages.containsKey(pkg.packageName)
5963                || mSharedLibraries.containsKey(pkg.packageName)) {
5964            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5965                    "Application package " + pkg.packageName
5966                    + " already installed.  Skipping duplicate.");
5967        }
5968
5969        // If we're only installing presumed-existing packages, require that the
5970        // scanned APK is both already known and at the path previously established
5971        // for it.  Previously unknown packages we pick up normally, but if we have an
5972        // a priori expectation about this package's install presence, enforce it.
5973        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
5974            PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
5975            if (known != null) {
5976                if (DEBUG_PACKAGE_SCANNING) {
5977                    Log.d(TAG, "Examining " + pkg.codePath
5978                            + " and requiring known paths " + known.codePathString
5979                            + " & " + known.resourcePathString);
5980                }
5981                if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
5982                        || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
5983                    throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
5984                            "Application package " + pkg.packageName
5985                            + " found at " + pkg.applicationInfo.getCodePath()
5986                            + " but expected at " + known.codePathString + "; ignoring.");
5987                }
5988            }
5989        }
5990
5991        // Initialize package source and resource directories
5992        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5993        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5994
5995        SharedUserSetting suid = null;
5996        PackageSetting pkgSetting = null;
5997
5998        if (!isSystemApp(pkg)) {
5999            // Only system apps can use these features.
6000            pkg.mOriginalPackages = null;
6001            pkg.mRealPackage = null;
6002            pkg.mAdoptPermissions = null;
6003        }
6004
6005        // writer
6006        synchronized (mPackages) {
6007            if (pkg.mSharedUserId != null) {
6008                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6009                if (suid == null) {
6010                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6011                            "Creating application package " + pkg.packageName
6012                            + " for shared user failed");
6013                }
6014                if (DEBUG_PACKAGE_SCANNING) {
6015                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6016                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6017                                + "): packages=" + suid.packages);
6018                }
6019            }
6020
6021            // Check if we are renaming from an original package name.
6022            PackageSetting origPackage = null;
6023            String realName = null;
6024            if (pkg.mOriginalPackages != null) {
6025                // This package may need to be renamed to a previously
6026                // installed name.  Let's check on that...
6027                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6028                if (pkg.mOriginalPackages.contains(renamed)) {
6029                    // This package had originally been installed as the
6030                    // original name, and we have already taken care of
6031                    // transitioning to the new one.  Just update the new
6032                    // one to continue using the old name.
6033                    realName = pkg.mRealPackage;
6034                    if (!pkg.packageName.equals(renamed)) {
6035                        // Callers into this function may have already taken
6036                        // care of renaming the package; only do it here if
6037                        // it is not already done.
6038                        pkg.setPackageName(renamed);
6039                    }
6040
6041                } else {
6042                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6043                        if ((origPackage = mSettings.peekPackageLPr(
6044                                pkg.mOriginalPackages.get(i))) != null) {
6045                            // We do have the package already installed under its
6046                            // original name...  should we use it?
6047                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6048                                // New package is not compatible with original.
6049                                origPackage = null;
6050                                continue;
6051                            } else if (origPackage.sharedUser != null) {
6052                                // Make sure uid is compatible between packages.
6053                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6054                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6055                                            + " to " + pkg.packageName + ": old uid "
6056                                            + origPackage.sharedUser.name
6057                                            + " differs from " + pkg.mSharedUserId);
6058                                    origPackage = null;
6059                                    continue;
6060                                }
6061                            } else {
6062                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6063                                        + pkg.packageName + " to old name " + origPackage.name);
6064                            }
6065                            break;
6066                        }
6067                    }
6068                }
6069            }
6070
6071            if (mTransferedPackages.contains(pkg.packageName)) {
6072                Slog.w(TAG, "Package " + pkg.packageName
6073                        + " was transferred to another, but its .apk remains");
6074            }
6075
6076            // Just create the setting, don't add it yet. For already existing packages
6077            // the PkgSetting exists already and doesn't have to be created.
6078            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6079                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6080                    pkg.applicationInfo.primaryCpuAbi,
6081                    pkg.applicationInfo.secondaryCpuAbi,
6082                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6083                    user, false);
6084            if (pkgSetting == null) {
6085                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6086                        "Creating application package " + pkg.packageName + " failed");
6087            }
6088
6089            if (pkgSetting.origPackage != null) {
6090                // If we are first transitioning from an original package,
6091                // fix up the new package's name now.  We need to do this after
6092                // looking up the package under its new name, so getPackageLP
6093                // can take care of fiddling things correctly.
6094                pkg.setPackageName(origPackage.name);
6095
6096                // File a report about this.
6097                String msg = "New package " + pkgSetting.realName
6098                        + " renamed to replace old package " + pkgSetting.name;
6099                reportSettingsProblem(Log.WARN, msg);
6100
6101                // Make a note of it.
6102                mTransferedPackages.add(origPackage.name);
6103
6104                // No longer need to retain this.
6105                pkgSetting.origPackage = null;
6106            }
6107
6108            if (realName != null) {
6109                // Make a note of it.
6110                mTransferedPackages.add(pkg.packageName);
6111            }
6112
6113            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6114                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6115            }
6116
6117            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6118                // Check all shared libraries and map to their actual file path.
6119                // We only do this here for apps not on a system dir, because those
6120                // are the only ones that can fail an install due to this.  We
6121                // will take care of the system apps by updating all of their
6122                // library paths after the scan is done.
6123                updateSharedLibrariesLPw(pkg, null);
6124            }
6125
6126            if (mFoundPolicyFile) {
6127                SELinuxMMAC.assignSeinfoValue(pkg);
6128            }
6129
6130            pkg.applicationInfo.uid = pkgSetting.appId;
6131            pkg.mExtras = pkgSetting;
6132            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
6133                try {
6134                    verifySignaturesLP(pkgSetting, pkg);
6135                    // We just determined the app is signed correctly, so bring
6136                    // over the latest parsed certs.
6137                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6138                } catch (PackageManagerException e) {
6139                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6140                        throw e;
6141                    }
6142                    // The signature has changed, but this package is in the system
6143                    // image...  let's recover!
6144                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6145                    // However...  if this package is part of a shared user, but it
6146                    // doesn't match the signature of the shared user, let's fail.
6147                    // What this means is that you can't change the signatures
6148                    // associated with an overall shared user, which doesn't seem all
6149                    // that unreasonable.
6150                    if (pkgSetting.sharedUser != null) {
6151                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6152                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6153                            throw new PackageManagerException(
6154                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6155                                            "Signature mismatch for shared user : "
6156                                            + pkgSetting.sharedUser);
6157                        }
6158                    }
6159                    // File a report about this.
6160                    String msg = "System package " + pkg.packageName
6161                        + " signature changed; retaining data.";
6162                    reportSettingsProblem(Log.WARN, msg);
6163                }
6164            } else {
6165                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
6166                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6167                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6168                                "Package " + pkg.packageName + " upgrade keys do not match the "
6169                                + "previously installed version");
6170                    } else {
6171                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6172                        String msg = "System package " + pkg.packageName
6173                            + " signature changed; retaining data.";
6174                        reportSettingsProblem(Log.WARN, msg);
6175                    }
6176                } else {
6177                    // We just determined the app is signed correctly, so bring
6178                    // over the latest parsed certs.
6179                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6180                }
6181            }
6182            // Verify that this new package doesn't have any content providers
6183            // that conflict with existing packages.  Only do this if the
6184            // package isn't already installed, since we don't want to break
6185            // things that are installed.
6186            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6187                final int N = pkg.providers.size();
6188                int i;
6189                for (i=0; i<N; i++) {
6190                    PackageParser.Provider p = pkg.providers.get(i);
6191                    if (p.info.authority != null) {
6192                        String names[] = p.info.authority.split(";");
6193                        for (int j = 0; j < names.length; j++) {
6194                            if (mProvidersByAuthority.containsKey(names[j])) {
6195                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6196                                final String otherPackageName =
6197                                        ((other != null && other.getComponentName() != null) ?
6198                                                other.getComponentName().getPackageName() : "?");
6199                                throw new PackageManagerException(
6200                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6201                                                "Can't install because provider name " + names[j]
6202                                                + " (in package " + pkg.applicationInfo.packageName
6203                                                + ") is already used by " + otherPackageName);
6204                            }
6205                        }
6206                    }
6207                }
6208            }
6209
6210            if (pkg.mAdoptPermissions != null) {
6211                // This package wants to adopt ownership of permissions from
6212                // another package.
6213                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6214                    final String origName = pkg.mAdoptPermissions.get(i);
6215                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6216                    if (orig != null) {
6217                        if (verifyPackageUpdateLPr(orig, pkg)) {
6218                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6219                                    + pkg.packageName);
6220                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6221                        }
6222                    }
6223                }
6224            }
6225        }
6226
6227        final String pkgName = pkg.packageName;
6228
6229        final long scanFileTime = scanFile.lastModified();
6230        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6231        pkg.applicationInfo.processName = fixProcessName(
6232                pkg.applicationInfo.packageName,
6233                pkg.applicationInfo.processName,
6234                pkg.applicationInfo.uid);
6235
6236        File dataPath;
6237        if (mPlatformPackage == pkg) {
6238            // The system package is special.
6239            dataPath = new File(Environment.getDataDirectory(), "system");
6240
6241            pkg.applicationInfo.dataDir = dataPath.getPath();
6242
6243        } else {
6244            // This is a normal package, need to make its data directory.
6245            dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName,
6246                    UserHandle.USER_OWNER);
6247
6248            boolean uidError = false;
6249            if (dataPath.exists()) {
6250                int currentUid = 0;
6251                try {
6252                    StructStat stat = Os.stat(dataPath.getPath());
6253                    currentUid = stat.st_uid;
6254                } catch (ErrnoException e) {
6255                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6256                }
6257
6258                // If we have mismatched owners for the data path, we have a problem.
6259                if (currentUid != pkg.applicationInfo.uid) {
6260                    boolean recovered = false;
6261                    if (currentUid == 0) {
6262                        // The directory somehow became owned by root.  Wow.
6263                        // This is probably because the system was stopped while
6264                        // installd was in the middle of messing with its libs
6265                        // directory.  Ask installd to fix that.
6266                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6267                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6268                        if (ret >= 0) {
6269                            recovered = true;
6270                            String msg = "Package " + pkg.packageName
6271                                    + " unexpectedly changed to uid 0; recovered to " +
6272                                    + pkg.applicationInfo.uid;
6273                            reportSettingsProblem(Log.WARN, msg);
6274                        }
6275                    }
6276                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6277                            || (scanFlags&SCAN_BOOTING) != 0)) {
6278                        // If this is a system app, we can at least delete its
6279                        // current data so the application will still work.
6280                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6281                        if (ret >= 0) {
6282                            // TODO: Kill the processes first
6283                            // Old data gone!
6284                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6285                                    ? "System package " : "Third party package ";
6286                            String msg = prefix + pkg.packageName
6287                                    + " has changed from uid: "
6288                                    + currentUid + " to "
6289                                    + pkg.applicationInfo.uid + "; old data erased";
6290                            reportSettingsProblem(Log.WARN, msg);
6291                            recovered = true;
6292
6293                            // And now re-install the app.
6294                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6295                                    pkg.applicationInfo.seinfo);
6296                            if (ret == -1) {
6297                                // Ack should not happen!
6298                                msg = prefix + pkg.packageName
6299                                        + " could not have data directory re-created after delete.";
6300                                reportSettingsProblem(Log.WARN, msg);
6301                                throw new PackageManagerException(
6302                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6303                            }
6304                        }
6305                        if (!recovered) {
6306                            mHasSystemUidErrors = true;
6307                        }
6308                    } else if (!recovered) {
6309                        // If we allow this install to proceed, we will be broken.
6310                        // Abort, abort!
6311                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6312                                "scanPackageLI");
6313                    }
6314                    if (!recovered) {
6315                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6316                            + pkg.applicationInfo.uid + "/fs_"
6317                            + currentUid;
6318                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6319                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6320                        String msg = "Package " + pkg.packageName
6321                                + " has mismatched uid: "
6322                                + currentUid + " on disk, "
6323                                + pkg.applicationInfo.uid + " in settings";
6324                        // writer
6325                        synchronized (mPackages) {
6326                            mSettings.mReadMessages.append(msg);
6327                            mSettings.mReadMessages.append('\n');
6328                            uidError = true;
6329                            if (!pkgSetting.uidError) {
6330                                reportSettingsProblem(Log.ERROR, msg);
6331                            }
6332                        }
6333                    }
6334                }
6335                pkg.applicationInfo.dataDir = dataPath.getPath();
6336                if (mShouldRestoreconData) {
6337                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6338                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6339                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6340                }
6341            } else {
6342                if (DEBUG_PACKAGE_SCANNING) {
6343                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6344                        Log.v(TAG, "Want this data dir: " + dataPath);
6345                }
6346                //invoke installer to do the actual installation
6347                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6348                        pkg.applicationInfo.seinfo);
6349                if (ret < 0) {
6350                    // Error from installer
6351                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6352                            "Unable to create data dirs [errorCode=" + ret + "]");
6353                }
6354
6355                if (dataPath.exists()) {
6356                    pkg.applicationInfo.dataDir = dataPath.getPath();
6357                } else {
6358                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6359                    pkg.applicationInfo.dataDir = null;
6360                }
6361            }
6362
6363            pkgSetting.uidError = uidError;
6364        }
6365
6366        final String path = scanFile.getPath();
6367        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6368
6369        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6370            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6371        } else {
6372            if ((scanFlags & SCAN_MOVE) != 0) {
6373                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6374                // but we already have this packages package info in the PackageSetting. We just
6375                // use that and derive the native library path based on the new codepath.
6376                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6377                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6378            }
6379
6380            // Set native library paths again. For moves, the path will be updated based on the
6381            // ABIs we've determined above. For non-moves, the path will be updated based on the
6382            // ABIs we determined during compilation, but the path will depend on the final
6383            // package path (after the rename away from the stage path).
6384            setNativeLibraryPaths(pkg);
6385        }
6386
6387        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6388        final int[] userIds = sUserManager.getUserIds();
6389        synchronized (mInstallLock) {
6390            // Create a native library symlink only if we have native libraries
6391            // and if the native libraries are 32 bit libraries. We do not provide
6392            // this symlink for 64 bit libraries.
6393            if (pkg.applicationInfo.primaryCpuAbi != null &&
6394                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6395                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6396                for (int userId : userIds) {
6397                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6398                            nativeLibPath, userId) < 0) {
6399                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6400                                "Failed linking native library dir (user=" + userId + ")");
6401                    }
6402                }
6403            }
6404        }
6405
6406        // This is a special case for the "system" package, where the ABI is
6407        // dictated by the zygote configuration (and init.rc). We should keep track
6408        // of this ABI so that we can deal with "normal" applications that run under
6409        // the same UID correctly.
6410        if (mPlatformPackage == pkg) {
6411            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6412                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6413        }
6414
6415        // If there's a mismatch between the abi-override in the package setting
6416        // and the abiOverride specified for the install. Warn about this because we
6417        // would've already compiled the app without taking the package setting into
6418        // account.
6419        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
6420            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
6421                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
6422                        " for package: " + pkg.packageName);
6423            }
6424        }
6425
6426        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6427        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6428        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6429
6430        // Copy the derived override back to the parsed package, so that we can
6431        // update the package settings accordingly.
6432        pkg.cpuAbiOverride = cpuAbiOverride;
6433
6434        if (DEBUG_ABI_SELECTION) {
6435            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6436                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6437                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6438        }
6439
6440        // Push the derived path down into PackageSettings so we know what to
6441        // clean up at uninstall time.
6442        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6443
6444        if (DEBUG_ABI_SELECTION) {
6445            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6446                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6447                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6448        }
6449
6450        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6451            // We don't do this here during boot because we can do it all
6452            // at once after scanning all existing packages.
6453            //
6454            // We also do this *before* we perform dexopt on this package, so that
6455            // we can avoid redundant dexopts, and also to make sure we've got the
6456            // code and package path correct.
6457            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
6458                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
6459        }
6460
6461        if ((scanFlags & SCAN_NO_DEX) == 0) {
6462            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
6463                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
6464            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6465                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
6466            }
6467        }
6468        if (mFactoryTest && pkg.requestedPermissions.contains(
6469                android.Manifest.permission.FACTORY_TEST)) {
6470            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
6471        }
6472
6473        ArrayList<PackageParser.Package> clientLibPkgs = null;
6474
6475        // writer
6476        synchronized (mPackages) {
6477            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6478                // Only system apps can add new shared libraries.
6479                if (pkg.libraryNames != null) {
6480                    for (int i=0; i<pkg.libraryNames.size(); i++) {
6481                        String name = pkg.libraryNames.get(i);
6482                        boolean allowed = false;
6483                        if (pkg.isUpdatedSystemApp()) {
6484                            // New library entries can only be added through the
6485                            // system image.  This is important to get rid of a lot
6486                            // of nasty edge cases: for example if we allowed a non-
6487                            // system update of the app to add a library, then uninstalling
6488                            // the update would make the library go away, and assumptions
6489                            // we made such as through app install filtering would now
6490                            // have allowed apps on the device which aren't compatible
6491                            // with it.  Better to just have the restriction here, be
6492                            // conservative, and create many fewer cases that can negatively
6493                            // impact the user experience.
6494                            final PackageSetting sysPs = mSettings
6495                                    .getDisabledSystemPkgLPr(pkg.packageName);
6496                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
6497                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
6498                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
6499                                        allowed = true;
6500                                        allowed = true;
6501                                        break;
6502                                    }
6503                                }
6504                            }
6505                        } else {
6506                            allowed = true;
6507                        }
6508                        if (allowed) {
6509                            if (!mSharedLibraries.containsKey(name)) {
6510                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
6511                            } else if (!name.equals(pkg.packageName)) {
6512                                Slog.w(TAG, "Package " + pkg.packageName + " library "
6513                                        + name + " already exists; skipping");
6514                            }
6515                        } else {
6516                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
6517                                    + name + " that is not declared on system image; skipping");
6518                        }
6519                    }
6520                    if ((scanFlags&SCAN_BOOTING) == 0) {
6521                        // If we are not booting, we need to update any applications
6522                        // that are clients of our shared library.  If we are booting,
6523                        // this will all be done once the scan is complete.
6524                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
6525                    }
6526                }
6527            }
6528        }
6529
6530        // We also need to dexopt any apps that are dependent on this library.  Note that
6531        // if these fail, we should abort the install since installing the library will
6532        // result in some apps being broken.
6533        if (clientLibPkgs != null) {
6534            if ((scanFlags & SCAN_NO_DEX) == 0) {
6535                for (int i = 0; i < clientLibPkgs.size(); i++) {
6536                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
6537                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
6538                            null /* instruction sets */, forceDex,
6539                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
6540                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6541                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
6542                                "scanPackageLI failed to dexopt clientLibPkgs");
6543                    }
6544                }
6545            }
6546        }
6547
6548        // Also need to kill any apps that are dependent on the library.
6549        if (clientLibPkgs != null) {
6550            for (int i=0; i<clientLibPkgs.size(); i++) {
6551                PackageParser.Package clientPkg = clientLibPkgs.get(i);
6552                killApplication(clientPkg.applicationInfo.packageName,
6553                        clientPkg.applicationInfo.uid, "update lib");
6554            }
6555        }
6556
6557        // writer
6558        synchronized (mPackages) {
6559            // We don't expect installation to fail beyond this point
6560
6561            // Add the new setting to mSettings
6562            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
6563            // Add the new setting to mPackages
6564            mPackages.put(pkg.applicationInfo.packageName, pkg);
6565            // Make sure we don't accidentally delete its data.
6566            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
6567            while (iter.hasNext()) {
6568                PackageCleanItem item = iter.next();
6569                if (pkgName.equals(item.packageName)) {
6570                    iter.remove();
6571                }
6572            }
6573
6574            // Take care of first install / last update times.
6575            if (currentTime != 0) {
6576                if (pkgSetting.firstInstallTime == 0) {
6577                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
6578                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
6579                    pkgSetting.lastUpdateTime = currentTime;
6580                }
6581            } else if (pkgSetting.firstInstallTime == 0) {
6582                // We need *something*.  Take time time stamp of the file.
6583                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
6584            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
6585                if (scanFileTime != pkgSetting.timeStamp) {
6586                    // A package on the system image has changed; consider this
6587                    // to be an update.
6588                    pkgSetting.lastUpdateTime = scanFileTime;
6589                }
6590            }
6591
6592            // Add the package's KeySets to the global KeySetManagerService
6593            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6594            try {
6595                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
6596                if (pkg.mKeySetMapping != null) {
6597                    ksms.addDefinedKeySetsToPackageLPw(pkg.packageName, pkg.mKeySetMapping);
6598                    if (pkg.mUpgradeKeySets != null) {
6599                        ksms.addUpgradeKeySetsToPackageLPw(pkg.packageName, pkg.mUpgradeKeySets);
6600                    }
6601                }
6602            } catch (NullPointerException e) {
6603                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
6604            } catch (IllegalArgumentException e) {
6605                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
6606            }
6607
6608            int N = pkg.providers.size();
6609            StringBuilder r = null;
6610            int i;
6611            for (i=0; i<N; i++) {
6612                PackageParser.Provider p = pkg.providers.get(i);
6613                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
6614                        p.info.processName, pkg.applicationInfo.uid);
6615                mProviders.addProvider(p);
6616                p.syncable = p.info.isSyncable;
6617                if (p.info.authority != null) {
6618                    String names[] = p.info.authority.split(";");
6619                    p.info.authority = null;
6620                    for (int j = 0; j < names.length; j++) {
6621                        if (j == 1 && p.syncable) {
6622                            // We only want the first authority for a provider to possibly be
6623                            // syncable, so if we already added this provider using a different
6624                            // authority clear the syncable flag. We copy the provider before
6625                            // changing it because the mProviders object contains a reference
6626                            // to a provider that we don't want to change.
6627                            // Only do this for the second authority since the resulting provider
6628                            // object can be the same for all future authorities for this provider.
6629                            p = new PackageParser.Provider(p);
6630                            p.syncable = false;
6631                        }
6632                        if (!mProvidersByAuthority.containsKey(names[j])) {
6633                            mProvidersByAuthority.put(names[j], p);
6634                            if (p.info.authority == null) {
6635                                p.info.authority = names[j];
6636                            } else {
6637                                p.info.authority = p.info.authority + ";" + names[j];
6638                            }
6639                            if (DEBUG_PACKAGE_SCANNING) {
6640                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6641                                    Log.d(TAG, "Registered content provider: " + names[j]
6642                                            + ", className = " + p.info.name + ", isSyncable = "
6643                                            + p.info.isSyncable);
6644                            }
6645                        } else {
6646                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6647                            Slog.w(TAG, "Skipping provider name " + names[j] +
6648                                    " (in package " + pkg.applicationInfo.packageName +
6649                                    "): name already used by "
6650                                    + ((other != null && other.getComponentName() != null)
6651                                            ? other.getComponentName().getPackageName() : "?"));
6652                        }
6653                    }
6654                }
6655                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6656                    if (r == null) {
6657                        r = new StringBuilder(256);
6658                    } else {
6659                        r.append(' ');
6660                    }
6661                    r.append(p.info.name);
6662                }
6663            }
6664            if (r != null) {
6665                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
6666            }
6667
6668            N = pkg.services.size();
6669            r = null;
6670            for (i=0; i<N; i++) {
6671                PackageParser.Service s = pkg.services.get(i);
6672                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
6673                        s.info.processName, pkg.applicationInfo.uid);
6674                mServices.addService(s);
6675                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6676                    if (r == null) {
6677                        r = new StringBuilder(256);
6678                    } else {
6679                        r.append(' ');
6680                    }
6681                    r.append(s.info.name);
6682                }
6683            }
6684            if (r != null) {
6685                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
6686            }
6687
6688            N = pkg.receivers.size();
6689            r = null;
6690            for (i=0; i<N; i++) {
6691                PackageParser.Activity a = pkg.receivers.get(i);
6692                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6693                        a.info.processName, pkg.applicationInfo.uid);
6694                mReceivers.addActivity(a, "receiver");
6695                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6696                    if (r == null) {
6697                        r = new StringBuilder(256);
6698                    } else {
6699                        r.append(' ');
6700                    }
6701                    r.append(a.info.name);
6702                }
6703            }
6704            if (r != null) {
6705                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
6706            }
6707
6708            N = pkg.activities.size();
6709            r = null;
6710            for (i=0; i<N; i++) {
6711                PackageParser.Activity a = pkg.activities.get(i);
6712                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6713                        a.info.processName, pkg.applicationInfo.uid);
6714                mActivities.addActivity(a, "activity");
6715                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6716                    if (r == null) {
6717                        r = new StringBuilder(256);
6718                    } else {
6719                        r.append(' ');
6720                    }
6721                    r.append(a.info.name);
6722                }
6723            }
6724            if (r != null) {
6725                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
6726            }
6727
6728            N = pkg.permissionGroups.size();
6729            r = null;
6730            for (i=0; i<N; i++) {
6731                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
6732                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
6733                if (cur == null) {
6734                    mPermissionGroups.put(pg.info.name, pg);
6735                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6736                        if (r == null) {
6737                            r = new StringBuilder(256);
6738                        } else {
6739                            r.append(' ');
6740                        }
6741                        r.append(pg.info.name);
6742                    }
6743                } else {
6744                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
6745                            + pg.info.packageName + " ignored: original from "
6746                            + cur.info.packageName);
6747                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6748                        if (r == null) {
6749                            r = new StringBuilder(256);
6750                        } else {
6751                            r.append(' ');
6752                        }
6753                        r.append("DUP:");
6754                        r.append(pg.info.name);
6755                    }
6756                }
6757            }
6758            if (r != null) {
6759                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6760            }
6761
6762            N = pkg.permissions.size();
6763            r = null;
6764            for (i=0; i<N; i++) {
6765                PackageParser.Permission p = pkg.permissions.get(i);
6766
6767                // Now that permission groups have a special meaning, we ignore permission
6768                // groups for legacy apps to prevent unexpected behavior. In particular,
6769                // permissions for one app being granted to someone just becuase they happen
6770                // to be in a group defined by another app (before this had no implications).
6771                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
6772                    p.group = mPermissionGroups.get(p.info.group);
6773                    // Warn for a permission in an unknown group.
6774                    if (p.info.group != null && p.group == null) {
6775                        Slog.w(TAG, "Permission " + p.info.name + " from package "
6776                                + p.info.packageName + " in an unknown group " + p.info.group);
6777                    }
6778                }
6779
6780                ArrayMap<String, BasePermission> permissionMap =
6781                        p.tree ? mSettings.mPermissionTrees
6782                                : mSettings.mPermissions;
6783                BasePermission bp = permissionMap.get(p.info.name);
6784
6785                // Allow system apps to redefine non-system permissions
6786                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
6787                    final boolean currentOwnerIsSystem = (bp.perm != null
6788                            && isSystemApp(bp.perm.owner));
6789                    if (isSystemApp(p.owner)) {
6790                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
6791                            // It's a built-in permission and no owner, take ownership now
6792                            bp.packageSetting = pkgSetting;
6793                            bp.perm = p;
6794                            bp.uid = pkg.applicationInfo.uid;
6795                            bp.sourcePackage = p.info.packageName;
6796                        } else if (!currentOwnerIsSystem) {
6797                            String msg = "New decl " + p.owner + " of permission  "
6798                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
6799                            reportSettingsProblem(Log.WARN, msg);
6800                            bp = null;
6801                        }
6802                    }
6803                }
6804
6805                if (bp == null) {
6806                    bp = new BasePermission(p.info.name, p.info.packageName,
6807                            BasePermission.TYPE_NORMAL);
6808                    permissionMap.put(p.info.name, bp);
6809                }
6810
6811                if (bp.perm == null) {
6812                    if (bp.sourcePackage == null
6813                            || bp.sourcePackage.equals(p.info.packageName)) {
6814                        BasePermission tree = findPermissionTreeLP(p.info.name);
6815                        if (tree == null
6816                                || tree.sourcePackage.equals(p.info.packageName)) {
6817                            bp.packageSetting = pkgSetting;
6818                            bp.perm = p;
6819                            bp.uid = pkg.applicationInfo.uid;
6820                            bp.sourcePackage = p.info.packageName;
6821                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6822                                if (r == null) {
6823                                    r = new StringBuilder(256);
6824                                } else {
6825                                    r.append(' ');
6826                                }
6827                                r.append(p.info.name);
6828                            }
6829                        } else {
6830                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6831                                    + p.info.packageName + " ignored: base tree "
6832                                    + tree.name + " is from package "
6833                                    + tree.sourcePackage);
6834                        }
6835                    } else {
6836                        Slog.w(TAG, "Permission " + p.info.name + " from package "
6837                                + p.info.packageName + " ignored: original from "
6838                                + bp.sourcePackage);
6839                    }
6840                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6841                    if (r == null) {
6842                        r = new StringBuilder(256);
6843                    } else {
6844                        r.append(' ');
6845                    }
6846                    r.append("DUP:");
6847                    r.append(p.info.name);
6848                }
6849                if (bp.perm == p) {
6850                    bp.protectionLevel = p.info.protectionLevel;
6851                }
6852            }
6853
6854            if (r != null) {
6855                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6856            }
6857
6858            N = pkg.instrumentation.size();
6859            r = null;
6860            for (i=0; i<N; i++) {
6861                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6862                a.info.packageName = pkg.applicationInfo.packageName;
6863                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6864                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6865                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6866                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6867                a.info.dataDir = pkg.applicationInfo.dataDir;
6868
6869                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6870                // need other information about the application, like the ABI and what not ?
6871                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6872                mInstrumentation.put(a.getComponentName(), a);
6873                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6874                    if (r == null) {
6875                        r = new StringBuilder(256);
6876                    } else {
6877                        r.append(' ');
6878                    }
6879                    r.append(a.info.name);
6880                }
6881            }
6882            if (r != null) {
6883                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6884            }
6885
6886            if (pkg.protectedBroadcasts != null) {
6887                N = pkg.protectedBroadcasts.size();
6888                for (i=0; i<N; i++) {
6889                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6890                }
6891            }
6892
6893            pkgSetting.setTimeStamp(scanFileTime);
6894
6895            // Create idmap files for pairs of (packages, overlay packages).
6896            // Note: "android", ie framework-res.apk, is handled by native layers.
6897            if (pkg.mOverlayTarget != null) {
6898                // This is an overlay package.
6899                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6900                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6901                        mOverlays.put(pkg.mOverlayTarget,
6902                                new ArrayMap<String, PackageParser.Package>());
6903                    }
6904                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6905                    map.put(pkg.packageName, pkg);
6906                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6907                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6908                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6909                                "scanPackageLI failed to createIdmap");
6910                    }
6911                }
6912            } else if (mOverlays.containsKey(pkg.packageName) &&
6913                    !pkg.packageName.equals("android")) {
6914                // This is a regular package, with one or more known overlay packages.
6915                createIdmapsForPackageLI(pkg);
6916            }
6917        }
6918
6919        return pkg;
6920    }
6921
6922    /**
6923     * Derive the ABI of a non-system package located at {@code scanFile}. This information
6924     * is derived purely on the basis of the contents of {@code scanFile} and
6925     * {@code cpuAbiOverride}.
6926     *
6927     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
6928     */
6929    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
6930                                 String cpuAbiOverride, boolean extractLibs)
6931            throws PackageManagerException {
6932        // TODO: We can probably be smarter about this stuff. For installed apps,
6933        // we can calculate this information at install time once and for all. For
6934        // system apps, we can probably assume that this information doesn't change
6935        // after the first boot scan. As things stand, we do lots of unnecessary work.
6936
6937        // Give ourselves some initial paths; we'll come back for another
6938        // pass once we've determined ABI below.
6939        setNativeLibraryPaths(pkg);
6940
6941        // We would never need to extract libs for forward-locked and external packages,
6942        // since the container service will do it for us. We shouldn't attempt to
6943        // extract libs from system app when it was not updated.
6944        if (pkg.isForwardLocked() || isExternal(pkg) ||
6945            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
6946            extractLibs = false;
6947        }
6948
6949        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
6950        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
6951
6952        NativeLibraryHelper.Handle handle = null;
6953        try {
6954            handle = NativeLibraryHelper.Handle.create(scanFile);
6955            // TODO(multiArch): This can be null for apps that didn't go through the
6956            // usual installation process. We can calculate it again, like we
6957            // do during install time.
6958            //
6959            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
6960            // unnecessary.
6961            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
6962
6963            // Null out the abis so that they can be recalculated.
6964            pkg.applicationInfo.primaryCpuAbi = null;
6965            pkg.applicationInfo.secondaryCpuAbi = null;
6966            if (isMultiArch(pkg.applicationInfo)) {
6967                // Warn if we've set an abiOverride for multi-lib packages..
6968                // By definition, we need to copy both 32 and 64 bit libraries for
6969                // such packages.
6970                if (pkg.cpuAbiOverride != null
6971                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
6972                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
6973                }
6974
6975                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
6976                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
6977                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
6978                    if (extractLibs) {
6979                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
6980                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
6981                                useIsaSpecificSubdirs);
6982                    } else {
6983                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
6984                    }
6985                }
6986
6987                maybeThrowExceptionForMultiArchCopy(
6988                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
6989
6990                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
6991                    if (extractLibs) {
6992                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
6993                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
6994                                useIsaSpecificSubdirs);
6995                    } else {
6996                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
6997                    }
6998                }
6999
7000                maybeThrowExceptionForMultiArchCopy(
7001                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7002
7003                if (abi64 >= 0) {
7004                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7005                }
7006
7007                if (abi32 >= 0) {
7008                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7009                    if (abi64 >= 0) {
7010                        pkg.applicationInfo.secondaryCpuAbi = abi;
7011                    } else {
7012                        pkg.applicationInfo.primaryCpuAbi = abi;
7013                    }
7014                }
7015            } else {
7016                String[] abiList = (cpuAbiOverride != null) ?
7017                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7018
7019                // Enable gross and lame hacks for apps that are built with old
7020                // SDK tools. We must scan their APKs for renderscript bitcode and
7021                // not launch them if it's present. Don't bother checking on devices
7022                // that don't have 64 bit support.
7023                boolean needsRenderScriptOverride = false;
7024                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7025                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7026                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7027                    needsRenderScriptOverride = true;
7028                }
7029
7030                final int copyRet;
7031                if (extractLibs) {
7032                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7033                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7034                } else {
7035                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7036                }
7037
7038                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7039                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7040                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7041                }
7042
7043                if (copyRet >= 0) {
7044                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7045                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7046                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7047                } else if (needsRenderScriptOverride) {
7048                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7049                }
7050            }
7051        } catch (IOException ioe) {
7052            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7053        } finally {
7054            IoUtils.closeQuietly(handle);
7055        }
7056
7057        // Now that we've calculated the ABIs and determined if it's an internal app,
7058        // we will go ahead and populate the nativeLibraryPath.
7059        setNativeLibraryPaths(pkg);
7060    }
7061
7062    /**
7063     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7064     * i.e, so that all packages can be run inside a single process if required.
7065     *
7066     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7067     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7068     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7069     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7070     * updating a package that belongs to a shared user.
7071     *
7072     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7073     * adds unnecessary complexity.
7074     */
7075    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7076            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7077        String requiredInstructionSet = null;
7078        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7079            requiredInstructionSet = VMRuntime.getInstructionSet(
7080                     scannedPackage.applicationInfo.primaryCpuAbi);
7081        }
7082
7083        PackageSetting requirer = null;
7084        for (PackageSetting ps : packagesForUser) {
7085            // If packagesForUser contains scannedPackage, we skip it. This will happen
7086            // when scannedPackage is an update of an existing package. Without this check,
7087            // we will never be able to change the ABI of any package belonging to a shared
7088            // user, even if it's compatible with other packages.
7089            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7090                if (ps.primaryCpuAbiString == null) {
7091                    continue;
7092                }
7093
7094                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7095                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7096                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7097                    // this but there's not much we can do.
7098                    String errorMessage = "Instruction set mismatch, "
7099                            + ((requirer == null) ? "[caller]" : requirer)
7100                            + " requires " + requiredInstructionSet + " whereas " + ps
7101                            + " requires " + instructionSet;
7102                    Slog.w(TAG, errorMessage);
7103                }
7104
7105                if (requiredInstructionSet == null) {
7106                    requiredInstructionSet = instructionSet;
7107                    requirer = ps;
7108                }
7109            }
7110        }
7111
7112        if (requiredInstructionSet != null) {
7113            String adjustedAbi;
7114            if (requirer != null) {
7115                // requirer != null implies that either scannedPackage was null or that scannedPackage
7116                // did not require an ABI, in which case we have to adjust scannedPackage to match
7117                // the ABI of the set (which is the same as requirer's ABI)
7118                adjustedAbi = requirer.primaryCpuAbiString;
7119                if (scannedPackage != null) {
7120                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7121                }
7122            } else {
7123                // requirer == null implies that we're updating all ABIs in the set to
7124                // match scannedPackage.
7125                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7126            }
7127
7128            for (PackageSetting ps : packagesForUser) {
7129                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7130                    if (ps.primaryCpuAbiString != null) {
7131                        continue;
7132                    }
7133
7134                    ps.primaryCpuAbiString = adjustedAbi;
7135                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7136                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7137                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7138
7139                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7140                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7141                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7142                            ps.primaryCpuAbiString = null;
7143                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7144                            return;
7145                        } else {
7146                            mInstaller.rmdex(ps.codePathString,
7147                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7148                        }
7149                    }
7150                }
7151            }
7152        }
7153    }
7154
7155    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7156        synchronized (mPackages) {
7157            mResolverReplaced = true;
7158            // Set up information for custom user intent resolution activity.
7159            mResolveActivity.applicationInfo = pkg.applicationInfo;
7160            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7161            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7162            mResolveActivity.processName = pkg.applicationInfo.packageName;
7163            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7164            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7165                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7166            mResolveActivity.theme = 0;
7167            mResolveActivity.exported = true;
7168            mResolveActivity.enabled = true;
7169            mResolveInfo.activityInfo = mResolveActivity;
7170            mResolveInfo.priority = 0;
7171            mResolveInfo.preferredOrder = 0;
7172            mResolveInfo.match = 0;
7173            mResolveComponentName = mCustomResolverComponentName;
7174            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7175                    mResolveComponentName);
7176        }
7177    }
7178
7179    private static String calculateBundledApkRoot(final String codePathString) {
7180        final File codePath = new File(codePathString);
7181        final File codeRoot;
7182        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7183            codeRoot = Environment.getRootDirectory();
7184        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7185            codeRoot = Environment.getOemDirectory();
7186        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7187            codeRoot = Environment.getVendorDirectory();
7188        } else {
7189            // Unrecognized code path; take its top real segment as the apk root:
7190            // e.g. /something/app/blah.apk => /something
7191            try {
7192                File f = codePath.getCanonicalFile();
7193                File parent = f.getParentFile();    // non-null because codePath is a file
7194                File tmp;
7195                while ((tmp = parent.getParentFile()) != null) {
7196                    f = parent;
7197                    parent = tmp;
7198                }
7199                codeRoot = f;
7200                Slog.w(TAG, "Unrecognized code path "
7201                        + codePath + " - using " + codeRoot);
7202            } catch (IOException e) {
7203                // Can't canonicalize the code path -- shenanigans?
7204                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7205                return Environment.getRootDirectory().getPath();
7206            }
7207        }
7208        return codeRoot.getPath();
7209    }
7210
7211    /**
7212     * Derive and set the location of native libraries for the given package,
7213     * which varies depending on where and how the package was installed.
7214     */
7215    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7216        final ApplicationInfo info = pkg.applicationInfo;
7217        final String codePath = pkg.codePath;
7218        final File codeFile = new File(codePath);
7219        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7220        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7221
7222        info.nativeLibraryRootDir = null;
7223        info.nativeLibraryRootRequiresIsa = false;
7224        info.nativeLibraryDir = null;
7225        info.secondaryNativeLibraryDir = null;
7226
7227        if (isApkFile(codeFile)) {
7228            // Monolithic install
7229            if (bundledApp) {
7230                // If "/system/lib64/apkname" exists, assume that is the per-package
7231                // native library directory to use; otherwise use "/system/lib/apkname".
7232                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7233                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7234                        getPrimaryInstructionSet(info));
7235
7236                // This is a bundled system app so choose the path based on the ABI.
7237                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7238                // is just the default path.
7239                final String apkName = deriveCodePathName(codePath);
7240                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7241                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7242                        apkName).getAbsolutePath();
7243
7244                if (info.secondaryCpuAbi != null) {
7245                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7246                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7247                            secondaryLibDir, apkName).getAbsolutePath();
7248                }
7249            } else if (asecApp) {
7250                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7251                        .getAbsolutePath();
7252            } else {
7253                final String apkName = deriveCodePathName(codePath);
7254                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7255                        .getAbsolutePath();
7256            }
7257
7258            info.nativeLibraryRootRequiresIsa = false;
7259            info.nativeLibraryDir = info.nativeLibraryRootDir;
7260        } else {
7261            // Cluster install
7262            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7263            info.nativeLibraryRootRequiresIsa = true;
7264
7265            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7266                    getPrimaryInstructionSet(info)).getAbsolutePath();
7267
7268            if (info.secondaryCpuAbi != null) {
7269                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7270                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7271            }
7272        }
7273    }
7274
7275    /**
7276     * Deduces the ABI of a bundled app and sets the relevant fields on the
7277     * parsed pkg object.
7278     *
7279     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7280     *        under which system libraries are installed.
7281     * @param apkName the name of the installed package.
7282     */
7283    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7284        final File codeFile = new File(pkg.codePath);
7285
7286        final boolean has64BitLibs;
7287        final boolean has32BitLibs;
7288        if (isApkFile(codeFile)) {
7289            // Monolithic install
7290            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7291            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7292        } else {
7293            // Cluster install
7294            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7295            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7296                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7297                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7298                has64BitLibs = (new File(rootDir, isa)).exists();
7299            } else {
7300                has64BitLibs = false;
7301            }
7302            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7303                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7304                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7305                has32BitLibs = (new File(rootDir, isa)).exists();
7306            } else {
7307                has32BitLibs = false;
7308            }
7309        }
7310
7311        if (has64BitLibs && !has32BitLibs) {
7312            // The package has 64 bit libs, but not 32 bit libs. Its primary
7313            // ABI should be 64 bit. We can safely assume here that the bundled
7314            // native libraries correspond to the most preferred ABI in the list.
7315
7316            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7317            pkg.applicationInfo.secondaryCpuAbi = null;
7318        } else if (has32BitLibs && !has64BitLibs) {
7319            // The package has 32 bit libs but not 64 bit libs. Its primary
7320            // ABI should be 32 bit.
7321
7322            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7323            pkg.applicationInfo.secondaryCpuAbi = null;
7324        } else if (has32BitLibs && has64BitLibs) {
7325            // The application has both 64 and 32 bit bundled libraries. We check
7326            // here that the app declares multiArch support, and warn if it doesn't.
7327            //
7328            // We will be lenient here and record both ABIs. The primary will be the
7329            // ABI that's higher on the list, i.e, a device that's configured to prefer
7330            // 64 bit apps will see a 64 bit primary ABI,
7331
7332            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7333                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7334            }
7335
7336            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7337                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7338                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7339            } else {
7340                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7341                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7342            }
7343        } else {
7344            pkg.applicationInfo.primaryCpuAbi = null;
7345            pkg.applicationInfo.secondaryCpuAbi = null;
7346        }
7347    }
7348
7349    private void killApplication(String pkgName, int appId, String reason) {
7350        // Request the ActivityManager to kill the process(only for existing packages)
7351        // so that we do not end up in a confused state while the user is still using the older
7352        // version of the application while the new one gets installed.
7353        IActivityManager am = ActivityManagerNative.getDefault();
7354        if (am != null) {
7355            try {
7356                am.killApplicationWithAppId(pkgName, appId, reason);
7357            } catch (RemoteException e) {
7358            }
7359        }
7360    }
7361
7362    void removePackageLI(PackageSetting ps, boolean chatty) {
7363        if (DEBUG_INSTALL) {
7364            if (chatty)
7365                Log.d(TAG, "Removing package " + ps.name);
7366        }
7367
7368        // writer
7369        synchronized (mPackages) {
7370            mPackages.remove(ps.name);
7371            final PackageParser.Package pkg = ps.pkg;
7372            if (pkg != null) {
7373                cleanPackageDataStructuresLILPw(pkg, chatty);
7374            }
7375        }
7376    }
7377
7378    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7379        if (DEBUG_INSTALL) {
7380            if (chatty)
7381                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7382        }
7383
7384        // writer
7385        synchronized (mPackages) {
7386            mPackages.remove(pkg.applicationInfo.packageName);
7387            cleanPackageDataStructuresLILPw(pkg, chatty);
7388        }
7389    }
7390
7391    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7392        int N = pkg.providers.size();
7393        StringBuilder r = null;
7394        int i;
7395        for (i=0; i<N; i++) {
7396            PackageParser.Provider p = pkg.providers.get(i);
7397            mProviders.removeProvider(p);
7398            if (p.info.authority == null) {
7399
7400                /* There was another ContentProvider with this authority when
7401                 * this app was installed so this authority is null,
7402                 * Ignore it as we don't have to unregister the provider.
7403                 */
7404                continue;
7405            }
7406            String names[] = p.info.authority.split(";");
7407            for (int j = 0; j < names.length; j++) {
7408                if (mProvidersByAuthority.get(names[j]) == p) {
7409                    mProvidersByAuthority.remove(names[j]);
7410                    if (DEBUG_REMOVE) {
7411                        if (chatty)
7412                            Log.d(TAG, "Unregistered content provider: " + names[j]
7413                                    + ", className = " + p.info.name + ", isSyncable = "
7414                                    + p.info.isSyncable);
7415                    }
7416                }
7417            }
7418            if (DEBUG_REMOVE && chatty) {
7419                if (r == null) {
7420                    r = new StringBuilder(256);
7421                } else {
7422                    r.append(' ');
7423                }
7424                r.append(p.info.name);
7425            }
7426        }
7427        if (r != null) {
7428            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7429        }
7430
7431        N = pkg.services.size();
7432        r = null;
7433        for (i=0; i<N; i++) {
7434            PackageParser.Service s = pkg.services.get(i);
7435            mServices.removeService(s);
7436            if (chatty) {
7437                if (r == null) {
7438                    r = new StringBuilder(256);
7439                } else {
7440                    r.append(' ');
7441                }
7442                r.append(s.info.name);
7443            }
7444        }
7445        if (r != null) {
7446            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
7447        }
7448
7449        N = pkg.receivers.size();
7450        r = null;
7451        for (i=0; i<N; i++) {
7452            PackageParser.Activity a = pkg.receivers.get(i);
7453            mReceivers.removeActivity(a, "receiver");
7454            if (DEBUG_REMOVE && chatty) {
7455                if (r == null) {
7456                    r = new StringBuilder(256);
7457                } else {
7458                    r.append(' ');
7459                }
7460                r.append(a.info.name);
7461            }
7462        }
7463        if (r != null) {
7464            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
7465        }
7466
7467        N = pkg.activities.size();
7468        r = null;
7469        for (i=0; i<N; i++) {
7470            PackageParser.Activity a = pkg.activities.get(i);
7471            mActivities.removeActivity(a, "activity");
7472            if (DEBUG_REMOVE && chatty) {
7473                if (r == null) {
7474                    r = new StringBuilder(256);
7475                } else {
7476                    r.append(' ');
7477                }
7478                r.append(a.info.name);
7479            }
7480        }
7481        if (r != null) {
7482            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
7483        }
7484
7485        N = pkg.permissions.size();
7486        r = null;
7487        for (i=0; i<N; i++) {
7488            PackageParser.Permission p = pkg.permissions.get(i);
7489            BasePermission bp = mSettings.mPermissions.get(p.info.name);
7490            if (bp == null) {
7491                bp = mSettings.mPermissionTrees.get(p.info.name);
7492            }
7493            if (bp != null && bp.perm == p) {
7494                bp.perm = null;
7495                if (DEBUG_REMOVE && chatty) {
7496                    if (r == null) {
7497                        r = new StringBuilder(256);
7498                    } else {
7499                        r.append(' ');
7500                    }
7501                    r.append(p.info.name);
7502                }
7503            }
7504            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7505                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
7506                if (appOpPerms != null) {
7507                    appOpPerms.remove(pkg.packageName);
7508                }
7509            }
7510        }
7511        if (r != null) {
7512            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7513        }
7514
7515        N = pkg.requestedPermissions.size();
7516        r = null;
7517        for (i=0; i<N; i++) {
7518            String perm = pkg.requestedPermissions.get(i);
7519            BasePermission bp = mSettings.mPermissions.get(perm);
7520            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7521                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
7522                if (appOpPerms != null) {
7523                    appOpPerms.remove(pkg.packageName);
7524                    if (appOpPerms.isEmpty()) {
7525                        mAppOpPermissionPackages.remove(perm);
7526                    }
7527                }
7528            }
7529        }
7530        if (r != null) {
7531            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7532        }
7533
7534        N = pkg.instrumentation.size();
7535        r = null;
7536        for (i=0; i<N; i++) {
7537            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7538            mInstrumentation.remove(a.getComponentName());
7539            if (DEBUG_REMOVE && chatty) {
7540                if (r == null) {
7541                    r = new StringBuilder(256);
7542                } else {
7543                    r.append(' ');
7544                }
7545                r.append(a.info.name);
7546            }
7547        }
7548        if (r != null) {
7549            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
7550        }
7551
7552        r = null;
7553        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7554            // Only system apps can hold shared libraries.
7555            if (pkg.libraryNames != null) {
7556                for (i=0; i<pkg.libraryNames.size(); i++) {
7557                    String name = pkg.libraryNames.get(i);
7558                    SharedLibraryEntry cur = mSharedLibraries.get(name);
7559                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
7560                        mSharedLibraries.remove(name);
7561                        if (DEBUG_REMOVE && chatty) {
7562                            if (r == null) {
7563                                r = new StringBuilder(256);
7564                            } else {
7565                                r.append(' ');
7566                            }
7567                            r.append(name);
7568                        }
7569                    }
7570                }
7571            }
7572        }
7573        if (r != null) {
7574            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
7575        }
7576    }
7577
7578    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
7579        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
7580            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
7581                return true;
7582            }
7583        }
7584        return false;
7585    }
7586
7587    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
7588    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
7589    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
7590
7591    private void updatePermissionsLPw(String changingPkg,
7592            PackageParser.Package pkgInfo, int flags) {
7593        // Make sure there are no dangling permission trees.
7594        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
7595        while (it.hasNext()) {
7596            final BasePermission bp = it.next();
7597            if (bp.packageSetting == null) {
7598                // We may not yet have parsed the package, so just see if
7599                // we still know about its settings.
7600                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7601            }
7602            if (bp.packageSetting == null) {
7603                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
7604                        + " from package " + bp.sourcePackage);
7605                it.remove();
7606            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7607                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7608                    Slog.i(TAG, "Removing old permission tree: " + bp.name
7609                            + " from package " + bp.sourcePackage);
7610                    flags |= UPDATE_PERMISSIONS_ALL;
7611                    it.remove();
7612                }
7613            }
7614        }
7615
7616        // Make sure all dynamic permissions have been assigned to a package,
7617        // and make sure there are no dangling permissions.
7618        it = mSettings.mPermissions.values().iterator();
7619        while (it.hasNext()) {
7620            final BasePermission bp = it.next();
7621            if (bp.type == BasePermission.TYPE_DYNAMIC) {
7622                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
7623                        + bp.name + " pkg=" + bp.sourcePackage
7624                        + " info=" + bp.pendingInfo);
7625                if (bp.packageSetting == null && bp.pendingInfo != null) {
7626                    final BasePermission tree = findPermissionTreeLP(bp.name);
7627                    if (tree != null && tree.perm != null) {
7628                        bp.packageSetting = tree.packageSetting;
7629                        bp.perm = new PackageParser.Permission(tree.perm.owner,
7630                                new PermissionInfo(bp.pendingInfo));
7631                        bp.perm.info.packageName = tree.perm.info.packageName;
7632                        bp.perm.info.name = bp.name;
7633                        bp.uid = tree.uid;
7634                    }
7635                }
7636            }
7637            if (bp.packageSetting == null) {
7638                // We may not yet have parsed the package, so just see if
7639                // we still know about its settings.
7640                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7641            }
7642            if (bp.packageSetting == null) {
7643                Slog.w(TAG, "Removing dangling permission: " + bp.name
7644                        + " from package " + bp.sourcePackage);
7645                it.remove();
7646            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7647                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7648                    Slog.i(TAG, "Removing old permission: " + bp.name
7649                            + " from package " + bp.sourcePackage);
7650                    flags |= UPDATE_PERMISSIONS_ALL;
7651                    it.remove();
7652                }
7653            }
7654        }
7655
7656        // Now update the permissions for all packages, in particular
7657        // replace the granted permissions of the system packages.
7658        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
7659            for (PackageParser.Package pkg : mPackages.values()) {
7660                if (pkg != pkgInfo) {
7661                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
7662                            changingPkg);
7663                }
7664            }
7665        }
7666
7667        if (pkgInfo != null) {
7668            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
7669        }
7670    }
7671
7672    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
7673            String packageOfInterest) {
7674        // IMPORTANT: There are two types of permissions: install and runtime.
7675        // Install time permissions are granted when the app is installed to
7676        // all device users and users added in the future. Runtime permissions
7677        // are granted at runtime explicitly to specific users. Normal and signature
7678        // protected permissions are install time permissions. Dangerous permissions
7679        // are install permissions if the app's target SDK is Lollipop MR1 or older,
7680        // otherwise they are runtime permissions. This function does not manage
7681        // runtime permissions except for the case an app targeting Lollipop MR1
7682        // being upgraded to target a newer SDK, in which case dangerous permissions
7683        // are transformed from install time to runtime ones.
7684
7685        final PackageSetting ps = (PackageSetting) pkg.mExtras;
7686        if (ps == null) {
7687            return;
7688        }
7689
7690        PermissionsState permissionsState = ps.getPermissionsState();
7691        PermissionsState origPermissions = permissionsState;
7692
7693        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
7694
7695        int[] upgradeUserIds = EMPTY_INT_ARRAY;
7696        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
7697
7698        boolean changedInstallPermission = false;
7699
7700        if (replace) {
7701            ps.installPermissionsFixed = false;
7702            if (!ps.isSharedUser()) {
7703                origPermissions = new PermissionsState(permissionsState);
7704                permissionsState.reset();
7705            }
7706        }
7707
7708        permissionsState.setGlobalGids(mGlobalGids);
7709
7710        final int N = pkg.requestedPermissions.size();
7711        for (int i=0; i<N; i++) {
7712            final String name = pkg.requestedPermissions.get(i);
7713            final BasePermission bp = mSettings.mPermissions.get(name);
7714
7715            if (DEBUG_INSTALL) {
7716                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
7717            }
7718
7719            if (bp == null || bp.packageSetting == null) {
7720                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7721                    Slog.w(TAG, "Unknown permission " + name
7722                            + " in package " + pkg.packageName);
7723                }
7724                continue;
7725            }
7726
7727            final String perm = bp.name;
7728            boolean allowedSig = false;
7729            int grant = GRANT_DENIED;
7730
7731            // Keep track of app op permissions.
7732            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7733                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
7734                if (pkgs == null) {
7735                    pkgs = new ArraySet<>();
7736                    mAppOpPermissionPackages.put(bp.name, pkgs);
7737                }
7738                pkgs.add(pkg.packageName);
7739            }
7740
7741            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
7742            switch (level) {
7743                case PermissionInfo.PROTECTION_NORMAL: {
7744                    // For all apps normal permissions are install time ones.
7745                    grant = GRANT_INSTALL;
7746                } break;
7747
7748                case PermissionInfo.PROTECTION_DANGEROUS: {
7749                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
7750                        // For legacy apps dangerous permissions are install time ones.
7751                        grant = GRANT_INSTALL_LEGACY;
7752                    } else if (ps.isSystem()) {
7753                        final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds();
7754                        if (origPermissions.hasInstallPermission(bp.name)) {
7755                            // If a system app had an install permission, then the app was
7756                            // upgraded and we grant the permissions as runtime to all users.
7757                            grant = GRANT_UPGRADE;
7758                            upgradeUserIds = currentUserIds;
7759                        } else if (!Arrays.equals(updatedUserIds, currentUserIds)) {
7760                            // If users changed since the last permissions update for a
7761                            // system app, we grant the permission as runtime to the new users.
7762                            grant = GRANT_UPGRADE;
7763                            upgradeUserIds = currentUserIds;
7764                            for (int userId : updatedUserIds) {
7765                                upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId);
7766                            }
7767                        } else {
7768                            // Otherwise, we grant the permission as runtime if the app
7769                            // already had it, i.e. we preserve runtime permissions.
7770                            grant = GRANT_RUNTIME;
7771                        }
7772                    } else if (origPermissions.hasInstallPermission(bp.name)) {
7773                        // For legacy apps that became modern, install becomes runtime.
7774                        grant = GRANT_UPGRADE;
7775                        upgradeUserIds = currentUserIds;
7776                    } else if (replace) {
7777                        // For upgraded modern apps keep runtime permissions unchanged.
7778                        grant = GRANT_RUNTIME;
7779                    }
7780                } break;
7781
7782                case PermissionInfo.PROTECTION_SIGNATURE: {
7783                    // For all apps signature permissions are install time ones.
7784                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
7785                    if (allowedSig) {
7786                        grant = GRANT_INSTALL;
7787                    }
7788                } break;
7789            }
7790
7791            if (DEBUG_INSTALL) {
7792                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
7793            }
7794
7795            if (grant != GRANT_DENIED) {
7796                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
7797                    // If this is an existing, non-system package, then
7798                    // we can't add any new permissions to it.
7799                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
7800                        // Except...  if this is a permission that was added
7801                        // to the platform (note: need to only do this when
7802                        // updating the platform).
7803                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
7804                            grant = GRANT_DENIED;
7805                        }
7806                    }
7807                }
7808
7809                switch (grant) {
7810                    case GRANT_INSTALL: {
7811                        // Revoke this as runtime permission to handle the case of
7812                        // a runtime permssion being downgraded to an install one.
7813                        for (int userId : UserManagerService.getInstance().getUserIds()) {
7814                            if (origPermissions.getRuntimePermissionState(
7815                                    bp.name, userId) != null) {
7816                                // Revoke the runtime permission and clear the flags.
7817                                origPermissions.revokeRuntimePermission(bp, userId);
7818                                origPermissions.updatePermissionFlags(bp, userId,
7819                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
7820                                // If we revoked a permission permission, we have to write.
7821                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7822                                        changedRuntimePermissionUserIds, userId);
7823                            }
7824                        }
7825                        // Grant an install permission.
7826                        if (permissionsState.grantInstallPermission(bp) !=
7827                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
7828                            changedInstallPermission = true;
7829                        }
7830                    } break;
7831
7832                    case GRANT_INSTALL_LEGACY: {
7833                        // Grant an install permission.
7834                        if (permissionsState.grantInstallPermission(bp) !=
7835                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
7836                            changedInstallPermission = true;
7837                        }
7838                    } break;
7839
7840                    case GRANT_RUNTIME: {
7841                        // Grant previously granted runtime permissions.
7842                        for (int userId : UserManagerService.getInstance().getUserIds()) {
7843                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
7844                                PermissionState permissionState = origPermissions
7845                                        .getRuntimePermissionState(bp.name, userId);
7846                                final int flags = permissionState.getFlags();
7847                                if (permissionsState.grantRuntimePermission(bp, userId) ==
7848                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7849                                    // If we cannot put the permission as it was, we have to write.
7850                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7851                                            changedRuntimePermissionUserIds, userId);
7852                                } else {
7853                                    // System components not only get the permissions but
7854                                    // they are also fixed, so nothing can change that.
7855                                    final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg)
7856                                            ? flags
7857                                            : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
7858                                    // Propagate the permission flags.
7859                                    permissionsState.updatePermissionFlags(bp, userId,
7860                                            newFlags, newFlags);
7861                                }
7862                            }
7863                        }
7864                    } break;
7865
7866                    case GRANT_UPGRADE: {
7867                        // Grant runtime permissions for a previously held install permission.
7868                        PermissionState permissionState = origPermissions
7869                                .getInstallPermissionState(bp.name);
7870                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
7871
7872                        origPermissions.revokeInstallPermission(bp);
7873                        // We will be transferring the permission flags, so clear them.
7874                        origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
7875                                PackageManager.MASK_PERMISSION_FLAGS, 0);
7876
7877                        // If the permission is not to be promoted to runtime we ignore it and
7878                        // also its other flags as they are not applicable to install permissions.
7879                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
7880                            for (int userId : upgradeUserIds) {
7881                                if (permissionsState.grantRuntimePermission(bp, userId) !=
7882                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7883                                    // System components not only get the permissions but
7884                                    // they are also fixed so nothing can change that.
7885                                    final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg)
7886                                            ? flags
7887                                            : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
7888                                    // Transfer the permission flags.
7889                                    permissionsState.updatePermissionFlags(bp, userId,
7890                                            newFlags, newFlags);
7891                                    // If we granted the permission, we have to write.
7892                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7893                                            changedRuntimePermissionUserIds, userId);
7894                                }
7895                            }
7896                        }
7897                    } break;
7898
7899                    default: {
7900                        if (packageOfInterest == null
7901                                || packageOfInterest.equals(pkg.packageName)) {
7902                            Slog.w(TAG, "Not granting permission " + perm
7903                                    + " to package " + pkg.packageName
7904                                    + " because it was previously installed without");
7905                        }
7906                    } break;
7907                }
7908            } else {
7909                if (permissionsState.revokeInstallPermission(bp) !=
7910                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7911                    // Also drop the permission flags.
7912                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
7913                            PackageManager.MASK_PERMISSION_FLAGS, 0);
7914                    changedInstallPermission = true;
7915                    Slog.i(TAG, "Un-granting permission " + perm
7916                            + " from package " + pkg.packageName
7917                            + " (protectionLevel=" + bp.protectionLevel
7918                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7919                            + ")");
7920                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
7921                    // Don't print warning for app op permissions, since it is fine for them
7922                    // not to be granted, there is a UI for the user to decide.
7923                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7924                        Slog.w(TAG, "Not granting permission " + perm
7925                                + " to package " + pkg.packageName
7926                                + " (protectionLevel=" + bp.protectionLevel
7927                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7928                                + ")");
7929                    }
7930                }
7931            }
7932        }
7933
7934        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
7935                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
7936            // This is the first that we have heard about this package, so the
7937            // permissions we have now selected are fixed until explicitly
7938            // changed.
7939            ps.installPermissionsFixed = true;
7940        }
7941
7942        ps.setPermissionsUpdatedForUserIds(currentUserIds);
7943
7944        // Persist the runtime permissions state for users with changes.
7945        for (int userId : changedRuntimePermissionUserIds) {
7946            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
7947        }
7948    }
7949
7950    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
7951        boolean allowed = false;
7952        final int NP = PackageParser.NEW_PERMISSIONS.length;
7953        for (int ip=0; ip<NP; ip++) {
7954            final PackageParser.NewPermissionInfo npi
7955                    = PackageParser.NEW_PERMISSIONS[ip];
7956            if (npi.name.equals(perm)
7957                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
7958                allowed = true;
7959                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
7960                        + pkg.packageName);
7961                break;
7962            }
7963        }
7964        return allowed;
7965    }
7966
7967    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
7968            BasePermission bp, PermissionsState origPermissions) {
7969        boolean allowed;
7970        allowed = (compareSignatures(
7971                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
7972                        == PackageManager.SIGNATURE_MATCH)
7973                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
7974                        == PackageManager.SIGNATURE_MATCH);
7975        if (!allowed && (bp.protectionLevel
7976                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
7977            if (isSystemApp(pkg)) {
7978                // For updated system applications, a system permission
7979                // is granted only if it had been defined by the original application.
7980                if (pkg.isUpdatedSystemApp()) {
7981                    final PackageSetting sysPs = mSettings
7982                            .getDisabledSystemPkgLPr(pkg.packageName);
7983                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
7984                        // If the original was granted this permission, we take
7985                        // that grant decision as read and propagate it to the
7986                        // update.
7987                        if (sysPs.isPrivileged()) {
7988                            allowed = true;
7989                        }
7990                    } else {
7991                        // The system apk may have been updated with an older
7992                        // version of the one on the data partition, but which
7993                        // granted a new system permission that it didn't have
7994                        // before.  In this case we do want to allow the app to
7995                        // now get the new permission if the ancestral apk is
7996                        // privileged to get it.
7997                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
7998                            for (int j=0;
7999                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8000                                if (perm.equals(
8001                                        sysPs.pkg.requestedPermissions.get(j))) {
8002                                    allowed = true;
8003                                    break;
8004                                }
8005                            }
8006                        }
8007                    }
8008                } else {
8009                    allowed = isPrivilegedApp(pkg);
8010                }
8011            }
8012        }
8013        if (!allowed && (bp.protectionLevel
8014                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8015            // For development permissions, a development permission
8016            // is granted only if it was already granted.
8017            allowed = origPermissions.hasInstallPermission(perm);
8018        }
8019        return allowed;
8020    }
8021
8022    final class ActivityIntentResolver
8023            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8024        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8025                boolean defaultOnly, int userId) {
8026            if (!sUserManager.exists(userId)) return null;
8027            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8028            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8029        }
8030
8031        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8032                int userId) {
8033            if (!sUserManager.exists(userId)) return null;
8034            mFlags = flags;
8035            return super.queryIntent(intent, resolvedType,
8036                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8037        }
8038
8039        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8040                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8041            if (!sUserManager.exists(userId)) return null;
8042            if (packageActivities == null) {
8043                return null;
8044            }
8045            mFlags = flags;
8046            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8047            final int N = packageActivities.size();
8048            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8049                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8050
8051            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8052            for (int i = 0; i < N; ++i) {
8053                intentFilters = packageActivities.get(i).intents;
8054                if (intentFilters != null && intentFilters.size() > 0) {
8055                    PackageParser.ActivityIntentInfo[] array =
8056                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8057                    intentFilters.toArray(array);
8058                    listCut.add(array);
8059                }
8060            }
8061            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8062        }
8063
8064        public final void addActivity(PackageParser.Activity a, String type) {
8065            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8066            mActivities.put(a.getComponentName(), a);
8067            if (DEBUG_SHOW_INFO)
8068                Log.v(
8069                TAG, "  " + type + " " +
8070                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8071            if (DEBUG_SHOW_INFO)
8072                Log.v(TAG, "    Class=" + a.info.name);
8073            final int NI = a.intents.size();
8074            for (int j=0; j<NI; j++) {
8075                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8076                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8077                    intent.setPriority(0);
8078                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8079                            + a.className + " with priority > 0, forcing to 0");
8080                }
8081                if (DEBUG_SHOW_INFO) {
8082                    Log.v(TAG, "    IntentFilter:");
8083                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8084                }
8085                if (!intent.debugCheck()) {
8086                    Log.w(TAG, "==> For Activity " + a.info.name);
8087                }
8088                addFilter(intent);
8089            }
8090        }
8091
8092        public final void removeActivity(PackageParser.Activity a, String type) {
8093            mActivities.remove(a.getComponentName());
8094            if (DEBUG_SHOW_INFO) {
8095                Log.v(TAG, "  " + type + " "
8096                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8097                                : a.info.name) + ":");
8098                Log.v(TAG, "    Class=" + a.info.name);
8099            }
8100            final int NI = a.intents.size();
8101            for (int j=0; j<NI; j++) {
8102                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8103                if (DEBUG_SHOW_INFO) {
8104                    Log.v(TAG, "    IntentFilter:");
8105                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8106                }
8107                removeFilter(intent);
8108            }
8109        }
8110
8111        @Override
8112        protected boolean allowFilterResult(
8113                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8114            ActivityInfo filterAi = filter.activity.info;
8115            for (int i=dest.size()-1; i>=0; i--) {
8116                ActivityInfo destAi = dest.get(i).activityInfo;
8117                if (destAi.name == filterAi.name
8118                        && destAi.packageName == filterAi.packageName) {
8119                    return false;
8120                }
8121            }
8122            return true;
8123        }
8124
8125        @Override
8126        protected ActivityIntentInfo[] newArray(int size) {
8127            return new ActivityIntentInfo[size];
8128        }
8129
8130        @Override
8131        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8132            if (!sUserManager.exists(userId)) return true;
8133            PackageParser.Package p = filter.activity.owner;
8134            if (p != null) {
8135                PackageSetting ps = (PackageSetting)p.mExtras;
8136                if (ps != null) {
8137                    // System apps are never considered stopped for purposes of
8138                    // filtering, because there may be no way for the user to
8139                    // actually re-launch them.
8140                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8141                            && ps.getStopped(userId);
8142                }
8143            }
8144            return false;
8145        }
8146
8147        @Override
8148        protected boolean isPackageForFilter(String packageName,
8149                PackageParser.ActivityIntentInfo info) {
8150            return packageName.equals(info.activity.owner.packageName);
8151        }
8152
8153        @Override
8154        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8155                int match, int userId) {
8156            if (!sUserManager.exists(userId)) return null;
8157            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8158                return null;
8159            }
8160            final PackageParser.Activity activity = info.activity;
8161            if (mSafeMode && (activity.info.applicationInfo.flags
8162                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8163                return null;
8164            }
8165            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8166            if (ps == null) {
8167                return null;
8168            }
8169            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8170                    ps.readUserState(userId), userId);
8171            if (ai == null) {
8172                return null;
8173            }
8174            final ResolveInfo res = new ResolveInfo();
8175            res.activityInfo = ai;
8176            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8177                res.filter = info;
8178            }
8179            if (info != null) {
8180                res.handleAllWebDataURI = info.handleAllWebDataURI();
8181            }
8182            res.priority = info.getPriority();
8183            res.preferredOrder = activity.owner.mPreferredOrder;
8184            //System.out.println("Result: " + res.activityInfo.className +
8185            //                   " = " + res.priority);
8186            res.match = match;
8187            res.isDefault = info.hasDefault;
8188            res.labelRes = info.labelRes;
8189            res.nonLocalizedLabel = info.nonLocalizedLabel;
8190            if (userNeedsBadging(userId)) {
8191                res.noResourceId = true;
8192            } else {
8193                res.icon = info.icon;
8194            }
8195            res.system = res.activityInfo.applicationInfo.isSystemApp();
8196            return res;
8197        }
8198
8199        @Override
8200        protected void sortResults(List<ResolveInfo> results) {
8201            Collections.sort(results, mResolvePrioritySorter);
8202        }
8203
8204        @Override
8205        protected void dumpFilter(PrintWriter out, String prefix,
8206                PackageParser.ActivityIntentInfo filter) {
8207            out.print(prefix); out.print(
8208                    Integer.toHexString(System.identityHashCode(filter.activity)));
8209                    out.print(' ');
8210                    filter.activity.printComponentShortName(out);
8211                    out.print(" filter ");
8212                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8213        }
8214
8215        @Override
8216        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8217            return filter.activity;
8218        }
8219
8220        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8221            PackageParser.Activity activity = (PackageParser.Activity)label;
8222            out.print(prefix); out.print(
8223                    Integer.toHexString(System.identityHashCode(activity)));
8224                    out.print(' ');
8225                    activity.printComponentShortName(out);
8226            if (count > 1) {
8227                out.print(" ("); out.print(count); out.print(" filters)");
8228            }
8229            out.println();
8230        }
8231
8232//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8233//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8234//            final List<ResolveInfo> retList = Lists.newArrayList();
8235//            while (i.hasNext()) {
8236//                final ResolveInfo resolveInfo = i.next();
8237//                if (isEnabledLP(resolveInfo.activityInfo)) {
8238//                    retList.add(resolveInfo);
8239//                }
8240//            }
8241//            return retList;
8242//        }
8243
8244        // Keys are String (activity class name), values are Activity.
8245        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8246                = new ArrayMap<ComponentName, PackageParser.Activity>();
8247        private int mFlags;
8248    }
8249
8250    private final class ServiceIntentResolver
8251            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8252        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8253                boolean defaultOnly, int userId) {
8254            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8255            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8256        }
8257
8258        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8259                int userId) {
8260            if (!sUserManager.exists(userId)) return null;
8261            mFlags = flags;
8262            return super.queryIntent(intent, resolvedType,
8263                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8264        }
8265
8266        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8267                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8268            if (!sUserManager.exists(userId)) return null;
8269            if (packageServices == null) {
8270                return null;
8271            }
8272            mFlags = flags;
8273            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8274            final int N = packageServices.size();
8275            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8276                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8277
8278            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8279            for (int i = 0; i < N; ++i) {
8280                intentFilters = packageServices.get(i).intents;
8281                if (intentFilters != null && intentFilters.size() > 0) {
8282                    PackageParser.ServiceIntentInfo[] array =
8283                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8284                    intentFilters.toArray(array);
8285                    listCut.add(array);
8286                }
8287            }
8288            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8289        }
8290
8291        public final void addService(PackageParser.Service s) {
8292            mServices.put(s.getComponentName(), s);
8293            if (DEBUG_SHOW_INFO) {
8294                Log.v(TAG, "  "
8295                        + (s.info.nonLocalizedLabel != null
8296                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8297                Log.v(TAG, "    Class=" + s.info.name);
8298            }
8299            final int NI = s.intents.size();
8300            int j;
8301            for (j=0; j<NI; j++) {
8302                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8303                if (DEBUG_SHOW_INFO) {
8304                    Log.v(TAG, "    IntentFilter:");
8305                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8306                }
8307                if (!intent.debugCheck()) {
8308                    Log.w(TAG, "==> For Service " + s.info.name);
8309                }
8310                addFilter(intent);
8311            }
8312        }
8313
8314        public final void removeService(PackageParser.Service s) {
8315            mServices.remove(s.getComponentName());
8316            if (DEBUG_SHOW_INFO) {
8317                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8318                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8319                Log.v(TAG, "    Class=" + s.info.name);
8320            }
8321            final int NI = s.intents.size();
8322            int j;
8323            for (j=0; j<NI; j++) {
8324                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8325                if (DEBUG_SHOW_INFO) {
8326                    Log.v(TAG, "    IntentFilter:");
8327                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8328                }
8329                removeFilter(intent);
8330            }
8331        }
8332
8333        @Override
8334        protected boolean allowFilterResult(
8335                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8336            ServiceInfo filterSi = filter.service.info;
8337            for (int i=dest.size()-1; i>=0; i--) {
8338                ServiceInfo destAi = dest.get(i).serviceInfo;
8339                if (destAi.name == filterSi.name
8340                        && destAi.packageName == filterSi.packageName) {
8341                    return false;
8342                }
8343            }
8344            return true;
8345        }
8346
8347        @Override
8348        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8349            return new PackageParser.ServiceIntentInfo[size];
8350        }
8351
8352        @Override
8353        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8354            if (!sUserManager.exists(userId)) return true;
8355            PackageParser.Package p = filter.service.owner;
8356            if (p != null) {
8357                PackageSetting ps = (PackageSetting)p.mExtras;
8358                if (ps != null) {
8359                    // System apps are never considered stopped for purposes of
8360                    // filtering, because there may be no way for the user to
8361                    // actually re-launch them.
8362                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8363                            && ps.getStopped(userId);
8364                }
8365            }
8366            return false;
8367        }
8368
8369        @Override
8370        protected boolean isPackageForFilter(String packageName,
8371                PackageParser.ServiceIntentInfo info) {
8372            return packageName.equals(info.service.owner.packageName);
8373        }
8374
8375        @Override
8376        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8377                int match, int userId) {
8378            if (!sUserManager.exists(userId)) return null;
8379            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8380            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8381                return null;
8382            }
8383            final PackageParser.Service service = info.service;
8384            if (mSafeMode && (service.info.applicationInfo.flags
8385                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8386                return null;
8387            }
8388            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8389            if (ps == null) {
8390                return null;
8391            }
8392            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8393                    ps.readUserState(userId), userId);
8394            if (si == null) {
8395                return null;
8396            }
8397            final ResolveInfo res = new ResolveInfo();
8398            res.serviceInfo = si;
8399            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8400                res.filter = filter;
8401            }
8402            res.priority = info.getPriority();
8403            res.preferredOrder = service.owner.mPreferredOrder;
8404            res.match = match;
8405            res.isDefault = info.hasDefault;
8406            res.labelRes = info.labelRes;
8407            res.nonLocalizedLabel = info.nonLocalizedLabel;
8408            res.icon = info.icon;
8409            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8410            return res;
8411        }
8412
8413        @Override
8414        protected void sortResults(List<ResolveInfo> results) {
8415            Collections.sort(results, mResolvePrioritySorter);
8416        }
8417
8418        @Override
8419        protected void dumpFilter(PrintWriter out, String prefix,
8420                PackageParser.ServiceIntentInfo filter) {
8421            out.print(prefix); out.print(
8422                    Integer.toHexString(System.identityHashCode(filter.service)));
8423                    out.print(' ');
8424                    filter.service.printComponentShortName(out);
8425                    out.print(" filter ");
8426                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8427        }
8428
8429        @Override
8430        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8431            return filter.service;
8432        }
8433
8434        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8435            PackageParser.Service service = (PackageParser.Service)label;
8436            out.print(prefix); out.print(
8437                    Integer.toHexString(System.identityHashCode(service)));
8438                    out.print(' ');
8439                    service.printComponentShortName(out);
8440            if (count > 1) {
8441                out.print(" ("); out.print(count); out.print(" filters)");
8442            }
8443            out.println();
8444        }
8445
8446//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8447//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8448//            final List<ResolveInfo> retList = Lists.newArrayList();
8449//            while (i.hasNext()) {
8450//                final ResolveInfo resolveInfo = (ResolveInfo) i;
8451//                if (isEnabledLP(resolveInfo.serviceInfo)) {
8452//                    retList.add(resolveInfo);
8453//                }
8454//            }
8455//            return retList;
8456//        }
8457
8458        // Keys are String (activity class name), values are Activity.
8459        private final ArrayMap<ComponentName, PackageParser.Service> mServices
8460                = new ArrayMap<ComponentName, PackageParser.Service>();
8461        private int mFlags;
8462    };
8463
8464    private final class ProviderIntentResolver
8465            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
8466        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8467                boolean defaultOnly, int userId) {
8468            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8469            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8470        }
8471
8472        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8473                int userId) {
8474            if (!sUserManager.exists(userId))
8475                return null;
8476            mFlags = flags;
8477            return super.queryIntent(intent, resolvedType,
8478                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8479        }
8480
8481        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8482                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
8483            if (!sUserManager.exists(userId))
8484                return null;
8485            if (packageProviders == null) {
8486                return null;
8487            }
8488            mFlags = flags;
8489            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
8490            final int N = packageProviders.size();
8491            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
8492                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
8493
8494            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
8495            for (int i = 0; i < N; ++i) {
8496                intentFilters = packageProviders.get(i).intents;
8497                if (intentFilters != null && intentFilters.size() > 0) {
8498                    PackageParser.ProviderIntentInfo[] array =
8499                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
8500                    intentFilters.toArray(array);
8501                    listCut.add(array);
8502                }
8503            }
8504            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8505        }
8506
8507        public final void addProvider(PackageParser.Provider p) {
8508            if (mProviders.containsKey(p.getComponentName())) {
8509                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
8510                return;
8511            }
8512
8513            mProviders.put(p.getComponentName(), p);
8514            if (DEBUG_SHOW_INFO) {
8515                Log.v(TAG, "  "
8516                        + (p.info.nonLocalizedLabel != null
8517                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
8518                Log.v(TAG, "    Class=" + p.info.name);
8519            }
8520            final int NI = p.intents.size();
8521            int j;
8522            for (j = 0; j < NI; j++) {
8523                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8524                if (DEBUG_SHOW_INFO) {
8525                    Log.v(TAG, "    IntentFilter:");
8526                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8527                }
8528                if (!intent.debugCheck()) {
8529                    Log.w(TAG, "==> For Provider " + p.info.name);
8530                }
8531                addFilter(intent);
8532            }
8533        }
8534
8535        public final void removeProvider(PackageParser.Provider p) {
8536            mProviders.remove(p.getComponentName());
8537            if (DEBUG_SHOW_INFO) {
8538                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
8539                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
8540                Log.v(TAG, "    Class=" + p.info.name);
8541            }
8542            final int NI = p.intents.size();
8543            int j;
8544            for (j = 0; j < NI; j++) {
8545                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8546                if (DEBUG_SHOW_INFO) {
8547                    Log.v(TAG, "    IntentFilter:");
8548                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8549                }
8550                removeFilter(intent);
8551            }
8552        }
8553
8554        @Override
8555        protected boolean allowFilterResult(
8556                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
8557            ProviderInfo filterPi = filter.provider.info;
8558            for (int i = dest.size() - 1; i >= 0; i--) {
8559                ProviderInfo destPi = dest.get(i).providerInfo;
8560                if (destPi.name == filterPi.name
8561                        && destPi.packageName == filterPi.packageName) {
8562                    return false;
8563                }
8564            }
8565            return true;
8566        }
8567
8568        @Override
8569        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
8570            return new PackageParser.ProviderIntentInfo[size];
8571        }
8572
8573        @Override
8574        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
8575            if (!sUserManager.exists(userId))
8576                return true;
8577            PackageParser.Package p = filter.provider.owner;
8578            if (p != null) {
8579                PackageSetting ps = (PackageSetting) p.mExtras;
8580                if (ps != null) {
8581                    // System apps are never considered stopped for purposes of
8582                    // filtering, because there may be no way for the user to
8583                    // actually re-launch them.
8584                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8585                            && ps.getStopped(userId);
8586                }
8587            }
8588            return false;
8589        }
8590
8591        @Override
8592        protected boolean isPackageForFilter(String packageName,
8593                PackageParser.ProviderIntentInfo info) {
8594            return packageName.equals(info.provider.owner.packageName);
8595        }
8596
8597        @Override
8598        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
8599                int match, int userId) {
8600            if (!sUserManager.exists(userId))
8601                return null;
8602            final PackageParser.ProviderIntentInfo info = filter;
8603            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
8604                return null;
8605            }
8606            final PackageParser.Provider provider = info.provider;
8607            if (mSafeMode && (provider.info.applicationInfo.flags
8608                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
8609                return null;
8610            }
8611            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
8612            if (ps == null) {
8613                return null;
8614            }
8615            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
8616                    ps.readUserState(userId), userId);
8617            if (pi == null) {
8618                return null;
8619            }
8620            final ResolveInfo res = new ResolveInfo();
8621            res.providerInfo = pi;
8622            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
8623                res.filter = filter;
8624            }
8625            res.priority = info.getPriority();
8626            res.preferredOrder = provider.owner.mPreferredOrder;
8627            res.match = match;
8628            res.isDefault = info.hasDefault;
8629            res.labelRes = info.labelRes;
8630            res.nonLocalizedLabel = info.nonLocalizedLabel;
8631            res.icon = info.icon;
8632            res.system = res.providerInfo.applicationInfo.isSystemApp();
8633            return res;
8634        }
8635
8636        @Override
8637        protected void sortResults(List<ResolveInfo> results) {
8638            Collections.sort(results, mResolvePrioritySorter);
8639        }
8640
8641        @Override
8642        protected void dumpFilter(PrintWriter out, String prefix,
8643                PackageParser.ProviderIntentInfo filter) {
8644            out.print(prefix);
8645            out.print(
8646                    Integer.toHexString(System.identityHashCode(filter.provider)));
8647            out.print(' ');
8648            filter.provider.printComponentShortName(out);
8649            out.print(" filter ");
8650            out.println(Integer.toHexString(System.identityHashCode(filter)));
8651        }
8652
8653        @Override
8654        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
8655            return filter.provider;
8656        }
8657
8658        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8659            PackageParser.Provider provider = (PackageParser.Provider)label;
8660            out.print(prefix); out.print(
8661                    Integer.toHexString(System.identityHashCode(provider)));
8662                    out.print(' ');
8663                    provider.printComponentShortName(out);
8664            if (count > 1) {
8665                out.print(" ("); out.print(count); out.print(" filters)");
8666            }
8667            out.println();
8668        }
8669
8670        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
8671                = new ArrayMap<ComponentName, PackageParser.Provider>();
8672        private int mFlags;
8673    };
8674
8675    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
8676            new Comparator<ResolveInfo>() {
8677        public int compare(ResolveInfo r1, ResolveInfo r2) {
8678            int v1 = r1.priority;
8679            int v2 = r2.priority;
8680            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
8681            if (v1 != v2) {
8682                return (v1 > v2) ? -1 : 1;
8683            }
8684            v1 = r1.preferredOrder;
8685            v2 = r2.preferredOrder;
8686            if (v1 != v2) {
8687                return (v1 > v2) ? -1 : 1;
8688            }
8689            if (r1.isDefault != r2.isDefault) {
8690                return r1.isDefault ? -1 : 1;
8691            }
8692            v1 = r1.match;
8693            v2 = r2.match;
8694            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
8695            if (v1 != v2) {
8696                return (v1 > v2) ? -1 : 1;
8697            }
8698            if (r1.system != r2.system) {
8699                return r1.system ? -1 : 1;
8700            }
8701            return 0;
8702        }
8703    };
8704
8705    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
8706            new Comparator<ProviderInfo>() {
8707        public int compare(ProviderInfo p1, ProviderInfo p2) {
8708            final int v1 = p1.initOrder;
8709            final int v2 = p2.initOrder;
8710            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
8711        }
8712    };
8713
8714    final void sendPackageBroadcast(final String action, final String pkg,
8715            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
8716            final int[] userIds) {
8717        mHandler.post(new Runnable() {
8718            @Override
8719            public void run() {
8720                try {
8721                    final IActivityManager am = ActivityManagerNative.getDefault();
8722                    if (am == null) return;
8723                    final int[] resolvedUserIds;
8724                    if (userIds == null) {
8725                        resolvedUserIds = am.getRunningUserIds();
8726                    } else {
8727                        resolvedUserIds = userIds;
8728                    }
8729                    for (int id : resolvedUserIds) {
8730                        final Intent intent = new Intent(action,
8731                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
8732                        if (extras != null) {
8733                            intent.putExtras(extras);
8734                        }
8735                        if (targetPkg != null) {
8736                            intent.setPackage(targetPkg);
8737                        }
8738                        // Modify the UID when posting to other users
8739                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
8740                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
8741                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
8742                            intent.putExtra(Intent.EXTRA_UID, uid);
8743                        }
8744                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
8745                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
8746                        if (DEBUG_BROADCASTS) {
8747                            RuntimeException here = new RuntimeException("here");
8748                            here.fillInStackTrace();
8749                            Slog.d(TAG, "Sending to user " + id + ": "
8750                                    + intent.toShortString(false, true, false, false)
8751                                    + " " + intent.getExtras(), here);
8752                        }
8753                        am.broadcastIntent(null, intent, null, finishedReceiver,
8754                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
8755                                finishedReceiver != null, false, id);
8756                    }
8757                } catch (RemoteException ex) {
8758                }
8759            }
8760        });
8761    }
8762
8763    /**
8764     * Check if the external storage media is available. This is true if there
8765     * is a mounted external storage medium or if the external storage is
8766     * emulated.
8767     */
8768    private boolean isExternalMediaAvailable() {
8769        return mMediaMounted || Environment.isExternalStorageEmulated();
8770    }
8771
8772    @Override
8773    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
8774        // writer
8775        synchronized (mPackages) {
8776            if (!isExternalMediaAvailable()) {
8777                // If the external storage is no longer mounted at this point,
8778                // the caller may not have been able to delete all of this
8779                // packages files and can not delete any more.  Bail.
8780                return null;
8781            }
8782            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
8783            if (lastPackage != null) {
8784                pkgs.remove(lastPackage);
8785            }
8786            if (pkgs.size() > 0) {
8787                return pkgs.get(0);
8788            }
8789        }
8790        return null;
8791    }
8792
8793    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
8794        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
8795                userId, andCode ? 1 : 0, packageName);
8796        if (mSystemReady) {
8797            msg.sendToTarget();
8798        } else {
8799            if (mPostSystemReadyMessages == null) {
8800                mPostSystemReadyMessages = new ArrayList<>();
8801            }
8802            mPostSystemReadyMessages.add(msg);
8803        }
8804    }
8805
8806    void startCleaningPackages() {
8807        // reader
8808        synchronized (mPackages) {
8809            if (!isExternalMediaAvailable()) {
8810                return;
8811            }
8812            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
8813                return;
8814            }
8815        }
8816        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
8817        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
8818        IActivityManager am = ActivityManagerNative.getDefault();
8819        if (am != null) {
8820            try {
8821                am.startService(null, intent, null, UserHandle.USER_OWNER);
8822            } catch (RemoteException e) {
8823            }
8824        }
8825    }
8826
8827    @Override
8828    public void installPackage(String originPath, IPackageInstallObserver2 observer,
8829            int installFlags, String installerPackageName, VerificationParams verificationParams,
8830            String packageAbiOverride) {
8831        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
8832                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
8833    }
8834
8835    @Override
8836    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
8837            int installFlags, String installerPackageName, VerificationParams verificationParams,
8838            String packageAbiOverride, int userId) {
8839        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
8840
8841        final int callingUid = Binder.getCallingUid();
8842        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
8843
8844        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8845            try {
8846                if (observer != null) {
8847                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
8848                }
8849            } catch (RemoteException re) {
8850            }
8851            return;
8852        }
8853
8854        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
8855            installFlags |= PackageManager.INSTALL_FROM_ADB;
8856
8857        } else {
8858            // Caller holds INSTALL_PACKAGES permission, so we're less strict
8859            // about installerPackageName.
8860
8861            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
8862            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
8863        }
8864
8865        UserHandle user;
8866        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
8867            user = UserHandle.ALL;
8868        } else {
8869            user = new UserHandle(userId);
8870        }
8871
8872        // Only system components can circumvent runtime permissions when installing.
8873        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
8874                && mContext.checkCallingOrSelfPermission(Manifest.permission
8875                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
8876            throw new SecurityException("You need the "
8877                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
8878                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
8879        }
8880
8881        verificationParams.setInstallerUid(callingUid);
8882
8883        final File originFile = new File(originPath);
8884        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
8885
8886        final Message msg = mHandler.obtainMessage(INIT_COPY);
8887        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
8888                null, verificationParams, user, packageAbiOverride);
8889        mHandler.sendMessage(msg);
8890    }
8891
8892    void installStage(String packageName, File stagedDir, String stagedCid,
8893            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
8894            String installerPackageName, int installerUid, UserHandle user) {
8895        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
8896                params.referrerUri, installerUid, null);
8897
8898        final OriginInfo origin;
8899        if (stagedDir != null) {
8900            origin = OriginInfo.fromStagedFile(stagedDir);
8901        } else {
8902            origin = OriginInfo.fromStagedContainer(stagedCid);
8903        }
8904
8905        final Message msg = mHandler.obtainMessage(INIT_COPY);
8906        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
8907                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
8908        mHandler.sendMessage(msg);
8909    }
8910
8911    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
8912        Bundle extras = new Bundle(1);
8913        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
8914
8915        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
8916                packageName, extras, null, null, new int[] {userId});
8917        try {
8918            IActivityManager am = ActivityManagerNative.getDefault();
8919            final boolean isSystem =
8920                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
8921            if (isSystem && am.isUserRunning(userId, false)) {
8922                // The just-installed/enabled app is bundled on the system, so presumed
8923                // to be able to run automatically without needing an explicit launch.
8924                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
8925                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
8926                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
8927                        .setPackage(packageName);
8928                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
8929                        android.app.AppOpsManager.OP_NONE, false, false, userId);
8930            }
8931        } catch (RemoteException e) {
8932            // shouldn't happen
8933            Slog.w(TAG, "Unable to bootstrap installed package", e);
8934        }
8935    }
8936
8937    @Override
8938    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
8939            int userId) {
8940        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8941        PackageSetting pkgSetting;
8942        final int uid = Binder.getCallingUid();
8943        enforceCrossUserPermission(uid, userId, true, true,
8944                "setApplicationHiddenSetting for user " + userId);
8945
8946        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
8947            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
8948            return false;
8949        }
8950
8951        long callingId = Binder.clearCallingIdentity();
8952        try {
8953            boolean sendAdded = false;
8954            boolean sendRemoved = false;
8955            // writer
8956            synchronized (mPackages) {
8957                pkgSetting = mSettings.mPackages.get(packageName);
8958                if (pkgSetting == null) {
8959                    return false;
8960                }
8961                if (pkgSetting.getHidden(userId) != hidden) {
8962                    pkgSetting.setHidden(hidden, userId);
8963                    mSettings.writePackageRestrictionsLPr(userId);
8964                    if (hidden) {
8965                        sendRemoved = true;
8966                    } else {
8967                        sendAdded = true;
8968                    }
8969                }
8970            }
8971            if (sendAdded) {
8972                sendPackageAddedForUser(packageName, pkgSetting, userId);
8973                return true;
8974            }
8975            if (sendRemoved) {
8976                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
8977                        "hiding pkg");
8978                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
8979            }
8980        } finally {
8981            Binder.restoreCallingIdentity(callingId);
8982        }
8983        return false;
8984    }
8985
8986    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
8987            int userId) {
8988        final PackageRemovedInfo info = new PackageRemovedInfo();
8989        info.removedPackage = packageName;
8990        info.removedUsers = new int[] {userId};
8991        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
8992        info.sendBroadcast(false, false, false);
8993    }
8994
8995    /**
8996     * Returns true if application is not found or there was an error. Otherwise it returns
8997     * the hidden state of the package for the given user.
8998     */
8999    @Override
9000    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9001        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9002        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9003                false, "getApplicationHidden for user " + userId);
9004        PackageSetting pkgSetting;
9005        long callingId = Binder.clearCallingIdentity();
9006        try {
9007            // writer
9008            synchronized (mPackages) {
9009                pkgSetting = mSettings.mPackages.get(packageName);
9010                if (pkgSetting == null) {
9011                    return true;
9012                }
9013                return pkgSetting.getHidden(userId);
9014            }
9015        } finally {
9016            Binder.restoreCallingIdentity(callingId);
9017        }
9018    }
9019
9020    /**
9021     * @hide
9022     */
9023    @Override
9024    public int installExistingPackageAsUser(String packageName, int userId) {
9025        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9026                null);
9027        PackageSetting pkgSetting;
9028        final int uid = Binder.getCallingUid();
9029        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9030                + userId);
9031        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9032            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9033        }
9034
9035        long callingId = Binder.clearCallingIdentity();
9036        try {
9037            boolean sendAdded = false;
9038
9039            // writer
9040            synchronized (mPackages) {
9041                pkgSetting = mSettings.mPackages.get(packageName);
9042                if (pkgSetting == null) {
9043                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9044                }
9045                if (!pkgSetting.getInstalled(userId)) {
9046                    pkgSetting.setInstalled(true, userId);
9047                    pkgSetting.setHidden(false, userId);
9048                    mSettings.writePackageRestrictionsLPr(userId);
9049                    sendAdded = true;
9050                }
9051            }
9052
9053            if (sendAdded) {
9054                sendPackageAddedForUser(packageName, pkgSetting, userId);
9055            }
9056        } finally {
9057            Binder.restoreCallingIdentity(callingId);
9058        }
9059
9060        return PackageManager.INSTALL_SUCCEEDED;
9061    }
9062
9063    boolean isUserRestricted(int userId, String restrictionKey) {
9064        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9065        if (restrictions.getBoolean(restrictionKey, false)) {
9066            Log.w(TAG, "User is restricted: " + restrictionKey);
9067            return true;
9068        }
9069        return false;
9070    }
9071
9072    @Override
9073    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9074        mContext.enforceCallingOrSelfPermission(
9075                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9076                "Only package verification agents can verify applications");
9077
9078        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9079        final PackageVerificationResponse response = new PackageVerificationResponse(
9080                verificationCode, Binder.getCallingUid());
9081        msg.arg1 = id;
9082        msg.obj = response;
9083        mHandler.sendMessage(msg);
9084    }
9085
9086    @Override
9087    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9088            long millisecondsToDelay) {
9089        mContext.enforceCallingOrSelfPermission(
9090                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9091                "Only package verification agents can extend verification timeouts");
9092
9093        final PackageVerificationState state = mPendingVerification.get(id);
9094        final PackageVerificationResponse response = new PackageVerificationResponse(
9095                verificationCodeAtTimeout, Binder.getCallingUid());
9096
9097        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9098            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9099        }
9100        if (millisecondsToDelay < 0) {
9101            millisecondsToDelay = 0;
9102        }
9103        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9104                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9105            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9106        }
9107
9108        if ((state != null) && !state.timeoutExtended()) {
9109            state.extendTimeout();
9110
9111            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9112            msg.arg1 = id;
9113            msg.obj = response;
9114            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9115        }
9116    }
9117
9118    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9119            int verificationCode, UserHandle user) {
9120        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9121        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9122        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9123        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9124        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9125
9126        mContext.sendBroadcastAsUser(intent, user,
9127                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9128    }
9129
9130    private ComponentName matchComponentForVerifier(String packageName,
9131            List<ResolveInfo> receivers) {
9132        ActivityInfo targetReceiver = null;
9133
9134        final int NR = receivers.size();
9135        for (int i = 0; i < NR; i++) {
9136            final ResolveInfo info = receivers.get(i);
9137            if (info.activityInfo == null) {
9138                continue;
9139            }
9140
9141            if (packageName.equals(info.activityInfo.packageName)) {
9142                targetReceiver = info.activityInfo;
9143                break;
9144            }
9145        }
9146
9147        if (targetReceiver == null) {
9148            return null;
9149        }
9150
9151        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9152    }
9153
9154    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9155            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9156        if (pkgInfo.verifiers.length == 0) {
9157            return null;
9158        }
9159
9160        final int N = pkgInfo.verifiers.length;
9161        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9162        for (int i = 0; i < N; i++) {
9163            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9164
9165            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9166                    receivers);
9167            if (comp == null) {
9168                continue;
9169            }
9170
9171            final int verifierUid = getUidForVerifier(verifierInfo);
9172            if (verifierUid == -1) {
9173                continue;
9174            }
9175
9176            if (DEBUG_VERIFY) {
9177                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9178                        + " with the correct signature");
9179            }
9180            sufficientVerifiers.add(comp);
9181            verificationState.addSufficientVerifier(verifierUid);
9182        }
9183
9184        return sufficientVerifiers;
9185    }
9186
9187    private int getUidForVerifier(VerifierInfo verifierInfo) {
9188        synchronized (mPackages) {
9189            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9190            if (pkg == null) {
9191                return -1;
9192            } else if (pkg.mSignatures.length != 1) {
9193                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9194                        + " has more than one signature; ignoring");
9195                return -1;
9196            }
9197
9198            /*
9199             * If the public key of the package's signature does not match
9200             * our expected public key, then this is a different package and
9201             * we should skip.
9202             */
9203
9204            final byte[] expectedPublicKey;
9205            try {
9206                final Signature verifierSig = pkg.mSignatures[0];
9207                final PublicKey publicKey = verifierSig.getPublicKey();
9208                expectedPublicKey = publicKey.getEncoded();
9209            } catch (CertificateException e) {
9210                return -1;
9211            }
9212
9213            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9214
9215            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9216                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9217                        + " does not have the expected public key; ignoring");
9218                return -1;
9219            }
9220
9221            return pkg.applicationInfo.uid;
9222        }
9223    }
9224
9225    @Override
9226    public void finishPackageInstall(int token) {
9227        enforceSystemOrRoot("Only the system is allowed to finish installs");
9228
9229        if (DEBUG_INSTALL) {
9230            Slog.v(TAG, "BM finishing package install for " + token);
9231        }
9232
9233        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9234        mHandler.sendMessage(msg);
9235    }
9236
9237    /**
9238     * Get the verification agent timeout.
9239     *
9240     * @return verification timeout in milliseconds
9241     */
9242    private long getVerificationTimeout() {
9243        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9244                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9245                DEFAULT_VERIFICATION_TIMEOUT);
9246    }
9247
9248    /**
9249     * Get the default verification agent response code.
9250     *
9251     * @return default verification response code
9252     */
9253    private int getDefaultVerificationResponse() {
9254        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9255                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9256                DEFAULT_VERIFICATION_RESPONSE);
9257    }
9258
9259    /**
9260     * Check whether or not package verification has been enabled.
9261     *
9262     * @return true if verification should be performed
9263     */
9264    private boolean isVerificationEnabled(int userId, int installFlags) {
9265        if (!DEFAULT_VERIFY_ENABLE) {
9266            return false;
9267        }
9268
9269        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9270
9271        // Check if installing from ADB
9272        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9273            // Do not run verification in a test harness environment
9274            if (ActivityManager.isRunningInTestHarness()) {
9275                return false;
9276            }
9277            if (ensureVerifyAppsEnabled) {
9278                return true;
9279            }
9280            // Check if the developer does not want package verification for ADB installs
9281            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9282                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9283                return false;
9284            }
9285        }
9286
9287        if (ensureVerifyAppsEnabled) {
9288            return true;
9289        }
9290
9291        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9292                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9293    }
9294
9295    @Override
9296    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9297            throws RemoteException {
9298        mContext.enforceCallingOrSelfPermission(
9299                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9300                "Only intentfilter verification agents can verify applications");
9301
9302        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9303        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9304                Binder.getCallingUid(), verificationCode, failedDomains);
9305        msg.arg1 = id;
9306        msg.obj = response;
9307        mHandler.sendMessage(msg);
9308    }
9309
9310    @Override
9311    public int getIntentVerificationStatus(String packageName, int userId) {
9312        synchronized (mPackages) {
9313            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9314        }
9315    }
9316
9317    @Override
9318    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9319        boolean result = false;
9320        synchronized (mPackages) {
9321            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9322        }
9323        if (result) {
9324            scheduleWritePackageRestrictionsLocked(userId);
9325        }
9326        return result;
9327    }
9328
9329    @Override
9330    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9331        synchronized (mPackages) {
9332            return mSettings.getIntentFilterVerificationsLPr(packageName);
9333        }
9334    }
9335
9336    @Override
9337    public List<IntentFilter> getAllIntentFilters(String packageName) {
9338        if (TextUtils.isEmpty(packageName)) {
9339            return Collections.<IntentFilter>emptyList();
9340        }
9341        synchronized (mPackages) {
9342            PackageParser.Package pkg = mPackages.get(packageName);
9343            if (pkg == null || pkg.activities == null) {
9344                return Collections.<IntentFilter>emptyList();
9345            }
9346            final int count = pkg.activities.size();
9347            ArrayList<IntentFilter> result = new ArrayList<>();
9348            for (int n=0; n<count; n++) {
9349                PackageParser.Activity activity = pkg.activities.get(n);
9350                if (activity.intents != null || activity.intents.size() > 0) {
9351                    result.addAll(activity.intents);
9352                }
9353            }
9354            return result;
9355        }
9356    }
9357
9358    @Override
9359    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9360        synchronized (mPackages) {
9361            boolean result = mSettings.setDefaultBrowserPackageNameLPr(packageName, userId);
9362            if (packageName != null) {
9363                result |= updateIntentVerificationStatus(packageName,
9364                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9365                        UserHandle.myUserId());
9366            }
9367            return result;
9368        }
9369    }
9370
9371    @Override
9372    public String getDefaultBrowserPackageName(int userId) {
9373        synchronized (mPackages) {
9374            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9375        }
9376    }
9377
9378    /**
9379     * Get the "allow unknown sources" setting.
9380     *
9381     * @return the current "allow unknown sources" setting
9382     */
9383    private int getUnknownSourcesSettings() {
9384        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9385                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9386                -1);
9387    }
9388
9389    @Override
9390    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9391        final int uid = Binder.getCallingUid();
9392        // writer
9393        synchronized (mPackages) {
9394            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9395            if (targetPackageSetting == null) {
9396                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9397            }
9398
9399            PackageSetting installerPackageSetting;
9400            if (installerPackageName != null) {
9401                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9402                if (installerPackageSetting == null) {
9403                    throw new IllegalArgumentException("Unknown installer package: "
9404                            + installerPackageName);
9405                }
9406            } else {
9407                installerPackageSetting = null;
9408            }
9409
9410            Signature[] callerSignature;
9411            Object obj = mSettings.getUserIdLPr(uid);
9412            if (obj != null) {
9413                if (obj instanceof SharedUserSetting) {
9414                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9415                } else if (obj instanceof PackageSetting) {
9416                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9417                } else {
9418                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9419                }
9420            } else {
9421                throw new SecurityException("Unknown calling uid " + uid);
9422            }
9423
9424            // Verify: can't set installerPackageName to a package that is
9425            // not signed with the same cert as the caller.
9426            if (installerPackageSetting != null) {
9427                if (compareSignatures(callerSignature,
9428                        installerPackageSetting.signatures.mSignatures)
9429                        != PackageManager.SIGNATURE_MATCH) {
9430                    throw new SecurityException(
9431                            "Caller does not have same cert as new installer package "
9432                            + installerPackageName);
9433                }
9434            }
9435
9436            // Verify: if target already has an installer package, it must
9437            // be signed with the same cert as the caller.
9438            if (targetPackageSetting.installerPackageName != null) {
9439                PackageSetting setting = mSettings.mPackages.get(
9440                        targetPackageSetting.installerPackageName);
9441                // If the currently set package isn't valid, then it's always
9442                // okay to change it.
9443                if (setting != null) {
9444                    if (compareSignatures(callerSignature,
9445                            setting.signatures.mSignatures)
9446                            != PackageManager.SIGNATURE_MATCH) {
9447                        throw new SecurityException(
9448                                "Caller does not have same cert as old installer package "
9449                                + targetPackageSetting.installerPackageName);
9450                    }
9451                }
9452            }
9453
9454            // Okay!
9455            targetPackageSetting.installerPackageName = installerPackageName;
9456            scheduleWriteSettingsLocked();
9457        }
9458    }
9459
9460    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
9461        // Queue up an async operation since the package installation may take a little while.
9462        mHandler.post(new Runnable() {
9463            public void run() {
9464                mHandler.removeCallbacks(this);
9465                 // Result object to be returned
9466                PackageInstalledInfo res = new PackageInstalledInfo();
9467                res.returnCode = currentStatus;
9468                res.uid = -1;
9469                res.pkg = null;
9470                res.removedInfo = new PackageRemovedInfo();
9471                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9472                    args.doPreInstall(res.returnCode);
9473                    synchronized (mInstallLock) {
9474                        installPackageLI(args, res);
9475                    }
9476                    args.doPostInstall(res.returnCode, res.uid);
9477                }
9478
9479                // A restore should be performed at this point if (a) the install
9480                // succeeded, (b) the operation is not an update, and (c) the new
9481                // package has not opted out of backup participation.
9482                final boolean update = res.removedInfo.removedPackage != null;
9483                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
9484                boolean doRestore = !update
9485                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
9486
9487                // Set up the post-install work request bookkeeping.  This will be used
9488                // and cleaned up by the post-install event handling regardless of whether
9489                // there's a restore pass performed.  Token values are >= 1.
9490                int token;
9491                if (mNextInstallToken < 0) mNextInstallToken = 1;
9492                token = mNextInstallToken++;
9493
9494                PostInstallData data = new PostInstallData(args, res);
9495                mRunningInstalls.put(token, data);
9496                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
9497
9498                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
9499                    // Pass responsibility to the Backup Manager.  It will perform a
9500                    // restore if appropriate, then pass responsibility back to the
9501                    // Package Manager to run the post-install observer callbacks
9502                    // and broadcasts.
9503                    IBackupManager bm = IBackupManager.Stub.asInterface(
9504                            ServiceManager.getService(Context.BACKUP_SERVICE));
9505                    if (bm != null) {
9506                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
9507                                + " to BM for possible restore");
9508                        try {
9509                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
9510                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
9511                            } else {
9512                                doRestore = false;
9513                            }
9514                        } catch (RemoteException e) {
9515                            // can't happen; the backup manager is local
9516                        } catch (Exception e) {
9517                            Slog.e(TAG, "Exception trying to enqueue restore", e);
9518                            doRestore = false;
9519                        }
9520                    } else {
9521                        Slog.e(TAG, "Backup Manager not found!");
9522                        doRestore = false;
9523                    }
9524                }
9525
9526                if (!doRestore) {
9527                    // No restore possible, or the Backup Manager was mysteriously not
9528                    // available -- just fire the post-install work request directly.
9529                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
9530                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9531                    mHandler.sendMessage(msg);
9532                }
9533            }
9534        });
9535    }
9536
9537    private abstract class HandlerParams {
9538        private static final int MAX_RETRIES = 4;
9539
9540        /**
9541         * Number of times startCopy() has been attempted and had a non-fatal
9542         * error.
9543         */
9544        private int mRetries = 0;
9545
9546        /** User handle for the user requesting the information or installation. */
9547        private final UserHandle mUser;
9548
9549        HandlerParams(UserHandle user) {
9550            mUser = user;
9551        }
9552
9553        UserHandle getUser() {
9554            return mUser;
9555        }
9556
9557        final boolean startCopy() {
9558            boolean res;
9559            try {
9560                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
9561
9562                if (++mRetries > MAX_RETRIES) {
9563                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
9564                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
9565                    handleServiceError();
9566                    return false;
9567                } else {
9568                    handleStartCopy();
9569                    res = true;
9570                }
9571            } catch (RemoteException e) {
9572                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
9573                mHandler.sendEmptyMessage(MCS_RECONNECT);
9574                res = false;
9575            }
9576            handleReturnCode();
9577            return res;
9578        }
9579
9580        final void serviceError() {
9581            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
9582            handleServiceError();
9583            handleReturnCode();
9584        }
9585
9586        abstract void handleStartCopy() throws RemoteException;
9587        abstract void handleServiceError();
9588        abstract void handleReturnCode();
9589    }
9590
9591    class MeasureParams extends HandlerParams {
9592        private final PackageStats mStats;
9593        private boolean mSuccess;
9594
9595        private final IPackageStatsObserver mObserver;
9596
9597        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
9598            super(new UserHandle(stats.userHandle));
9599            mObserver = observer;
9600            mStats = stats;
9601        }
9602
9603        @Override
9604        public String toString() {
9605            return "MeasureParams{"
9606                + Integer.toHexString(System.identityHashCode(this))
9607                + " " + mStats.packageName + "}";
9608        }
9609
9610        @Override
9611        void handleStartCopy() throws RemoteException {
9612            synchronized (mInstallLock) {
9613                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
9614            }
9615
9616            if (mSuccess) {
9617                final boolean mounted;
9618                if (Environment.isExternalStorageEmulated()) {
9619                    mounted = true;
9620                } else {
9621                    final String status = Environment.getExternalStorageState();
9622                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
9623                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
9624                }
9625
9626                if (mounted) {
9627                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
9628
9629                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
9630                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
9631
9632                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
9633                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
9634
9635                    // Always subtract cache size, since it's a subdirectory
9636                    mStats.externalDataSize -= mStats.externalCacheSize;
9637
9638                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
9639                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
9640
9641                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
9642                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
9643                }
9644            }
9645        }
9646
9647        @Override
9648        void handleReturnCode() {
9649            if (mObserver != null) {
9650                try {
9651                    mObserver.onGetStatsCompleted(mStats, mSuccess);
9652                } catch (RemoteException e) {
9653                    Slog.i(TAG, "Observer no longer exists.");
9654                }
9655            }
9656        }
9657
9658        @Override
9659        void handleServiceError() {
9660            Slog.e(TAG, "Could not measure application " + mStats.packageName
9661                            + " external storage");
9662        }
9663    }
9664
9665    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
9666            throws RemoteException {
9667        long result = 0;
9668        for (File path : paths) {
9669            result += mcs.calculateDirectorySize(path.getAbsolutePath());
9670        }
9671        return result;
9672    }
9673
9674    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
9675        for (File path : paths) {
9676            try {
9677                mcs.clearDirectory(path.getAbsolutePath());
9678            } catch (RemoteException e) {
9679            }
9680        }
9681    }
9682
9683    static class OriginInfo {
9684        /**
9685         * Location where install is coming from, before it has been
9686         * copied/renamed into place. This could be a single monolithic APK
9687         * file, or a cluster directory. This location may be untrusted.
9688         */
9689        final File file;
9690        final String cid;
9691
9692        /**
9693         * Flag indicating that {@link #file} or {@link #cid} has already been
9694         * staged, meaning downstream users don't need to defensively copy the
9695         * contents.
9696         */
9697        final boolean staged;
9698
9699        /**
9700         * Flag indicating that {@link #file} or {@link #cid} is an already
9701         * installed app that is being moved.
9702         */
9703        final boolean existing;
9704
9705        final String resolvedPath;
9706        final File resolvedFile;
9707
9708        static OriginInfo fromNothing() {
9709            return new OriginInfo(null, null, false, false);
9710        }
9711
9712        static OriginInfo fromUntrustedFile(File file) {
9713            return new OriginInfo(file, null, false, false);
9714        }
9715
9716        static OriginInfo fromExistingFile(File file) {
9717            return new OriginInfo(file, null, false, true);
9718        }
9719
9720        static OriginInfo fromStagedFile(File file) {
9721            return new OriginInfo(file, null, true, false);
9722        }
9723
9724        static OriginInfo fromStagedContainer(String cid) {
9725            return new OriginInfo(null, cid, true, false);
9726        }
9727
9728        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
9729            this.file = file;
9730            this.cid = cid;
9731            this.staged = staged;
9732            this.existing = existing;
9733
9734            if (cid != null) {
9735                resolvedPath = PackageHelper.getSdDir(cid);
9736                resolvedFile = new File(resolvedPath);
9737            } else if (file != null) {
9738                resolvedPath = file.getAbsolutePath();
9739                resolvedFile = file;
9740            } else {
9741                resolvedPath = null;
9742                resolvedFile = null;
9743            }
9744        }
9745    }
9746
9747    class MoveInfo {
9748        final int moveId;
9749        final String fromUuid;
9750        final String toUuid;
9751        final String packageName;
9752        final String dataAppName;
9753        final int appId;
9754        final String seinfo;
9755
9756        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
9757                String dataAppName, int appId, String seinfo) {
9758            this.moveId = moveId;
9759            this.fromUuid = fromUuid;
9760            this.toUuid = toUuid;
9761            this.packageName = packageName;
9762            this.dataAppName = dataAppName;
9763            this.appId = appId;
9764            this.seinfo = seinfo;
9765        }
9766    }
9767
9768    class InstallParams extends HandlerParams {
9769        final OriginInfo origin;
9770        final MoveInfo move;
9771        final IPackageInstallObserver2 observer;
9772        int installFlags;
9773        final String installerPackageName;
9774        final String volumeUuid;
9775        final VerificationParams verificationParams;
9776        private InstallArgs mArgs;
9777        private int mRet;
9778        final String packageAbiOverride;
9779
9780        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
9781                int installFlags, String installerPackageName, String volumeUuid,
9782                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
9783            super(user);
9784            this.origin = origin;
9785            this.move = move;
9786            this.observer = observer;
9787            this.installFlags = installFlags;
9788            this.installerPackageName = installerPackageName;
9789            this.volumeUuid = volumeUuid;
9790            this.verificationParams = verificationParams;
9791            this.packageAbiOverride = packageAbiOverride;
9792        }
9793
9794        @Override
9795        public String toString() {
9796            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
9797                    + " file=" + origin.file + " cid=" + origin.cid + "}";
9798        }
9799
9800        public ManifestDigest getManifestDigest() {
9801            if (verificationParams == null) {
9802                return null;
9803            }
9804            return verificationParams.getManifestDigest();
9805        }
9806
9807        private int installLocationPolicy(PackageInfoLite pkgLite) {
9808            String packageName = pkgLite.packageName;
9809            int installLocation = pkgLite.installLocation;
9810            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9811            // reader
9812            synchronized (mPackages) {
9813                PackageParser.Package pkg = mPackages.get(packageName);
9814                if (pkg != null) {
9815                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
9816                        // Check for downgrading.
9817                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
9818                            try {
9819                                checkDowngrade(pkg, pkgLite);
9820                            } catch (PackageManagerException e) {
9821                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
9822                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
9823                            }
9824                        }
9825                        // Check for updated system application.
9826                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9827                            if (onSd) {
9828                                Slog.w(TAG, "Cannot install update to system app on sdcard");
9829                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
9830                            }
9831                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9832                        } else {
9833                            if (onSd) {
9834                                // Install flag overrides everything.
9835                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9836                            }
9837                            // If current upgrade specifies particular preference
9838                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
9839                                // Application explicitly specified internal.
9840                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9841                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
9842                                // App explictly prefers external. Let policy decide
9843                            } else {
9844                                // Prefer previous location
9845                                if (isExternal(pkg)) {
9846                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9847                                }
9848                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9849                            }
9850                        }
9851                    } else {
9852                        // Invalid install. Return error code
9853                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
9854                    }
9855                }
9856            }
9857            // All the special cases have been taken care of.
9858            // Return result based on recommended install location.
9859            if (onSd) {
9860                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9861            }
9862            return pkgLite.recommendedInstallLocation;
9863        }
9864
9865        /*
9866         * Invoke remote method to get package information and install
9867         * location values. Override install location based on default
9868         * policy if needed and then create install arguments based
9869         * on the install location.
9870         */
9871        public void handleStartCopy() throws RemoteException {
9872            int ret = PackageManager.INSTALL_SUCCEEDED;
9873
9874            // If we're already staged, we've firmly committed to an install location
9875            if (origin.staged) {
9876                if (origin.file != null) {
9877                    installFlags |= PackageManager.INSTALL_INTERNAL;
9878                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
9879                } else if (origin.cid != null) {
9880                    installFlags |= PackageManager.INSTALL_EXTERNAL;
9881                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
9882                } else {
9883                    throw new IllegalStateException("Invalid stage location");
9884                }
9885            }
9886
9887            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9888            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
9889
9890            PackageInfoLite pkgLite = null;
9891
9892            if (onInt && onSd) {
9893                // Check if both bits are set.
9894                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
9895                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9896            } else {
9897                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
9898                        packageAbiOverride);
9899
9900                /*
9901                 * If we have too little free space, try to free cache
9902                 * before giving up.
9903                 */
9904                if (!origin.staged && pkgLite.recommendedInstallLocation
9905                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9906                    // TODO: focus freeing disk space on the target device
9907                    final StorageManager storage = StorageManager.from(mContext);
9908                    final long lowThreshold = storage.getStorageLowBytes(
9909                            Environment.getDataDirectory());
9910
9911                    final long sizeBytes = mContainerService.calculateInstalledSize(
9912                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
9913
9914                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
9915                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
9916                                installFlags, packageAbiOverride);
9917                    }
9918
9919                    /*
9920                     * The cache free must have deleted the file we
9921                     * downloaded to install.
9922                     *
9923                     * TODO: fix the "freeCache" call to not delete
9924                     *       the file we care about.
9925                     */
9926                    if (pkgLite.recommendedInstallLocation
9927                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9928                        pkgLite.recommendedInstallLocation
9929                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
9930                    }
9931                }
9932            }
9933
9934            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9935                int loc = pkgLite.recommendedInstallLocation;
9936                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
9937                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9938                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
9939                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9940                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9941                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9942                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
9943                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
9944                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9945                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
9946                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
9947                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
9948                } else {
9949                    // Override with defaults if needed.
9950                    loc = installLocationPolicy(pkgLite);
9951                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
9952                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
9953                    } else if (!onSd && !onInt) {
9954                        // Override install location with flags
9955                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
9956                            // Set the flag to install on external media.
9957                            installFlags |= PackageManager.INSTALL_EXTERNAL;
9958                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
9959                        } else {
9960                            // Make sure the flag for installing on external
9961                            // media is unset
9962                            installFlags |= PackageManager.INSTALL_INTERNAL;
9963                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
9964                        }
9965                    }
9966                }
9967            }
9968
9969            final InstallArgs args = createInstallArgs(this);
9970            mArgs = args;
9971
9972            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9973                 /*
9974                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
9975                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
9976                 */
9977                int userIdentifier = getUser().getIdentifier();
9978                if (userIdentifier == UserHandle.USER_ALL
9979                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
9980                    userIdentifier = UserHandle.USER_OWNER;
9981                }
9982
9983                /*
9984                 * Determine if we have any installed package verifiers. If we
9985                 * do, then we'll defer to them to verify the packages.
9986                 */
9987                final int requiredUid = mRequiredVerifierPackage == null ? -1
9988                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
9989                if (!origin.existing && requiredUid != -1
9990                        && isVerificationEnabled(userIdentifier, installFlags)) {
9991                    final Intent verification = new Intent(
9992                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
9993                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
9994                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
9995                            PACKAGE_MIME_TYPE);
9996                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9997
9998                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
9999                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10000                            0 /* TODO: Which userId? */);
10001
10002                    if (DEBUG_VERIFY) {
10003                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10004                                + verification.toString() + " with " + pkgLite.verifiers.length
10005                                + " optional verifiers");
10006                    }
10007
10008                    final int verificationId = mPendingVerificationToken++;
10009
10010                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10011
10012                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10013                            installerPackageName);
10014
10015                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10016                            installFlags);
10017
10018                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10019                            pkgLite.packageName);
10020
10021                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10022                            pkgLite.versionCode);
10023
10024                    if (verificationParams != null) {
10025                        if (verificationParams.getVerificationURI() != null) {
10026                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10027                                 verificationParams.getVerificationURI());
10028                        }
10029                        if (verificationParams.getOriginatingURI() != null) {
10030                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10031                                  verificationParams.getOriginatingURI());
10032                        }
10033                        if (verificationParams.getReferrer() != null) {
10034                            verification.putExtra(Intent.EXTRA_REFERRER,
10035                                  verificationParams.getReferrer());
10036                        }
10037                        if (verificationParams.getOriginatingUid() >= 0) {
10038                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10039                                  verificationParams.getOriginatingUid());
10040                        }
10041                        if (verificationParams.getInstallerUid() >= 0) {
10042                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10043                                  verificationParams.getInstallerUid());
10044                        }
10045                    }
10046
10047                    final PackageVerificationState verificationState = new PackageVerificationState(
10048                            requiredUid, args);
10049
10050                    mPendingVerification.append(verificationId, verificationState);
10051
10052                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10053                            receivers, verificationState);
10054
10055                    /*
10056                     * If any sufficient verifiers were listed in the package
10057                     * manifest, attempt to ask them.
10058                     */
10059                    if (sufficientVerifiers != null) {
10060                        final int N = sufficientVerifiers.size();
10061                        if (N == 0) {
10062                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10063                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10064                        } else {
10065                            for (int i = 0; i < N; i++) {
10066                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10067
10068                                final Intent sufficientIntent = new Intent(verification);
10069                                sufficientIntent.setComponent(verifierComponent);
10070
10071                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
10072                            }
10073                        }
10074                    }
10075
10076                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10077                            mRequiredVerifierPackage, receivers);
10078                    if (ret == PackageManager.INSTALL_SUCCEEDED
10079                            && mRequiredVerifierPackage != null) {
10080                        /*
10081                         * Send the intent to the required verification agent,
10082                         * but only start the verification timeout after the
10083                         * target BroadcastReceivers have run.
10084                         */
10085                        verification.setComponent(requiredVerifierComponent);
10086                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
10087                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10088                                new BroadcastReceiver() {
10089                                    @Override
10090                                    public void onReceive(Context context, Intent intent) {
10091                                        final Message msg = mHandler
10092                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10093                                        msg.arg1 = verificationId;
10094                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10095                                    }
10096                                }, null, 0, null, null);
10097
10098                        /*
10099                         * We don't want the copy to proceed until verification
10100                         * succeeds, so null out this field.
10101                         */
10102                        mArgs = null;
10103                    }
10104                } else {
10105                    /*
10106                     * No package verification is enabled, so immediately start
10107                     * the remote call to initiate copy using temporary file.
10108                     */
10109                    ret = args.copyApk(mContainerService, true);
10110                }
10111            }
10112
10113            mRet = ret;
10114        }
10115
10116        @Override
10117        void handleReturnCode() {
10118            // If mArgs is null, then MCS couldn't be reached. When it
10119            // reconnects, it will try again to install. At that point, this
10120            // will succeed.
10121            if (mArgs != null) {
10122                processPendingInstall(mArgs, mRet);
10123            }
10124        }
10125
10126        @Override
10127        void handleServiceError() {
10128            mArgs = createInstallArgs(this);
10129            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10130        }
10131
10132        public boolean isForwardLocked() {
10133            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10134        }
10135    }
10136
10137    /**
10138     * Used during creation of InstallArgs
10139     *
10140     * @param installFlags package installation flags
10141     * @return true if should be installed on external storage
10142     */
10143    private static boolean installOnExternalAsec(int installFlags) {
10144        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10145            return false;
10146        }
10147        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10148            return true;
10149        }
10150        return false;
10151    }
10152
10153    /**
10154     * Used during creation of InstallArgs
10155     *
10156     * @param installFlags package installation flags
10157     * @return true if should be installed as forward locked
10158     */
10159    private static boolean installForwardLocked(int installFlags) {
10160        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10161    }
10162
10163    private InstallArgs createInstallArgs(InstallParams params) {
10164        if (params.move != null) {
10165            return new MoveInstallArgs(params);
10166        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10167            return new AsecInstallArgs(params);
10168        } else {
10169            return new FileInstallArgs(params);
10170        }
10171    }
10172
10173    /**
10174     * Create args that describe an existing installed package. Typically used
10175     * when cleaning up old installs, or used as a move source.
10176     */
10177    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10178            String resourcePath, String[] instructionSets) {
10179        final boolean isInAsec;
10180        if (installOnExternalAsec(installFlags)) {
10181            /* Apps on SD card are always in ASEC containers. */
10182            isInAsec = true;
10183        } else if (installForwardLocked(installFlags)
10184                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10185            /*
10186             * Forward-locked apps are only in ASEC containers if they're the
10187             * new style
10188             */
10189            isInAsec = true;
10190        } else {
10191            isInAsec = false;
10192        }
10193
10194        if (isInAsec) {
10195            return new AsecInstallArgs(codePath, instructionSets,
10196                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10197        } else {
10198            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10199        }
10200    }
10201
10202    static abstract class InstallArgs {
10203        /** @see InstallParams#origin */
10204        final OriginInfo origin;
10205        /** @see InstallParams#move */
10206        final MoveInfo move;
10207
10208        final IPackageInstallObserver2 observer;
10209        // Always refers to PackageManager flags only
10210        final int installFlags;
10211        final String installerPackageName;
10212        final String volumeUuid;
10213        final ManifestDigest manifestDigest;
10214        final UserHandle user;
10215        final String abiOverride;
10216
10217        // The list of instruction sets supported by this app. This is currently
10218        // only used during the rmdex() phase to clean up resources. We can get rid of this
10219        // if we move dex files under the common app path.
10220        /* nullable */ String[] instructionSets;
10221
10222        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10223                int installFlags, String installerPackageName, String volumeUuid,
10224                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10225                String abiOverride) {
10226            this.origin = origin;
10227            this.move = move;
10228            this.installFlags = installFlags;
10229            this.observer = observer;
10230            this.installerPackageName = installerPackageName;
10231            this.volumeUuid = volumeUuid;
10232            this.manifestDigest = manifestDigest;
10233            this.user = user;
10234            this.instructionSets = instructionSets;
10235            this.abiOverride = abiOverride;
10236        }
10237
10238        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10239        abstract int doPreInstall(int status);
10240
10241        /**
10242         * Rename package into final resting place. All paths on the given
10243         * scanned package should be updated to reflect the rename.
10244         */
10245        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10246        abstract int doPostInstall(int status, int uid);
10247
10248        /** @see PackageSettingBase#codePathString */
10249        abstract String getCodePath();
10250        /** @see PackageSettingBase#resourcePathString */
10251        abstract String getResourcePath();
10252
10253        // Need installer lock especially for dex file removal.
10254        abstract void cleanUpResourcesLI();
10255        abstract boolean doPostDeleteLI(boolean delete);
10256
10257        /**
10258         * Called before the source arguments are copied. This is used mostly
10259         * for MoveParams when it needs to read the source file to put it in the
10260         * destination.
10261         */
10262        int doPreCopy() {
10263            return PackageManager.INSTALL_SUCCEEDED;
10264        }
10265
10266        /**
10267         * Called after the source arguments are copied. This is used mostly for
10268         * MoveParams when it needs to read the source file to put it in the
10269         * destination.
10270         *
10271         * @return
10272         */
10273        int doPostCopy(int uid) {
10274            return PackageManager.INSTALL_SUCCEEDED;
10275        }
10276
10277        protected boolean isFwdLocked() {
10278            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10279        }
10280
10281        protected boolean isExternalAsec() {
10282            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10283        }
10284
10285        UserHandle getUser() {
10286            return user;
10287        }
10288    }
10289
10290    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10291        if (!allCodePaths.isEmpty()) {
10292            if (instructionSets == null) {
10293                throw new IllegalStateException("instructionSet == null");
10294            }
10295            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10296            for (String codePath : allCodePaths) {
10297                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10298                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10299                    if (retCode < 0) {
10300                        Slog.w(TAG, "Couldn't remove dex file for package: "
10301                                + " at location " + codePath + ", retcode=" + retCode);
10302                        // we don't consider this to be a failure of the core package deletion
10303                    }
10304                }
10305            }
10306        }
10307    }
10308
10309    /**
10310     * Logic to handle installation of non-ASEC applications, including copying
10311     * and renaming logic.
10312     */
10313    class FileInstallArgs extends InstallArgs {
10314        private File codeFile;
10315        private File resourceFile;
10316
10317        // Example topology:
10318        // /data/app/com.example/base.apk
10319        // /data/app/com.example/split_foo.apk
10320        // /data/app/com.example/lib/arm/libfoo.so
10321        // /data/app/com.example/lib/arm64/libfoo.so
10322        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10323
10324        /** New install */
10325        FileInstallArgs(InstallParams params) {
10326            super(params.origin, params.move, params.observer, params.installFlags,
10327                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10328                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10329            if (isFwdLocked()) {
10330                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10331            }
10332        }
10333
10334        /** Existing install */
10335        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10336            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10337                    null);
10338            this.codeFile = (codePath != null) ? new File(codePath) : null;
10339            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10340        }
10341
10342        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10343            if (origin.staged) {
10344                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10345                codeFile = origin.file;
10346                resourceFile = origin.file;
10347                return PackageManager.INSTALL_SUCCEEDED;
10348            }
10349
10350            try {
10351                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10352                codeFile = tempDir;
10353                resourceFile = tempDir;
10354            } catch (IOException e) {
10355                Slog.w(TAG, "Failed to create copy file: " + e);
10356                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10357            }
10358
10359            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10360                @Override
10361                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10362                    if (!FileUtils.isValidExtFilename(name)) {
10363                        throw new IllegalArgumentException("Invalid filename: " + name);
10364                    }
10365                    try {
10366                        final File file = new File(codeFile, name);
10367                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10368                                O_RDWR | O_CREAT, 0644);
10369                        Os.chmod(file.getAbsolutePath(), 0644);
10370                        return new ParcelFileDescriptor(fd);
10371                    } catch (ErrnoException e) {
10372                        throw new RemoteException("Failed to open: " + e.getMessage());
10373                    }
10374                }
10375            };
10376
10377            int ret = PackageManager.INSTALL_SUCCEEDED;
10378            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10379            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10380                Slog.e(TAG, "Failed to copy package");
10381                return ret;
10382            }
10383
10384            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10385            NativeLibraryHelper.Handle handle = null;
10386            try {
10387                handle = NativeLibraryHelper.Handle.create(codeFile);
10388                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10389                        abiOverride);
10390            } catch (IOException e) {
10391                Slog.e(TAG, "Copying native libraries failed", e);
10392                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10393            } finally {
10394                IoUtils.closeQuietly(handle);
10395            }
10396
10397            return ret;
10398        }
10399
10400        int doPreInstall(int status) {
10401            if (status != PackageManager.INSTALL_SUCCEEDED) {
10402                cleanUp();
10403            }
10404            return status;
10405        }
10406
10407        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10408            if (status != PackageManager.INSTALL_SUCCEEDED) {
10409                cleanUp();
10410                return false;
10411            }
10412
10413            final File targetDir = codeFile.getParentFile();
10414            final File beforeCodeFile = codeFile;
10415            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10416
10417            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10418            try {
10419                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10420            } catch (ErrnoException e) {
10421                Slog.w(TAG, "Failed to rename", e);
10422                return false;
10423            }
10424
10425            if (!SELinux.restoreconRecursive(afterCodeFile)) {
10426                Slog.w(TAG, "Failed to restorecon");
10427                return false;
10428            }
10429
10430            // Reflect the rename internally
10431            codeFile = afterCodeFile;
10432            resourceFile = afterCodeFile;
10433
10434            // Reflect the rename in scanned details
10435            pkg.codePath = afterCodeFile.getAbsolutePath();
10436            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10437                    pkg.baseCodePath);
10438            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10439                    pkg.splitCodePaths);
10440
10441            // Reflect the rename in app info
10442            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10443            pkg.applicationInfo.setCodePath(pkg.codePath);
10444            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10445            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10446            pkg.applicationInfo.setResourcePath(pkg.codePath);
10447            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10448            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10449
10450            return true;
10451        }
10452
10453        int doPostInstall(int status, int uid) {
10454            if (status != PackageManager.INSTALL_SUCCEEDED) {
10455                cleanUp();
10456            }
10457            return status;
10458        }
10459
10460        @Override
10461        String getCodePath() {
10462            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10463        }
10464
10465        @Override
10466        String getResourcePath() {
10467            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10468        }
10469
10470        private boolean cleanUp() {
10471            if (codeFile == null || !codeFile.exists()) {
10472                return false;
10473            }
10474
10475            if (codeFile.isDirectory()) {
10476                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10477            } else {
10478                codeFile.delete();
10479            }
10480
10481            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10482                resourceFile.delete();
10483            }
10484
10485            return true;
10486        }
10487
10488        void cleanUpResourcesLI() {
10489            // Try enumerating all code paths before deleting
10490            List<String> allCodePaths = Collections.EMPTY_LIST;
10491            if (codeFile != null && codeFile.exists()) {
10492                try {
10493                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10494                    allCodePaths = pkg.getAllCodePaths();
10495                } catch (PackageParserException e) {
10496                    // Ignored; we tried our best
10497                }
10498            }
10499
10500            cleanUp();
10501            removeDexFiles(allCodePaths, instructionSets);
10502        }
10503
10504        boolean doPostDeleteLI(boolean delete) {
10505            // XXX err, shouldn't we respect the delete flag?
10506            cleanUpResourcesLI();
10507            return true;
10508        }
10509    }
10510
10511    private boolean isAsecExternal(String cid) {
10512        final String asecPath = PackageHelper.getSdFilesystem(cid);
10513        return !asecPath.startsWith(mAsecInternalPath);
10514    }
10515
10516    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
10517            PackageManagerException {
10518        if (copyRet < 0) {
10519            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
10520                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
10521                throw new PackageManagerException(copyRet, message);
10522            }
10523        }
10524    }
10525
10526    /**
10527     * Extract the MountService "container ID" from the full code path of an
10528     * .apk.
10529     */
10530    static String cidFromCodePath(String fullCodePath) {
10531        int eidx = fullCodePath.lastIndexOf("/");
10532        String subStr1 = fullCodePath.substring(0, eidx);
10533        int sidx = subStr1.lastIndexOf("/");
10534        return subStr1.substring(sidx+1, eidx);
10535    }
10536
10537    /**
10538     * Logic to handle installation of ASEC applications, including copying and
10539     * renaming logic.
10540     */
10541    class AsecInstallArgs extends InstallArgs {
10542        static final String RES_FILE_NAME = "pkg.apk";
10543        static final String PUBLIC_RES_FILE_NAME = "res.zip";
10544
10545        String cid;
10546        String packagePath;
10547        String resourcePath;
10548
10549        /** New install */
10550        AsecInstallArgs(InstallParams params) {
10551            super(params.origin, params.move, params.observer, params.installFlags,
10552                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10553                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10554        }
10555
10556        /** Existing install */
10557        AsecInstallArgs(String fullCodePath, String[] instructionSets,
10558                        boolean isExternal, boolean isForwardLocked) {
10559            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
10560                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10561                    instructionSets, null);
10562            // Hackily pretend we're still looking at a full code path
10563            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
10564                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
10565            }
10566
10567            // Extract cid from fullCodePath
10568            int eidx = fullCodePath.lastIndexOf("/");
10569            String subStr1 = fullCodePath.substring(0, eidx);
10570            int sidx = subStr1.lastIndexOf("/");
10571            cid = subStr1.substring(sidx+1, eidx);
10572            setMountPath(subStr1);
10573        }
10574
10575        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
10576            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
10577                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10578                    instructionSets, null);
10579            this.cid = cid;
10580            setMountPath(PackageHelper.getSdDir(cid));
10581        }
10582
10583        void createCopyFile() {
10584            cid = mInstallerService.allocateExternalStageCidLegacy();
10585        }
10586
10587        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10588            if (origin.staged) {
10589                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
10590                cid = origin.cid;
10591                setMountPath(PackageHelper.getSdDir(cid));
10592                return PackageManager.INSTALL_SUCCEEDED;
10593            }
10594
10595            if (temp) {
10596                createCopyFile();
10597            } else {
10598                /*
10599                 * Pre-emptively destroy the container since it's destroyed if
10600                 * copying fails due to it existing anyway.
10601                 */
10602                PackageHelper.destroySdDir(cid);
10603            }
10604
10605            final String newMountPath = imcs.copyPackageToContainer(
10606                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
10607                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
10608
10609            if (newMountPath != null) {
10610                setMountPath(newMountPath);
10611                return PackageManager.INSTALL_SUCCEEDED;
10612            } else {
10613                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10614            }
10615        }
10616
10617        @Override
10618        String getCodePath() {
10619            return packagePath;
10620        }
10621
10622        @Override
10623        String getResourcePath() {
10624            return resourcePath;
10625        }
10626
10627        int doPreInstall(int status) {
10628            if (status != PackageManager.INSTALL_SUCCEEDED) {
10629                // Destroy container
10630                PackageHelper.destroySdDir(cid);
10631            } else {
10632                boolean mounted = PackageHelper.isContainerMounted(cid);
10633                if (!mounted) {
10634                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
10635                            Process.SYSTEM_UID);
10636                    if (newMountPath != null) {
10637                        setMountPath(newMountPath);
10638                    } else {
10639                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10640                    }
10641                }
10642            }
10643            return status;
10644        }
10645
10646        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10647            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
10648            String newMountPath = null;
10649            if (PackageHelper.isContainerMounted(cid)) {
10650                // Unmount the container
10651                if (!PackageHelper.unMountSdDir(cid)) {
10652                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
10653                    return false;
10654                }
10655            }
10656            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10657                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
10658                        " which might be stale. Will try to clean up.");
10659                // Clean up the stale container and proceed to recreate.
10660                if (!PackageHelper.destroySdDir(newCacheId)) {
10661                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
10662                    return false;
10663                }
10664                // Successfully cleaned up stale container. Try to rename again.
10665                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10666                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
10667                            + " inspite of cleaning it up.");
10668                    return false;
10669                }
10670            }
10671            if (!PackageHelper.isContainerMounted(newCacheId)) {
10672                Slog.w(TAG, "Mounting container " + newCacheId);
10673                newMountPath = PackageHelper.mountSdDir(newCacheId,
10674                        getEncryptKey(), Process.SYSTEM_UID);
10675            } else {
10676                newMountPath = PackageHelper.getSdDir(newCacheId);
10677            }
10678            if (newMountPath == null) {
10679                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
10680                return false;
10681            }
10682            Log.i(TAG, "Succesfully renamed " + cid +
10683                    " to " + newCacheId +
10684                    " at new path: " + newMountPath);
10685            cid = newCacheId;
10686
10687            final File beforeCodeFile = new File(packagePath);
10688            setMountPath(newMountPath);
10689            final File afterCodeFile = new File(packagePath);
10690
10691            // Reflect the rename in scanned details
10692            pkg.codePath = afterCodeFile.getAbsolutePath();
10693            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10694                    pkg.baseCodePath);
10695            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10696                    pkg.splitCodePaths);
10697
10698            // Reflect the rename in app info
10699            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10700            pkg.applicationInfo.setCodePath(pkg.codePath);
10701            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10702            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10703            pkg.applicationInfo.setResourcePath(pkg.codePath);
10704            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10705            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10706
10707            return true;
10708        }
10709
10710        private void setMountPath(String mountPath) {
10711            final File mountFile = new File(mountPath);
10712
10713            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
10714            if (monolithicFile.exists()) {
10715                packagePath = monolithicFile.getAbsolutePath();
10716                if (isFwdLocked()) {
10717                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
10718                } else {
10719                    resourcePath = packagePath;
10720                }
10721            } else {
10722                packagePath = mountFile.getAbsolutePath();
10723                resourcePath = packagePath;
10724            }
10725        }
10726
10727        int doPostInstall(int status, int uid) {
10728            if (status != PackageManager.INSTALL_SUCCEEDED) {
10729                cleanUp();
10730            } else {
10731                final int groupOwner;
10732                final String protectedFile;
10733                if (isFwdLocked()) {
10734                    groupOwner = UserHandle.getSharedAppGid(uid);
10735                    protectedFile = RES_FILE_NAME;
10736                } else {
10737                    groupOwner = -1;
10738                    protectedFile = null;
10739                }
10740
10741                if (uid < Process.FIRST_APPLICATION_UID
10742                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
10743                    Slog.e(TAG, "Failed to finalize " + cid);
10744                    PackageHelper.destroySdDir(cid);
10745                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10746                }
10747
10748                boolean mounted = PackageHelper.isContainerMounted(cid);
10749                if (!mounted) {
10750                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
10751                }
10752            }
10753            return status;
10754        }
10755
10756        private void cleanUp() {
10757            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
10758
10759            // Destroy secure container
10760            PackageHelper.destroySdDir(cid);
10761        }
10762
10763        private List<String> getAllCodePaths() {
10764            final File codeFile = new File(getCodePath());
10765            if (codeFile != null && codeFile.exists()) {
10766                try {
10767                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10768                    return pkg.getAllCodePaths();
10769                } catch (PackageParserException e) {
10770                    // Ignored; we tried our best
10771                }
10772            }
10773            return Collections.EMPTY_LIST;
10774        }
10775
10776        void cleanUpResourcesLI() {
10777            // Enumerate all code paths before deleting
10778            cleanUpResourcesLI(getAllCodePaths());
10779        }
10780
10781        private void cleanUpResourcesLI(List<String> allCodePaths) {
10782            cleanUp();
10783            removeDexFiles(allCodePaths, instructionSets);
10784        }
10785
10786        String getPackageName() {
10787            return getAsecPackageName(cid);
10788        }
10789
10790        boolean doPostDeleteLI(boolean delete) {
10791            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
10792            final List<String> allCodePaths = getAllCodePaths();
10793            boolean mounted = PackageHelper.isContainerMounted(cid);
10794            if (mounted) {
10795                // Unmount first
10796                if (PackageHelper.unMountSdDir(cid)) {
10797                    mounted = false;
10798                }
10799            }
10800            if (!mounted && delete) {
10801                cleanUpResourcesLI(allCodePaths);
10802            }
10803            return !mounted;
10804        }
10805
10806        @Override
10807        int doPreCopy() {
10808            if (isFwdLocked()) {
10809                if (!PackageHelper.fixSdPermissions(cid,
10810                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
10811                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10812                }
10813            }
10814
10815            return PackageManager.INSTALL_SUCCEEDED;
10816        }
10817
10818        @Override
10819        int doPostCopy(int uid) {
10820            if (isFwdLocked()) {
10821                if (uid < Process.FIRST_APPLICATION_UID
10822                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
10823                                RES_FILE_NAME)) {
10824                    Slog.e(TAG, "Failed to finalize " + cid);
10825                    PackageHelper.destroySdDir(cid);
10826                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10827                }
10828            }
10829
10830            return PackageManager.INSTALL_SUCCEEDED;
10831        }
10832    }
10833
10834    /**
10835     * Logic to handle movement of existing installed applications.
10836     */
10837    class MoveInstallArgs extends InstallArgs {
10838        private File codeFile;
10839        private File resourceFile;
10840
10841        /** New install */
10842        MoveInstallArgs(InstallParams params) {
10843            super(params.origin, params.move, params.observer, params.installFlags,
10844                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10845                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10846        }
10847
10848        int copyApk(IMediaContainerService imcs, boolean temp) {
10849            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
10850                    + move.fromUuid + " to " + move.toUuid);
10851            synchronized (mInstaller) {
10852                if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
10853                        move.dataAppName, move.appId, move.seinfo) != 0) {
10854                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10855                }
10856            }
10857
10858            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
10859            resourceFile = codeFile;
10860            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
10861
10862            return PackageManager.INSTALL_SUCCEEDED;
10863        }
10864
10865        int doPreInstall(int status) {
10866            if (status != PackageManager.INSTALL_SUCCEEDED) {
10867                cleanUp();
10868            }
10869            return status;
10870        }
10871
10872        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10873            if (status != PackageManager.INSTALL_SUCCEEDED) {
10874                cleanUp();
10875                return false;
10876            }
10877
10878            // Reflect the move in app info
10879            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10880            pkg.applicationInfo.setCodePath(pkg.codePath);
10881            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10882            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10883            pkg.applicationInfo.setResourcePath(pkg.codePath);
10884            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10885            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10886
10887            return true;
10888        }
10889
10890        int doPostInstall(int status, int uid) {
10891            if (status != PackageManager.INSTALL_SUCCEEDED) {
10892                cleanUp();
10893            }
10894            return status;
10895        }
10896
10897        @Override
10898        String getCodePath() {
10899            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10900        }
10901
10902        @Override
10903        String getResourcePath() {
10904            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10905        }
10906
10907        private boolean cleanUp() {
10908            if (codeFile == null || !codeFile.exists()) {
10909                return false;
10910            }
10911
10912            if (codeFile.isDirectory()) {
10913                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10914            } else {
10915                codeFile.delete();
10916            }
10917
10918            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10919                resourceFile.delete();
10920            }
10921
10922            return true;
10923        }
10924
10925        void cleanUpResourcesLI() {
10926            cleanUp();
10927        }
10928
10929        boolean doPostDeleteLI(boolean delete) {
10930            // XXX err, shouldn't we respect the delete flag?
10931            cleanUpResourcesLI();
10932            return true;
10933        }
10934    }
10935
10936    static String getAsecPackageName(String packageCid) {
10937        int idx = packageCid.lastIndexOf("-");
10938        if (idx == -1) {
10939            return packageCid;
10940        }
10941        return packageCid.substring(0, idx);
10942    }
10943
10944    // Utility method used to create code paths based on package name and available index.
10945    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
10946        String idxStr = "";
10947        int idx = 1;
10948        // Fall back to default value of idx=1 if prefix is not
10949        // part of oldCodePath
10950        if (oldCodePath != null) {
10951            String subStr = oldCodePath;
10952            // Drop the suffix right away
10953            if (suffix != null && subStr.endsWith(suffix)) {
10954                subStr = subStr.substring(0, subStr.length() - suffix.length());
10955            }
10956            // If oldCodePath already contains prefix find out the
10957            // ending index to either increment or decrement.
10958            int sidx = subStr.lastIndexOf(prefix);
10959            if (sidx != -1) {
10960                subStr = subStr.substring(sidx + prefix.length());
10961                if (subStr != null) {
10962                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
10963                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
10964                    }
10965                    try {
10966                        idx = Integer.parseInt(subStr);
10967                        if (idx <= 1) {
10968                            idx++;
10969                        } else {
10970                            idx--;
10971                        }
10972                    } catch(NumberFormatException e) {
10973                    }
10974                }
10975            }
10976        }
10977        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
10978        return prefix + idxStr;
10979    }
10980
10981    private File getNextCodePath(File targetDir, String packageName) {
10982        int suffix = 1;
10983        File result;
10984        do {
10985            result = new File(targetDir, packageName + "-" + suffix);
10986            suffix++;
10987        } while (result.exists());
10988        return result;
10989    }
10990
10991    // Utility method that returns the relative package path with respect
10992    // to the installation directory. Like say for /data/data/com.test-1.apk
10993    // string com.test-1 is returned.
10994    static String deriveCodePathName(String codePath) {
10995        if (codePath == null) {
10996            return null;
10997        }
10998        final File codeFile = new File(codePath);
10999        final String name = codeFile.getName();
11000        if (codeFile.isDirectory()) {
11001            return name;
11002        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11003            final int lastDot = name.lastIndexOf('.');
11004            return name.substring(0, lastDot);
11005        } else {
11006            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11007            return null;
11008        }
11009    }
11010
11011    class PackageInstalledInfo {
11012        String name;
11013        int uid;
11014        // The set of users that originally had this package installed.
11015        int[] origUsers;
11016        // The set of users that now have this package installed.
11017        int[] newUsers;
11018        PackageParser.Package pkg;
11019        int returnCode;
11020        String returnMsg;
11021        PackageRemovedInfo removedInfo;
11022
11023        public void setError(int code, String msg) {
11024            returnCode = code;
11025            returnMsg = msg;
11026            Slog.w(TAG, msg);
11027        }
11028
11029        public void setError(String msg, PackageParserException e) {
11030            returnCode = e.error;
11031            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11032            Slog.w(TAG, msg, e);
11033        }
11034
11035        public void setError(String msg, PackageManagerException e) {
11036            returnCode = e.error;
11037            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11038            Slog.w(TAG, msg, e);
11039        }
11040
11041        // In some error cases we want to convey more info back to the observer
11042        String origPackage;
11043        String origPermission;
11044    }
11045
11046    /*
11047     * Install a non-existing package.
11048     */
11049    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11050            UserHandle user, String installerPackageName, String volumeUuid,
11051            PackageInstalledInfo res) {
11052        // Remember this for later, in case we need to rollback this install
11053        String pkgName = pkg.packageName;
11054
11055        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11056        final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName,
11057                UserHandle.USER_OWNER).exists();
11058        synchronized(mPackages) {
11059            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11060                // A package with the same name is already installed, though
11061                // it has been renamed to an older name.  The package we
11062                // are trying to install should be installed as an update to
11063                // the existing one, but that has not been requested, so bail.
11064                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11065                        + " without first uninstalling package running as "
11066                        + mSettings.mRenamedPackages.get(pkgName));
11067                return;
11068            }
11069            if (mPackages.containsKey(pkgName)) {
11070                // Don't allow installation over an existing package with the same name.
11071                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11072                        + " without first uninstalling.");
11073                return;
11074            }
11075        }
11076
11077        try {
11078            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11079                    System.currentTimeMillis(), user);
11080
11081            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11082            // delete the partially installed application. the data directory will have to be
11083            // restored if it was already existing
11084            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11085                // remove package from internal structures.  Note that we want deletePackageX to
11086                // delete the package data and cache directories that it created in
11087                // scanPackageLocked, unless those directories existed before we even tried to
11088                // install.
11089                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11090                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11091                                res.removedInfo, true);
11092            }
11093
11094        } catch (PackageManagerException e) {
11095            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11096        }
11097    }
11098
11099    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11100        // Upgrade keysets are being used.  Determine if new package has a superset of the
11101        // required keys.
11102        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11103        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11104        for (int i = 0; i < upgradeKeySets.length; i++) {
11105            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11106            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
11107                return true;
11108            }
11109        }
11110        return false;
11111    }
11112
11113    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11114            UserHandle user, String installerPackageName, String volumeUuid,
11115            PackageInstalledInfo res) {
11116        final PackageParser.Package oldPackage;
11117        final String pkgName = pkg.packageName;
11118        final int[] allUsers;
11119        final boolean[] perUserInstalled;
11120        final boolean weFroze;
11121
11122        // First find the old package info and check signatures
11123        synchronized(mPackages) {
11124            oldPackage = mPackages.get(pkgName);
11125            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11126            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11127            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
11128                // default to original signature matching
11129                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11130                    != PackageManager.SIGNATURE_MATCH) {
11131                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11132                            "New package has a different signature: " + pkgName);
11133                    return;
11134                }
11135            } else {
11136                if(!checkUpgradeKeySetLP(ps, pkg)) {
11137                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11138                            "New package not signed by keys specified by upgrade-keysets: "
11139                            + pkgName);
11140                    return;
11141                }
11142            }
11143
11144            // In case of rollback, remember per-user/profile install state
11145            allUsers = sUserManager.getUserIds();
11146            perUserInstalled = new boolean[allUsers.length];
11147            for (int i = 0; i < allUsers.length; i++) {
11148                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11149            }
11150
11151            // Mark the app as frozen to prevent launching during the upgrade
11152            // process, and then kill all running instances
11153            if (!ps.frozen) {
11154                ps.frozen = true;
11155                weFroze = true;
11156            } else {
11157                weFroze = false;
11158            }
11159        }
11160
11161        // Now that we're guarded by frozen state, kill app during upgrade
11162        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11163
11164        try {
11165            boolean sysPkg = (isSystemApp(oldPackage));
11166            if (sysPkg) {
11167                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11168                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11169            } else {
11170                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11171                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11172            }
11173        } finally {
11174            // Regardless of success or failure of upgrade steps above, always
11175            // unfreeze the package if we froze it
11176            if (weFroze) {
11177                unfreezePackage(pkgName);
11178            }
11179        }
11180    }
11181
11182    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11183            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11184            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11185            String volumeUuid, PackageInstalledInfo res) {
11186        String pkgName = deletedPackage.packageName;
11187        boolean deletedPkg = true;
11188        boolean updatedSettings = false;
11189
11190        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11191                + deletedPackage);
11192        long origUpdateTime;
11193        if (pkg.mExtras != null) {
11194            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11195        } else {
11196            origUpdateTime = 0;
11197        }
11198
11199        // First delete the existing package while retaining the data directory
11200        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11201                res.removedInfo, true)) {
11202            // If the existing package wasn't successfully deleted
11203            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11204            deletedPkg = false;
11205        } else {
11206            // Successfully deleted the old package; proceed with replace.
11207
11208            // If deleted package lived in a container, give users a chance to
11209            // relinquish resources before killing.
11210            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11211                if (DEBUG_INSTALL) {
11212                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11213                }
11214                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11215                final ArrayList<String> pkgList = new ArrayList<String>(1);
11216                pkgList.add(deletedPackage.applicationInfo.packageName);
11217                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11218            }
11219
11220            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11221            try {
11222                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11223                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11224                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11225                        perUserInstalled, res, user);
11226                updatedSettings = true;
11227            } catch (PackageManagerException e) {
11228                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11229            }
11230        }
11231
11232        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11233            // remove package from internal structures.  Note that we want deletePackageX to
11234            // delete the package data and cache directories that it created in
11235            // scanPackageLocked, unless those directories existed before we even tried to
11236            // install.
11237            if(updatedSettings) {
11238                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11239                deletePackageLI(
11240                        pkgName, null, true, allUsers, perUserInstalled,
11241                        PackageManager.DELETE_KEEP_DATA,
11242                                res.removedInfo, true);
11243            }
11244            // Since we failed to install the new package we need to restore the old
11245            // package that we deleted.
11246            if (deletedPkg) {
11247                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11248                File restoreFile = new File(deletedPackage.codePath);
11249                // Parse old package
11250                boolean oldExternal = isExternal(deletedPackage);
11251                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11252                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11253                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11254                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11255                try {
11256                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11257                } catch (PackageManagerException e) {
11258                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11259                            + e.getMessage());
11260                    return;
11261                }
11262                // Restore of old package succeeded. Update permissions.
11263                // writer
11264                synchronized (mPackages) {
11265                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11266                            UPDATE_PERMISSIONS_ALL);
11267                    // can downgrade to reader
11268                    mSettings.writeLPr();
11269                }
11270                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11271            }
11272        }
11273    }
11274
11275    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11276            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11277            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11278            String volumeUuid, PackageInstalledInfo res) {
11279        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11280                + ", old=" + deletedPackage);
11281        boolean disabledSystem = false;
11282        boolean updatedSettings = false;
11283        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11284        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11285                != 0) {
11286            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11287        }
11288        String packageName = deletedPackage.packageName;
11289        if (packageName == null) {
11290            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11291                    "Attempt to delete null packageName.");
11292            return;
11293        }
11294        PackageParser.Package oldPkg;
11295        PackageSetting oldPkgSetting;
11296        // reader
11297        synchronized (mPackages) {
11298            oldPkg = mPackages.get(packageName);
11299            oldPkgSetting = mSettings.mPackages.get(packageName);
11300            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11301                    (oldPkgSetting == null)) {
11302                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11303                        "Couldn't find package:" + packageName + " information");
11304                return;
11305            }
11306        }
11307
11308        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11309        res.removedInfo.removedPackage = packageName;
11310        // Remove existing system package
11311        removePackageLI(oldPkgSetting, true);
11312        // writer
11313        synchronized (mPackages) {
11314            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11315            if (!disabledSystem && deletedPackage != null) {
11316                // We didn't need to disable the .apk as a current system package,
11317                // which means we are replacing another update that is already
11318                // installed.  We need to make sure to delete the older one's .apk.
11319                res.removedInfo.args = createInstallArgsForExisting(0,
11320                        deletedPackage.applicationInfo.getCodePath(),
11321                        deletedPackage.applicationInfo.getResourcePath(),
11322                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11323            } else {
11324                res.removedInfo.args = null;
11325            }
11326        }
11327
11328        // Successfully disabled the old package. Now proceed with re-installation
11329        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11330
11331        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11332        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11333
11334        PackageParser.Package newPackage = null;
11335        try {
11336            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11337            if (newPackage.mExtras != null) {
11338                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11339                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11340                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11341
11342                // is the update attempting to change shared user? that isn't going to work...
11343                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11344                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11345                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11346                            + " to " + newPkgSetting.sharedUser);
11347                    updatedSettings = true;
11348                }
11349            }
11350
11351            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11352                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11353                        perUserInstalled, res, user);
11354                updatedSettings = true;
11355            }
11356
11357        } catch (PackageManagerException e) {
11358            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11359        }
11360
11361        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11362            // Re installation failed. Restore old information
11363            // Remove new pkg information
11364            if (newPackage != null) {
11365                removeInstalledPackageLI(newPackage, true);
11366            }
11367            // Add back the old system package
11368            try {
11369                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11370            } catch (PackageManagerException e) {
11371                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11372            }
11373            // Restore the old system information in Settings
11374            synchronized (mPackages) {
11375                if (disabledSystem) {
11376                    mSettings.enableSystemPackageLPw(packageName);
11377                }
11378                if (updatedSettings) {
11379                    mSettings.setInstallerPackageName(packageName,
11380                            oldPkgSetting.installerPackageName);
11381                }
11382                mSettings.writeLPr();
11383            }
11384        }
11385    }
11386
11387    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
11388            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
11389            UserHandle user) {
11390        String pkgName = newPackage.packageName;
11391        synchronized (mPackages) {
11392            //write settings. the installStatus will be incomplete at this stage.
11393            //note that the new package setting would have already been
11394            //added to mPackages. It hasn't been persisted yet.
11395            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11396            mSettings.writeLPr();
11397        }
11398
11399        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11400
11401        synchronized (mPackages) {
11402            updatePermissionsLPw(newPackage.packageName, newPackage,
11403                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11404                            ? UPDATE_PERMISSIONS_ALL : 0));
11405            // For system-bundled packages, we assume that installing an upgraded version
11406            // of the package implies that the user actually wants to run that new code,
11407            // so we enable the package.
11408            PackageSetting ps = mSettings.mPackages.get(pkgName);
11409            if (ps != null) {
11410                if (isSystemApp(newPackage)) {
11411                    // NB: implicit assumption that system package upgrades apply to all users
11412                    if (DEBUG_INSTALL) {
11413                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
11414                    }
11415                    if (res.origUsers != null) {
11416                        for (int userHandle : res.origUsers) {
11417                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
11418                                    userHandle, installerPackageName);
11419                        }
11420                    }
11421                    // Also convey the prior install/uninstall state
11422                    if (allUsers != null && perUserInstalled != null) {
11423                        for (int i = 0; i < allUsers.length; i++) {
11424                            if (DEBUG_INSTALL) {
11425                                Slog.d(TAG, "    user " + allUsers[i]
11426                                        + " => " + perUserInstalled[i]);
11427                            }
11428                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
11429                        }
11430                        // these install state changes will be persisted in the
11431                        // upcoming call to mSettings.writeLPr().
11432                    }
11433                }
11434                // It's implied that when a user requests installation, they want the app to be
11435                // installed and enabled.
11436                int userId = user.getIdentifier();
11437                if (userId != UserHandle.USER_ALL) {
11438                    ps.setInstalled(true, userId);
11439                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
11440                }
11441            }
11442            res.name = pkgName;
11443            res.uid = newPackage.applicationInfo.uid;
11444            res.pkg = newPackage;
11445            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
11446            mSettings.setInstallerPackageName(pkgName, installerPackageName);
11447            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11448            //to update install status
11449            mSettings.writeLPr();
11450        }
11451    }
11452
11453    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
11454        final int installFlags = args.installFlags;
11455        final String installerPackageName = args.installerPackageName;
11456        final String volumeUuid = args.volumeUuid;
11457        final File tmpPackageFile = new File(args.getCodePath());
11458        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
11459        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
11460                || (args.volumeUuid != null));
11461        boolean replace = false;
11462        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
11463        // Result object to be returned
11464        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11465
11466        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
11467        // Retrieve PackageSettings and parse package
11468        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
11469                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
11470                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11471        PackageParser pp = new PackageParser();
11472        pp.setSeparateProcesses(mSeparateProcesses);
11473        pp.setDisplayMetrics(mMetrics);
11474
11475        final PackageParser.Package pkg;
11476        try {
11477            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
11478        } catch (PackageParserException e) {
11479            res.setError("Failed parse during installPackageLI", e);
11480            return;
11481        }
11482
11483        // Mark that we have an install time CPU ABI override.
11484        pkg.cpuAbiOverride = args.abiOverride;
11485
11486        String pkgName = res.name = pkg.packageName;
11487        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
11488            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
11489                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
11490                return;
11491            }
11492        }
11493
11494        try {
11495            pp.collectCertificates(pkg, parseFlags);
11496            pp.collectManifestDigest(pkg);
11497        } catch (PackageParserException e) {
11498            res.setError("Failed collect during installPackageLI", e);
11499            return;
11500        }
11501
11502        /* If the installer passed in a manifest digest, compare it now. */
11503        if (args.manifestDigest != null) {
11504            if (DEBUG_INSTALL) {
11505                final String parsedManifest = pkg.manifestDigest == null ? "null"
11506                        : pkg.manifestDigest.toString();
11507                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
11508                        + parsedManifest);
11509            }
11510
11511            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
11512                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
11513                return;
11514            }
11515        } else if (DEBUG_INSTALL) {
11516            final String parsedManifest = pkg.manifestDigest == null
11517                    ? "null" : pkg.manifestDigest.toString();
11518            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
11519        }
11520
11521        // Get rid of all references to package scan path via parser.
11522        pp = null;
11523        String oldCodePath = null;
11524        boolean systemApp = false;
11525        synchronized (mPackages) {
11526            // Check if installing already existing package
11527            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11528                String oldName = mSettings.mRenamedPackages.get(pkgName);
11529                if (pkg.mOriginalPackages != null
11530                        && pkg.mOriginalPackages.contains(oldName)
11531                        && mPackages.containsKey(oldName)) {
11532                    // This package is derived from an original package,
11533                    // and this device has been updating from that original
11534                    // name.  We must continue using the original name, so
11535                    // rename the new package here.
11536                    pkg.setPackageName(oldName);
11537                    pkgName = pkg.packageName;
11538                    replace = true;
11539                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
11540                            + oldName + " pkgName=" + pkgName);
11541                } else if (mPackages.containsKey(pkgName)) {
11542                    // This package, under its official name, already exists
11543                    // on the device; we should replace it.
11544                    replace = true;
11545                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
11546                }
11547
11548                // Prevent apps opting out from runtime permissions
11549                if (replace) {
11550                    PackageParser.Package oldPackage = mPackages.get(pkgName);
11551                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
11552                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
11553                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
11554                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
11555                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
11556                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
11557                                        + " doesn't support runtime permissions but the old"
11558                                        + " target SDK " + oldTargetSdk + " does.");
11559                        return;
11560                    }
11561                }
11562            }
11563
11564            PackageSetting ps = mSettings.mPackages.get(pkgName);
11565            if (ps != null) {
11566                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
11567
11568                // Quick sanity check that we're signed correctly if updating;
11569                // we'll check this again later when scanning, but we want to
11570                // bail early here before tripping over redefined permissions.
11571                if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
11572                    try {
11573                        verifySignaturesLP(ps, pkg);
11574                    } catch (PackageManagerException e) {
11575                        res.setError(e.error, e.getMessage());
11576                        return;
11577                    }
11578                } else {
11579                    if (!checkUpgradeKeySetLP(ps, pkg)) {
11580                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
11581                                + pkg.packageName + " upgrade keys do not match the "
11582                                + "previously installed version");
11583                        return;
11584                    }
11585                }
11586
11587                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
11588                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
11589                    systemApp = (ps.pkg.applicationInfo.flags &
11590                            ApplicationInfo.FLAG_SYSTEM) != 0;
11591                }
11592                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11593            }
11594
11595            // Check whether the newly-scanned package wants to define an already-defined perm
11596            int N = pkg.permissions.size();
11597            for (int i = N-1; i >= 0; i--) {
11598                PackageParser.Permission perm = pkg.permissions.get(i);
11599                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
11600                if (bp != null) {
11601                    // If the defining package is signed with our cert, it's okay.  This
11602                    // also includes the "updating the same package" case, of course.
11603                    // "updating same package" could also involve key-rotation.
11604                    final boolean sigsOk;
11605                    if (!bp.sourcePackage.equals(pkg.packageName)
11606                            || !(bp.packageSetting instanceof PackageSetting)
11607                            || !bp.packageSetting.keySetData.isUsingUpgradeKeySets()
11608                            || ((PackageSetting) bp.packageSetting).sharedUser != null) {
11609                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
11610                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
11611                    } else {
11612                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
11613                    }
11614                    if (!sigsOk) {
11615                        // If the owning package is the system itself, we log but allow
11616                        // install to proceed; we fail the install on all other permission
11617                        // redefinitions.
11618                        if (!bp.sourcePackage.equals("android")) {
11619                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
11620                                    + pkg.packageName + " attempting to redeclare permission "
11621                                    + perm.info.name + " already owned by " + bp.sourcePackage);
11622                            res.origPermission = perm.info.name;
11623                            res.origPackage = bp.sourcePackage;
11624                            return;
11625                        } else {
11626                            Slog.w(TAG, "Package " + pkg.packageName
11627                                    + " attempting to redeclare system permission "
11628                                    + perm.info.name + "; ignoring new declaration");
11629                            pkg.permissions.remove(i);
11630                        }
11631                    }
11632                }
11633            }
11634
11635        }
11636
11637        if (systemApp && onExternal) {
11638            // Disable updates to system apps on sdcard
11639            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11640                    "Cannot install updates to system apps on sdcard");
11641            return;
11642        }
11643
11644        if (args.move != null) {
11645            // We did an in-place move, so dex is ready to roll
11646            scanFlags |= SCAN_NO_DEX;
11647            scanFlags |= SCAN_MOVE;
11648        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
11649            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
11650            scanFlags |= SCAN_NO_DEX;
11651
11652            try {
11653                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
11654                        true /* extract libs */);
11655            } catch (PackageManagerException pme) {
11656                Slog.e(TAG, "Error deriving application ABI", pme);
11657                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
11658                return;
11659            }
11660
11661            // Run dexopt before old package gets removed, to minimize time when app is unavailable
11662            int result = mPackageDexOptimizer
11663                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
11664                            false /* defer */, false /* inclDependencies */);
11665            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
11666                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
11667                return;
11668            }
11669        }
11670
11671        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
11672            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
11673            return;
11674        }
11675
11676        startIntentFilterVerifications(args.user.getIdentifier(), pkg);
11677
11678        if (replace) {
11679            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
11680                    installerPackageName, volumeUuid, res);
11681        } else {
11682            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
11683                    args.user, installerPackageName, volumeUuid, res);
11684        }
11685        synchronized (mPackages) {
11686            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11687            if (ps != null) {
11688                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11689            }
11690        }
11691    }
11692
11693    private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) {
11694        if (mIntentFilterVerifierComponent == null) {
11695            Slog.w(TAG, "No IntentFilter verification will not be done as "
11696                    + "there is no IntentFilterVerifier available!");
11697            return;
11698        }
11699
11700        final int verifierUid = getPackageUid(
11701                mIntentFilterVerifierComponent.getPackageName(),
11702                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
11703
11704        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
11705        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
11706        msg.obj = pkg;
11707        msg.arg1 = userId;
11708        msg.arg2 = verifierUid;
11709
11710        mHandler.sendMessage(msg);
11711    }
11712
11713    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid,
11714            PackageParser.Package pkg) {
11715        int size = pkg.activities.size();
11716        if (size == 0) {
11717            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
11718                    "No activity, so no need to verify any IntentFilter!");
11719            return;
11720        }
11721
11722        final boolean hasDomainURLs = hasDomainURLs(pkg);
11723        if (!hasDomainURLs) {
11724            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
11725                    "No domain URLs, so no need to verify any IntentFilter!");
11726            return;
11727        }
11728
11729        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
11730                + " if any IntentFilter from the " + size
11731                + " Activities needs verification ...");
11732
11733        final int verificationId = mIntentFilterVerificationToken++;
11734        int count = 0;
11735        final String packageName = pkg.packageName;
11736        ArrayList<String> allHosts = new ArrayList<>();
11737
11738        synchronized (mPackages) {
11739            for (PackageParser.Activity a : pkg.activities) {
11740                for (ActivityIntentInfo filter : a.intents) {
11741                    boolean needsFilterVerification = filter.needsVerification();
11742                    if (needsFilterVerification && needsNetworkVerificationLPr(filter)) {
11743                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
11744                                "Verification needed for IntentFilter:" + filter.toString());
11745                        mIntentFilterVerifier.addOneIntentFilterVerification(
11746                                verifierUid, userId, verificationId, filter, packageName);
11747                        count++;
11748                    } else if (!needsFilterVerification) {
11749                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
11750                                "No verification needed for IntentFilter:" + filter.toString());
11751                        if (hasValidDomains(filter)) {
11752                            ArrayList<String> hosts = filter.getHostsList();
11753                            if (hosts.size() > 0) {
11754                                allHosts.addAll(hosts);
11755                            } else {
11756                                if (allHosts.isEmpty()) {
11757                                    allHosts.add("*");
11758                                }
11759                            }
11760                        }
11761                    } else {
11762                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
11763                                "Verification already done for IntentFilter:" + filter.toString());
11764                    }
11765                }
11766            }
11767        }
11768
11769        if (count > 0) {
11770            mIntentFilterVerifier.startVerifications(userId);
11771            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Started " + count
11772                    + " IntentFilter verification" + (count > 1 ? "s" : "")
11773                    +  " for userId:" + userId + "!");
11774        } else {
11775            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
11776                    "No need to start any IntentFilter verification!");
11777            if (allHosts.size() > 0 && mSettings.createIntentFilterVerificationIfNeededLPw(
11778                    packageName, allHosts) != null) {
11779                scheduleWriteSettingsLocked();
11780            }
11781        }
11782    }
11783
11784    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
11785        final ComponentName cn  = filter.activity.getComponentName();
11786        final String packageName = cn.getPackageName();
11787
11788        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
11789                packageName);
11790        if (ivi == null) {
11791            return true;
11792        }
11793        int status = ivi.getStatus();
11794        switch (status) {
11795            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
11796            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
11797                return true;
11798
11799            default:
11800                // Nothing to do
11801                return false;
11802        }
11803    }
11804
11805    private boolean isSystemComponentOrPersistentPrivApp(PackageParser.Package pkg) {
11806        return UserHandle.getAppId(pkg.applicationInfo.uid) < FIRST_APPLICATION_UID
11807                || ((pkg.applicationInfo.privateFlags
11808                        & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0
11809                && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0);
11810    }
11811
11812    private static boolean isMultiArch(PackageSetting ps) {
11813        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
11814    }
11815
11816    private static boolean isMultiArch(ApplicationInfo info) {
11817        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
11818    }
11819
11820    private static boolean isExternal(PackageParser.Package pkg) {
11821        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11822    }
11823
11824    private static boolean isExternal(PackageSetting ps) {
11825        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11826    }
11827
11828    private static boolean isExternal(ApplicationInfo info) {
11829        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11830    }
11831
11832    private static boolean isSystemApp(PackageParser.Package pkg) {
11833        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
11834    }
11835
11836    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
11837        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
11838    }
11839
11840    private static boolean hasDomainURLs(PackageParser.Package pkg) {
11841        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
11842    }
11843
11844    private static boolean isSystemApp(PackageSetting ps) {
11845        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
11846    }
11847
11848    private static boolean isUpdatedSystemApp(PackageSetting ps) {
11849        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
11850    }
11851
11852    private int packageFlagsToInstallFlags(PackageSetting ps) {
11853        int installFlags = 0;
11854        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
11855            // This existing package was an external ASEC install when we have
11856            // the external flag without a UUID
11857            installFlags |= PackageManager.INSTALL_EXTERNAL;
11858        }
11859        if (ps.isForwardLocked()) {
11860            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
11861        }
11862        return installFlags;
11863    }
11864
11865    private void deleteTempPackageFiles() {
11866        final FilenameFilter filter = new FilenameFilter() {
11867            public boolean accept(File dir, String name) {
11868                return name.startsWith("vmdl") && name.endsWith(".tmp");
11869            }
11870        };
11871        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
11872            file.delete();
11873        }
11874    }
11875
11876    @Override
11877    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
11878            int flags) {
11879        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
11880                flags);
11881    }
11882
11883    @Override
11884    public void deletePackage(final String packageName,
11885            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
11886        mContext.enforceCallingOrSelfPermission(
11887                android.Manifest.permission.DELETE_PACKAGES, null);
11888        final int uid = Binder.getCallingUid();
11889        if (UserHandle.getUserId(uid) != userId) {
11890            mContext.enforceCallingPermission(
11891                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
11892                    "deletePackage for user " + userId);
11893        }
11894        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
11895            try {
11896                observer.onPackageDeleted(packageName,
11897                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
11898            } catch (RemoteException re) {
11899            }
11900            return;
11901        }
11902
11903        boolean uninstallBlocked = false;
11904        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
11905            int[] users = sUserManager.getUserIds();
11906            for (int i = 0; i < users.length; ++i) {
11907                if (getBlockUninstallForUser(packageName, users[i])) {
11908                    uninstallBlocked = true;
11909                    break;
11910                }
11911            }
11912        } else {
11913            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
11914        }
11915        if (uninstallBlocked) {
11916            try {
11917                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
11918                        null);
11919            } catch (RemoteException re) {
11920            }
11921            return;
11922        }
11923
11924        if (DEBUG_REMOVE) {
11925            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
11926        }
11927        // Queue up an async operation since the package deletion may take a little while.
11928        mHandler.post(new Runnable() {
11929            public void run() {
11930                mHandler.removeCallbacks(this);
11931                final int returnCode = deletePackageX(packageName, userId, flags);
11932                if (observer != null) {
11933                    try {
11934                        observer.onPackageDeleted(packageName, returnCode, null);
11935                    } catch (RemoteException e) {
11936                        Log.i(TAG, "Observer no longer exists.");
11937                    } //end catch
11938                } //end if
11939            } //end run
11940        });
11941    }
11942
11943    private boolean isPackageDeviceAdmin(String packageName, int userId) {
11944        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
11945                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
11946        try {
11947            if (dpm != null) {
11948                if (dpm.isDeviceOwner(packageName)) {
11949                    return true;
11950                }
11951                int[] users;
11952                if (userId == UserHandle.USER_ALL) {
11953                    users = sUserManager.getUserIds();
11954                } else {
11955                    users = new int[]{userId};
11956                }
11957                for (int i = 0; i < users.length; ++i) {
11958                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
11959                        return true;
11960                    }
11961                }
11962            }
11963        } catch (RemoteException e) {
11964        }
11965        return false;
11966    }
11967
11968    /**
11969     *  This method is an internal method that could be get invoked either
11970     *  to delete an installed package or to clean up a failed installation.
11971     *  After deleting an installed package, a broadcast is sent to notify any
11972     *  listeners that the package has been installed. For cleaning up a failed
11973     *  installation, the broadcast is not necessary since the package's
11974     *  installation wouldn't have sent the initial broadcast either
11975     *  The key steps in deleting a package are
11976     *  deleting the package information in internal structures like mPackages,
11977     *  deleting the packages base directories through installd
11978     *  updating mSettings to reflect current status
11979     *  persisting settings for later use
11980     *  sending a broadcast if necessary
11981     */
11982    private int deletePackageX(String packageName, int userId, int flags) {
11983        final PackageRemovedInfo info = new PackageRemovedInfo();
11984        final boolean res;
11985
11986        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
11987                ? UserHandle.ALL : new UserHandle(userId);
11988
11989        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
11990            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
11991            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
11992        }
11993
11994        boolean removedForAllUsers = false;
11995        boolean systemUpdate = false;
11996
11997        // for the uninstall-updates case and restricted profiles, remember the per-
11998        // userhandle installed state
11999        int[] allUsers;
12000        boolean[] perUserInstalled;
12001        synchronized (mPackages) {
12002            PackageSetting ps = mSettings.mPackages.get(packageName);
12003            allUsers = sUserManager.getUserIds();
12004            perUserInstalled = new boolean[allUsers.length];
12005            for (int i = 0; i < allUsers.length; i++) {
12006                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12007            }
12008        }
12009
12010        synchronized (mInstallLock) {
12011            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12012            res = deletePackageLI(packageName, removeForUser,
12013                    true, allUsers, perUserInstalled,
12014                    flags | REMOVE_CHATTY, info, true);
12015            systemUpdate = info.isRemovedPackageSystemUpdate;
12016            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12017                removedForAllUsers = true;
12018            }
12019            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12020                    + " removedForAllUsers=" + removedForAllUsers);
12021        }
12022
12023        if (res) {
12024            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12025
12026            // If the removed package was a system update, the old system package
12027            // was re-enabled; we need to broadcast this information
12028            if (systemUpdate) {
12029                Bundle extras = new Bundle(1);
12030                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12031                        ? info.removedAppId : info.uid);
12032                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12033
12034                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12035                        extras, null, null, null);
12036                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12037                        extras, null, null, null);
12038                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12039                        null, packageName, null, null);
12040            }
12041        }
12042        // Force a gc here.
12043        Runtime.getRuntime().gc();
12044        // Delete the resources here after sending the broadcast to let
12045        // other processes clean up before deleting resources.
12046        if (info.args != null) {
12047            synchronized (mInstallLock) {
12048                info.args.doPostDeleteLI(true);
12049            }
12050        }
12051
12052        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12053    }
12054
12055    class PackageRemovedInfo {
12056        String removedPackage;
12057        int uid = -1;
12058        int removedAppId = -1;
12059        int[] removedUsers = null;
12060        boolean isRemovedPackageSystemUpdate = false;
12061        // Clean up resources deleted packages.
12062        InstallArgs args = null;
12063
12064        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12065            Bundle extras = new Bundle(1);
12066            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12067            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12068            if (replacing) {
12069                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12070            }
12071            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12072            if (removedPackage != null) {
12073                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12074                        extras, null, null, removedUsers);
12075                if (fullRemove && !replacing) {
12076                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12077                            extras, null, null, removedUsers);
12078                }
12079            }
12080            if (removedAppId >= 0) {
12081                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12082                        removedUsers);
12083            }
12084        }
12085    }
12086
12087    /*
12088     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12089     * flag is not set, the data directory is removed as well.
12090     * make sure this flag is set for partially installed apps. If not its meaningless to
12091     * delete a partially installed application.
12092     */
12093    private void removePackageDataLI(PackageSetting ps,
12094            int[] allUserHandles, boolean[] perUserInstalled,
12095            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12096        String packageName = ps.name;
12097        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12098        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12099        // Retrieve object to delete permissions for shared user later on
12100        final PackageSetting deletedPs;
12101        // reader
12102        synchronized (mPackages) {
12103            deletedPs = mSettings.mPackages.get(packageName);
12104            if (outInfo != null) {
12105                outInfo.removedPackage = packageName;
12106                outInfo.removedUsers = deletedPs != null
12107                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12108                        : null;
12109            }
12110        }
12111        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12112            removeDataDirsLI(ps.volumeUuid, packageName);
12113            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12114        }
12115        // writer
12116        synchronized (mPackages) {
12117            if (deletedPs != null) {
12118                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12119                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12120                    clearDefaultBrowserIfNeeded(packageName);
12121                    if (outInfo != null) {
12122                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12123                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12124                    }
12125                    updatePermissionsLPw(deletedPs.name, null, 0);
12126                    if (deletedPs.sharedUser != null) {
12127                        // Remove permissions associated with package. Since runtime
12128                        // permissions are per user we have to kill the removed package
12129                        // or packages running under the shared user of the removed
12130                        // package if revoking the permissions requested only by the removed
12131                        // package is successful and this causes a change in gids.
12132                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12133                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12134                                    userId);
12135                            if (userIdToKill == UserHandle.USER_ALL
12136                                    || userIdToKill >= UserHandle.USER_OWNER) {
12137                                // If gids changed for this user, kill all affected packages.
12138                                mHandler.post(new Runnable() {
12139                                    @Override
12140                                    public void run() {
12141                                        // This has to happen with no lock held.
12142                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12143                                                KILL_APP_REASON_GIDS_CHANGED);
12144                                    }
12145                                });
12146                            break;
12147                            }
12148                        }
12149                    }
12150                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12151                }
12152                // make sure to preserve per-user disabled state if this removal was just
12153                // a downgrade of a system app to the factory package
12154                if (allUserHandles != null && perUserInstalled != null) {
12155                    if (DEBUG_REMOVE) {
12156                        Slog.d(TAG, "Propagating install state across downgrade");
12157                    }
12158                    for (int i = 0; i < allUserHandles.length; i++) {
12159                        if (DEBUG_REMOVE) {
12160                            Slog.d(TAG, "    user " + allUserHandles[i]
12161                                    + " => " + perUserInstalled[i]);
12162                        }
12163                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12164                    }
12165                }
12166            }
12167            // can downgrade to reader
12168            if (writeSettings) {
12169                // Save settings now
12170                mSettings.writeLPr();
12171            }
12172        }
12173        if (outInfo != null) {
12174            // A user ID was deleted here. Go through all users and remove it
12175            // from KeyStore.
12176            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12177        }
12178    }
12179
12180    static boolean locationIsPrivileged(File path) {
12181        try {
12182            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12183                    .getCanonicalPath();
12184            return path.getCanonicalPath().startsWith(privilegedAppDir);
12185        } catch (IOException e) {
12186            Slog.e(TAG, "Unable to access code path " + path);
12187        }
12188        return false;
12189    }
12190
12191    /*
12192     * Tries to delete system package.
12193     */
12194    private boolean deleteSystemPackageLI(PackageSetting newPs,
12195            int[] allUserHandles, boolean[] perUserInstalled,
12196            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12197        final boolean applyUserRestrictions
12198                = (allUserHandles != null) && (perUserInstalled != null);
12199        PackageSetting disabledPs = null;
12200        // Confirm if the system package has been updated
12201        // An updated system app can be deleted. This will also have to restore
12202        // the system pkg from system partition
12203        // reader
12204        synchronized (mPackages) {
12205            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12206        }
12207        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12208                + " disabledPs=" + disabledPs);
12209        if (disabledPs == null) {
12210            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12211            return false;
12212        } else if (DEBUG_REMOVE) {
12213            Slog.d(TAG, "Deleting system pkg from data partition");
12214        }
12215        if (DEBUG_REMOVE) {
12216            if (applyUserRestrictions) {
12217                Slog.d(TAG, "Remembering install states:");
12218                for (int i = 0; i < allUserHandles.length; i++) {
12219                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12220                }
12221            }
12222        }
12223        // Delete the updated package
12224        outInfo.isRemovedPackageSystemUpdate = true;
12225        if (disabledPs.versionCode < newPs.versionCode) {
12226            // Delete data for downgrades
12227            flags &= ~PackageManager.DELETE_KEEP_DATA;
12228        } else {
12229            // Preserve data by setting flag
12230            flags |= PackageManager.DELETE_KEEP_DATA;
12231        }
12232        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12233                allUserHandles, perUserInstalled, outInfo, writeSettings);
12234        if (!ret) {
12235            return false;
12236        }
12237        // writer
12238        synchronized (mPackages) {
12239            // Reinstate the old system package
12240            mSettings.enableSystemPackageLPw(newPs.name);
12241            // Remove any native libraries from the upgraded package.
12242            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12243        }
12244        // Install the system package
12245        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12246        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12247        if (locationIsPrivileged(disabledPs.codePath)) {
12248            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12249        }
12250
12251        final PackageParser.Package newPkg;
12252        try {
12253            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12254        } catch (PackageManagerException e) {
12255            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12256            return false;
12257        }
12258
12259        // writer
12260        synchronized (mPackages) {
12261            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12262            updatePermissionsLPw(newPkg.packageName, newPkg,
12263                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12264            if (applyUserRestrictions) {
12265                if (DEBUG_REMOVE) {
12266                    Slog.d(TAG, "Propagating install state across reinstall");
12267                }
12268                for (int i = 0; i < allUserHandles.length; i++) {
12269                    if (DEBUG_REMOVE) {
12270                        Slog.d(TAG, "    user " + allUserHandles[i]
12271                                + " => " + perUserInstalled[i]);
12272                    }
12273                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12274                }
12275                // Regardless of writeSettings we need to ensure that this restriction
12276                // state propagation is persisted
12277                mSettings.writeAllUsersPackageRestrictionsLPr();
12278            }
12279            // can downgrade to reader here
12280            if (writeSettings) {
12281                mSettings.writeLPr();
12282            }
12283        }
12284        return true;
12285    }
12286
12287    private boolean deleteInstalledPackageLI(PackageSetting ps,
12288            boolean deleteCodeAndResources, int flags,
12289            int[] allUserHandles, boolean[] perUserInstalled,
12290            PackageRemovedInfo outInfo, boolean writeSettings) {
12291        if (outInfo != null) {
12292            outInfo.uid = ps.appId;
12293        }
12294
12295        // Delete package data from internal structures and also remove data if flag is set
12296        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12297
12298        // Delete application code and resources
12299        if (deleteCodeAndResources && (outInfo != null)) {
12300            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12301                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12302            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12303        }
12304        return true;
12305    }
12306
12307    @Override
12308    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12309            int userId) {
12310        mContext.enforceCallingOrSelfPermission(
12311                android.Manifest.permission.DELETE_PACKAGES, null);
12312        synchronized (mPackages) {
12313            PackageSetting ps = mSettings.mPackages.get(packageName);
12314            if (ps == null) {
12315                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12316                return false;
12317            }
12318            if (!ps.getInstalled(userId)) {
12319                // Can't block uninstall for an app that is not installed or enabled.
12320                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12321                return false;
12322            }
12323            ps.setBlockUninstall(blockUninstall, userId);
12324            mSettings.writePackageRestrictionsLPr(userId);
12325        }
12326        return true;
12327    }
12328
12329    @Override
12330    public boolean getBlockUninstallForUser(String packageName, int userId) {
12331        synchronized (mPackages) {
12332            PackageSetting ps = mSettings.mPackages.get(packageName);
12333            if (ps == null) {
12334                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
12335                return false;
12336            }
12337            return ps.getBlockUninstall(userId);
12338        }
12339    }
12340
12341    /*
12342     * This method handles package deletion in general
12343     */
12344    private boolean deletePackageLI(String packageName, UserHandle user,
12345            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
12346            int flags, PackageRemovedInfo outInfo,
12347            boolean writeSettings) {
12348        if (packageName == null) {
12349            Slog.w(TAG, "Attempt to delete null packageName.");
12350            return false;
12351        }
12352        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
12353        PackageSetting ps;
12354        boolean dataOnly = false;
12355        int removeUser = -1;
12356        int appId = -1;
12357        synchronized (mPackages) {
12358            ps = mSettings.mPackages.get(packageName);
12359            if (ps == null) {
12360                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12361                return false;
12362            }
12363            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
12364                    && user.getIdentifier() != UserHandle.USER_ALL) {
12365                // The caller is asking that the package only be deleted for a single
12366                // user.  To do this, we just mark its uninstalled state and delete
12367                // its data.  If this is a system app, we only allow this to happen if
12368                // they have set the special DELETE_SYSTEM_APP which requests different
12369                // semantics than normal for uninstalling system apps.
12370                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
12371                ps.setUserState(user.getIdentifier(),
12372                        COMPONENT_ENABLED_STATE_DEFAULT,
12373                        false, //installed
12374                        true,  //stopped
12375                        true,  //notLaunched
12376                        false, //hidden
12377                        null, null, null,
12378                        false, // blockUninstall
12379                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
12380                if (!isSystemApp(ps)) {
12381                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
12382                        // Other user still have this package installed, so all
12383                        // we need to do is clear this user's data and save that
12384                        // it is uninstalled.
12385                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
12386                        removeUser = user.getIdentifier();
12387                        appId = ps.appId;
12388                        scheduleWritePackageRestrictionsLocked(removeUser);
12389                    } else {
12390                        // We need to set it back to 'installed' so the uninstall
12391                        // broadcasts will be sent correctly.
12392                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
12393                        ps.setInstalled(true, user.getIdentifier());
12394                    }
12395                } else {
12396                    // This is a system app, so we assume that the
12397                    // other users still have this package installed, so all
12398                    // we need to do is clear this user's data and save that
12399                    // it is uninstalled.
12400                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
12401                    removeUser = user.getIdentifier();
12402                    appId = ps.appId;
12403                    scheduleWritePackageRestrictionsLocked(removeUser);
12404                }
12405            }
12406        }
12407
12408        if (removeUser >= 0) {
12409            // From above, we determined that we are deleting this only
12410            // for a single user.  Continue the work here.
12411            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
12412            if (outInfo != null) {
12413                outInfo.removedPackage = packageName;
12414                outInfo.removedAppId = appId;
12415                outInfo.removedUsers = new int[] {removeUser};
12416            }
12417            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
12418            removeKeystoreDataIfNeeded(removeUser, appId);
12419            schedulePackageCleaning(packageName, removeUser, false);
12420            synchronized (mPackages) {
12421                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
12422                    scheduleWritePackageRestrictionsLocked(removeUser);
12423                }
12424            }
12425            return true;
12426        }
12427
12428        if (dataOnly) {
12429            // Delete application data first
12430            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
12431            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
12432            return true;
12433        }
12434
12435        boolean ret = false;
12436        if (isSystemApp(ps)) {
12437            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
12438            // When an updated system application is deleted we delete the existing resources as well and
12439            // fall back to existing code in system partition
12440            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
12441                    flags, outInfo, writeSettings);
12442        } else {
12443            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
12444            // Kill application pre-emptively especially for apps on sd.
12445            killApplication(packageName, ps.appId, "uninstall pkg");
12446            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
12447                    allUserHandles, perUserInstalled,
12448                    outInfo, writeSettings);
12449        }
12450
12451        return ret;
12452    }
12453
12454    private final class ClearStorageConnection implements ServiceConnection {
12455        IMediaContainerService mContainerService;
12456
12457        @Override
12458        public void onServiceConnected(ComponentName name, IBinder service) {
12459            synchronized (this) {
12460                mContainerService = IMediaContainerService.Stub.asInterface(service);
12461                notifyAll();
12462            }
12463        }
12464
12465        @Override
12466        public void onServiceDisconnected(ComponentName name) {
12467        }
12468    }
12469
12470    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
12471        final boolean mounted;
12472        if (Environment.isExternalStorageEmulated()) {
12473            mounted = true;
12474        } else {
12475            final String status = Environment.getExternalStorageState();
12476
12477            mounted = status.equals(Environment.MEDIA_MOUNTED)
12478                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
12479        }
12480
12481        if (!mounted) {
12482            return;
12483        }
12484
12485        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
12486        int[] users;
12487        if (userId == UserHandle.USER_ALL) {
12488            users = sUserManager.getUserIds();
12489        } else {
12490            users = new int[] { userId };
12491        }
12492        final ClearStorageConnection conn = new ClearStorageConnection();
12493        if (mContext.bindServiceAsUser(
12494                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
12495            try {
12496                for (int curUser : users) {
12497                    long timeout = SystemClock.uptimeMillis() + 5000;
12498                    synchronized (conn) {
12499                        long now = SystemClock.uptimeMillis();
12500                        while (conn.mContainerService == null && now < timeout) {
12501                            try {
12502                                conn.wait(timeout - now);
12503                            } catch (InterruptedException e) {
12504                            }
12505                        }
12506                    }
12507                    if (conn.mContainerService == null) {
12508                        return;
12509                    }
12510
12511                    final UserEnvironment userEnv = new UserEnvironment(curUser);
12512                    clearDirectory(conn.mContainerService,
12513                            userEnv.buildExternalStorageAppCacheDirs(packageName));
12514                    if (allData) {
12515                        clearDirectory(conn.mContainerService,
12516                                userEnv.buildExternalStorageAppDataDirs(packageName));
12517                        clearDirectory(conn.mContainerService,
12518                                userEnv.buildExternalStorageAppMediaDirs(packageName));
12519                    }
12520                }
12521            } finally {
12522                mContext.unbindService(conn);
12523            }
12524        }
12525    }
12526
12527    @Override
12528    public void clearApplicationUserData(final String packageName,
12529            final IPackageDataObserver observer, final int userId) {
12530        mContext.enforceCallingOrSelfPermission(
12531                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
12532        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
12533        // Queue up an async operation since the package deletion may take a little while.
12534        mHandler.post(new Runnable() {
12535            public void run() {
12536                mHandler.removeCallbacks(this);
12537                final boolean succeeded;
12538                synchronized (mInstallLock) {
12539                    succeeded = clearApplicationUserDataLI(packageName, userId);
12540                }
12541                clearExternalStorageDataSync(packageName, userId, true);
12542                if (succeeded) {
12543                    // invoke DeviceStorageMonitor's update method to clear any notifications
12544                    DeviceStorageMonitorInternal
12545                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
12546                    if (dsm != null) {
12547                        dsm.checkMemory();
12548                    }
12549                }
12550                if(observer != null) {
12551                    try {
12552                        observer.onRemoveCompleted(packageName, succeeded);
12553                    } catch (RemoteException e) {
12554                        Log.i(TAG, "Observer no longer exists.");
12555                    }
12556                } //end if observer
12557            } //end run
12558        });
12559    }
12560
12561    private boolean clearApplicationUserDataLI(String packageName, int userId) {
12562        if (packageName == null) {
12563            Slog.w(TAG, "Attempt to delete null packageName.");
12564            return false;
12565        }
12566
12567        // Try finding details about the requested package
12568        PackageParser.Package pkg;
12569        synchronized (mPackages) {
12570            pkg = mPackages.get(packageName);
12571            if (pkg == null) {
12572                final PackageSetting ps = mSettings.mPackages.get(packageName);
12573                if (ps != null) {
12574                    pkg = ps.pkg;
12575                }
12576            }
12577        }
12578
12579        if (pkg == null) {
12580            Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12581        }
12582
12583        // Always delete data directories for package, even if we found no other
12584        // record of app. This helps users recover from UID mismatches without
12585        // resorting to a full data wipe.
12586        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
12587        if (retCode < 0) {
12588            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
12589            return false;
12590        }
12591
12592        if (pkg == null) {
12593            return false;
12594        }
12595
12596        if (pkg != null && pkg.applicationInfo != null) {
12597            final int appId = pkg.applicationInfo.uid;
12598            removeKeystoreDataIfNeeded(userId, appId);
12599        }
12600
12601        // Create a native library symlink only if we have native libraries
12602        // and if the native libraries are 32 bit libraries. We do not provide
12603        // this symlink for 64 bit libraries.
12604        if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null &&
12605                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
12606            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
12607            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
12608                    nativeLibPath, userId) < 0) {
12609                Slog.w(TAG, "Failed linking native library dir");
12610                return false;
12611            }
12612        }
12613
12614        return true;
12615    }
12616
12617    /**
12618     * Remove entries from the keystore daemon. Will only remove it if the
12619     * {@code appId} is valid.
12620     */
12621    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
12622        if (appId < 0) {
12623            return;
12624        }
12625
12626        final KeyStore keyStore = KeyStore.getInstance();
12627        if (keyStore != null) {
12628            if (userId == UserHandle.USER_ALL) {
12629                for (final int individual : sUserManager.getUserIds()) {
12630                    keyStore.clearUid(UserHandle.getUid(individual, appId));
12631                }
12632            } else {
12633                keyStore.clearUid(UserHandle.getUid(userId, appId));
12634            }
12635        } else {
12636            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
12637        }
12638    }
12639
12640    @Override
12641    public void deleteApplicationCacheFiles(final String packageName,
12642            final IPackageDataObserver observer) {
12643        mContext.enforceCallingOrSelfPermission(
12644                android.Manifest.permission.DELETE_CACHE_FILES, null);
12645        // Queue up an async operation since the package deletion may take a little while.
12646        final int userId = UserHandle.getCallingUserId();
12647        mHandler.post(new Runnable() {
12648            public void run() {
12649                mHandler.removeCallbacks(this);
12650                final boolean succeded;
12651                synchronized (mInstallLock) {
12652                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
12653                }
12654                clearExternalStorageDataSync(packageName, userId, false);
12655                if (observer != null) {
12656                    try {
12657                        observer.onRemoveCompleted(packageName, succeded);
12658                    } catch (RemoteException e) {
12659                        Log.i(TAG, "Observer no longer exists.");
12660                    }
12661                } //end if observer
12662            } //end run
12663        });
12664    }
12665
12666    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
12667        if (packageName == null) {
12668            Slog.w(TAG, "Attempt to delete null packageName.");
12669            return false;
12670        }
12671        PackageParser.Package p;
12672        synchronized (mPackages) {
12673            p = mPackages.get(packageName);
12674        }
12675        if (p == null) {
12676            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12677            return false;
12678        }
12679        final ApplicationInfo applicationInfo = p.applicationInfo;
12680        if (applicationInfo == null) {
12681            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12682            return false;
12683        }
12684        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
12685        if (retCode < 0) {
12686            Slog.w(TAG, "Couldn't remove cache files for package: "
12687                       + packageName + " u" + userId);
12688            return false;
12689        }
12690        return true;
12691    }
12692
12693    @Override
12694    public void getPackageSizeInfo(final String packageName, int userHandle,
12695            final IPackageStatsObserver observer) {
12696        mContext.enforceCallingOrSelfPermission(
12697                android.Manifest.permission.GET_PACKAGE_SIZE, null);
12698        if (packageName == null) {
12699            throw new IllegalArgumentException("Attempt to get size of null packageName");
12700        }
12701
12702        PackageStats stats = new PackageStats(packageName, userHandle);
12703
12704        /*
12705         * Queue up an async operation since the package measurement may take a
12706         * little while.
12707         */
12708        Message msg = mHandler.obtainMessage(INIT_COPY);
12709        msg.obj = new MeasureParams(stats, observer);
12710        mHandler.sendMessage(msg);
12711    }
12712
12713    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
12714            PackageStats pStats) {
12715        if (packageName == null) {
12716            Slog.w(TAG, "Attempt to get size of null packageName.");
12717            return false;
12718        }
12719        PackageParser.Package p;
12720        boolean dataOnly = false;
12721        String libDirRoot = null;
12722        String asecPath = null;
12723        PackageSetting ps = null;
12724        synchronized (mPackages) {
12725            p = mPackages.get(packageName);
12726            ps = mSettings.mPackages.get(packageName);
12727            if(p == null) {
12728                dataOnly = true;
12729                if((ps == null) || (ps.pkg == null)) {
12730                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12731                    return false;
12732                }
12733                p = ps.pkg;
12734            }
12735            if (ps != null) {
12736                libDirRoot = ps.legacyNativeLibraryPathString;
12737            }
12738            if (p != null && (isExternal(p) || p.isForwardLocked())) {
12739                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
12740                if (secureContainerId != null) {
12741                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
12742                }
12743            }
12744        }
12745        String publicSrcDir = null;
12746        if(!dataOnly) {
12747            final ApplicationInfo applicationInfo = p.applicationInfo;
12748            if (applicationInfo == null) {
12749                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12750                return false;
12751            }
12752            if (p.isForwardLocked()) {
12753                publicSrcDir = applicationInfo.getBaseResourcePath();
12754            }
12755        }
12756        // TODO: extend to measure size of split APKs
12757        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
12758        // not just the first level.
12759        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
12760        // just the primary.
12761        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
12762        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
12763                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
12764        if (res < 0) {
12765            return false;
12766        }
12767
12768        // Fix-up for forward-locked applications in ASEC containers.
12769        if (!isExternal(p)) {
12770            pStats.codeSize += pStats.externalCodeSize;
12771            pStats.externalCodeSize = 0L;
12772        }
12773
12774        return true;
12775    }
12776
12777
12778    @Override
12779    public void addPackageToPreferred(String packageName) {
12780        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
12781    }
12782
12783    @Override
12784    public void removePackageFromPreferred(String packageName) {
12785        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
12786    }
12787
12788    @Override
12789    public List<PackageInfo> getPreferredPackages(int flags) {
12790        return new ArrayList<PackageInfo>();
12791    }
12792
12793    private int getUidTargetSdkVersionLockedLPr(int uid) {
12794        Object obj = mSettings.getUserIdLPr(uid);
12795        if (obj instanceof SharedUserSetting) {
12796            final SharedUserSetting sus = (SharedUserSetting) obj;
12797            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
12798            final Iterator<PackageSetting> it = sus.packages.iterator();
12799            while (it.hasNext()) {
12800                final PackageSetting ps = it.next();
12801                if (ps.pkg != null) {
12802                    int v = ps.pkg.applicationInfo.targetSdkVersion;
12803                    if (v < vers) vers = v;
12804                }
12805            }
12806            return vers;
12807        } else if (obj instanceof PackageSetting) {
12808            final PackageSetting ps = (PackageSetting) obj;
12809            if (ps.pkg != null) {
12810                return ps.pkg.applicationInfo.targetSdkVersion;
12811            }
12812        }
12813        return Build.VERSION_CODES.CUR_DEVELOPMENT;
12814    }
12815
12816    @Override
12817    public void addPreferredActivity(IntentFilter filter, int match,
12818            ComponentName[] set, ComponentName activity, int userId) {
12819        addPreferredActivityInternal(filter, match, set, activity, true, userId,
12820                "Adding preferred");
12821    }
12822
12823    private void addPreferredActivityInternal(IntentFilter filter, int match,
12824            ComponentName[] set, ComponentName activity, boolean always, int userId,
12825            String opname) {
12826        // writer
12827        int callingUid = Binder.getCallingUid();
12828        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
12829        if (filter.countActions() == 0) {
12830            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
12831            return;
12832        }
12833        synchronized (mPackages) {
12834            if (mContext.checkCallingOrSelfPermission(
12835                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12836                    != PackageManager.PERMISSION_GRANTED) {
12837                if (getUidTargetSdkVersionLockedLPr(callingUid)
12838                        < Build.VERSION_CODES.FROYO) {
12839                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
12840                            + callingUid);
12841                    return;
12842                }
12843                mContext.enforceCallingOrSelfPermission(
12844                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12845            }
12846
12847            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
12848            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
12849                    + userId + ":");
12850            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12851            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
12852            scheduleWritePackageRestrictionsLocked(userId);
12853        }
12854    }
12855
12856    @Override
12857    public void replacePreferredActivity(IntentFilter filter, int match,
12858            ComponentName[] set, ComponentName activity, int userId) {
12859        if (filter.countActions() != 1) {
12860            throw new IllegalArgumentException(
12861                    "replacePreferredActivity expects filter to have only 1 action.");
12862        }
12863        if (filter.countDataAuthorities() != 0
12864                || filter.countDataPaths() != 0
12865                || filter.countDataSchemes() > 1
12866                || filter.countDataTypes() != 0) {
12867            throw new IllegalArgumentException(
12868                    "replacePreferredActivity expects filter to have no data authorities, " +
12869                    "paths, or types; and at most one scheme.");
12870        }
12871
12872        final int callingUid = Binder.getCallingUid();
12873        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
12874        synchronized (mPackages) {
12875            if (mContext.checkCallingOrSelfPermission(
12876                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12877                    != PackageManager.PERMISSION_GRANTED) {
12878                if (getUidTargetSdkVersionLockedLPr(callingUid)
12879                        < Build.VERSION_CODES.FROYO) {
12880                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
12881                            + Binder.getCallingUid());
12882                    return;
12883                }
12884                mContext.enforceCallingOrSelfPermission(
12885                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12886            }
12887
12888            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
12889            if (pir != null) {
12890                // Get all of the existing entries that exactly match this filter.
12891                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
12892                if (existing != null && existing.size() == 1) {
12893                    PreferredActivity cur = existing.get(0);
12894                    if (DEBUG_PREFERRED) {
12895                        Slog.i(TAG, "Checking replace of preferred:");
12896                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12897                        if (!cur.mPref.mAlways) {
12898                            Slog.i(TAG, "  -- CUR; not mAlways!");
12899                        } else {
12900                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
12901                            Slog.i(TAG, "  -- CUR: mSet="
12902                                    + Arrays.toString(cur.mPref.mSetComponents));
12903                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
12904                            Slog.i(TAG, "  -- NEW: mMatch="
12905                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
12906                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
12907                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
12908                        }
12909                    }
12910                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
12911                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
12912                            && cur.mPref.sameSet(set)) {
12913                        // Setting the preferred activity to what it happens to be already
12914                        if (DEBUG_PREFERRED) {
12915                            Slog.i(TAG, "Replacing with same preferred activity "
12916                                    + cur.mPref.mShortComponent + " for user "
12917                                    + userId + ":");
12918                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12919                        }
12920                        return;
12921                    }
12922                }
12923
12924                if (existing != null) {
12925                    if (DEBUG_PREFERRED) {
12926                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
12927                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12928                    }
12929                    for (int i = 0; i < existing.size(); i++) {
12930                        PreferredActivity pa = existing.get(i);
12931                        if (DEBUG_PREFERRED) {
12932                            Slog.i(TAG, "Removing existing preferred activity "
12933                                    + pa.mPref.mComponent + ":");
12934                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
12935                        }
12936                        pir.removeFilter(pa);
12937                    }
12938                }
12939            }
12940            addPreferredActivityInternal(filter, match, set, activity, true, userId,
12941                    "Replacing preferred");
12942        }
12943    }
12944
12945    @Override
12946    public void clearPackagePreferredActivities(String packageName) {
12947        final int uid = Binder.getCallingUid();
12948        // writer
12949        synchronized (mPackages) {
12950            PackageParser.Package pkg = mPackages.get(packageName);
12951            if (pkg == null || pkg.applicationInfo.uid != uid) {
12952                if (mContext.checkCallingOrSelfPermission(
12953                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12954                        != PackageManager.PERMISSION_GRANTED) {
12955                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
12956                            < Build.VERSION_CODES.FROYO) {
12957                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
12958                                + Binder.getCallingUid());
12959                        return;
12960                    }
12961                    mContext.enforceCallingOrSelfPermission(
12962                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12963                }
12964            }
12965
12966            int user = UserHandle.getCallingUserId();
12967            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
12968                scheduleWritePackageRestrictionsLocked(user);
12969            }
12970        }
12971    }
12972
12973    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
12974    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
12975        ArrayList<PreferredActivity> removed = null;
12976        boolean changed = false;
12977        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12978            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
12979            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12980            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
12981                continue;
12982            }
12983            Iterator<PreferredActivity> it = pir.filterIterator();
12984            while (it.hasNext()) {
12985                PreferredActivity pa = it.next();
12986                // Mark entry for removal only if it matches the package name
12987                // and the entry is of type "always".
12988                if (packageName == null ||
12989                        (pa.mPref.mComponent.getPackageName().equals(packageName)
12990                                && pa.mPref.mAlways)) {
12991                    if (removed == null) {
12992                        removed = new ArrayList<PreferredActivity>();
12993                    }
12994                    removed.add(pa);
12995                }
12996            }
12997            if (removed != null) {
12998                for (int j=0; j<removed.size(); j++) {
12999                    PreferredActivity pa = removed.get(j);
13000                    pir.removeFilter(pa);
13001                }
13002                changed = true;
13003            }
13004        }
13005        return changed;
13006    }
13007
13008    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13009    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13010        if (userId == UserHandle.USER_ALL) {
13011            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13012                    sUserManager.getUserIds())) {
13013                for (int oneUserId : sUserManager.getUserIds()) {
13014                    scheduleWritePackageRestrictionsLocked(oneUserId);
13015                }
13016            }
13017        } else {
13018            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13019                scheduleWritePackageRestrictionsLocked(userId);
13020            }
13021        }
13022    }
13023
13024
13025    void clearDefaultBrowserIfNeeded(String packageName) {
13026        for (int oneUserId : sUserManager.getUserIds()) {
13027            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13028            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13029            if (packageName.equals(defaultBrowserPackageName)) {
13030                setDefaultBrowserPackageName(null, oneUserId);
13031            }
13032        }
13033    }
13034
13035    @Override
13036    public void resetPreferredActivities(int userId) {
13037        /* TODO: Actually use userId. Why is it being passed in? */
13038        mContext.enforceCallingOrSelfPermission(
13039                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13040        // writer
13041        synchronized (mPackages) {
13042            int user = UserHandle.getCallingUserId();
13043            clearPackagePreferredActivitiesLPw(null, user);
13044            mSettings.readDefaultPreferredAppsLPw(this, user);
13045            scheduleWritePackageRestrictionsLocked(user);
13046        }
13047    }
13048
13049    @Override
13050    public int getPreferredActivities(List<IntentFilter> outFilters,
13051            List<ComponentName> outActivities, String packageName) {
13052
13053        int num = 0;
13054        final int userId = UserHandle.getCallingUserId();
13055        // reader
13056        synchronized (mPackages) {
13057            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13058            if (pir != null) {
13059                final Iterator<PreferredActivity> it = pir.filterIterator();
13060                while (it.hasNext()) {
13061                    final PreferredActivity pa = it.next();
13062                    if (packageName == null
13063                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13064                                    && pa.mPref.mAlways)) {
13065                        if (outFilters != null) {
13066                            outFilters.add(new IntentFilter(pa));
13067                        }
13068                        if (outActivities != null) {
13069                            outActivities.add(pa.mPref.mComponent);
13070                        }
13071                    }
13072                }
13073            }
13074        }
13075
13076        return num;
13077    }
13078
13079    @Override
13080    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13081            int userId) {
13082        int callingUid = Binder.getCallingUid();
13083        if (callingUid != Process.SYSTEM_UID) {
13084            throw new SecurityException(
13085                    "addPersistentPreferredActivity can only be run by the system");
13086        }
13087        if (filter.countActions() == 0) {
13088            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13089            return;
13090        }
13091        synchronized (mPackages) {
13092            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13093                    " :");
13094            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13095            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13096                    new PersistentPreferredActivity(filter, activity));
13097            scheduleWritePackageRestrictionsLocked(userId);
13098        }
13099    }
13100
13101    @Override
13102    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13103        int callingUid = Binder.getCallingUid();
13104        if (callingUid != Process.SYSTEM_UID) {
13105            throw new SecurityException(
13106                    "clearPackagePersistentPreferredActivities can only be run by the system");
13107        }
13108        ArrayList<PersistentPreferredActivity> removed = null;
13109        boolean changed = false;
13110        synchronized (mPackages) {
13111            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13112                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13113                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13114                        .valueAt(i);
13115                if (userId != thisUserId) {
13116                    continue;
13117                }
13118                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13119                while (it.hasNext()) {
13120                    PersistentPreferredActivity ppa = it.next();
13121                    // Mark entry for removal only if it matches the package name.
13122                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13123                        if (removed == null) {
13124                            removed = new ArrayList<PersistentPreferredActivity>();
13125                        }
13126                        removed.add(ppa);
13127                    }
13128                }
13129                if (removed != null) {
13130                    for (int j=0; j<removed.size(); j++) {
13131                        PersistentPreferredActivity ppa = removed.get(j);
13132                        ppir.removeFilter(ppa);
13133                    }
13134                    changed = true;
13135                }
13136            }
13137
13138            if (changed) {
13139                scheduleWritePackageRestrictionsLocked(userId);
13140            }
13141        }
13142    }
13143
13144    /**
13145     * Non-Binder method, support for the backup/restore mechanism: write the
13146     * full set of preferred activities in its canonical XML format.  Returns true
13147     * on success; false otherwise.
13148     */
13149    @Override
13150    public byte[] getPreferredActivityBackup(int userId) {
13151        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13152            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13153        }
13154
13155        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13156        try {
13157            final XmlSerializer serializer = new FastXmlSerializer();
13158            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13159            serializer.startDocument(null, true);
13160            serializer.startTag(null, TAG_PREFERRED_BACKUP);
13161
13162            synchronized (mPackages) {
13163                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13164            }
13165
13166            serializer.endTag(null, TAG_PREFERRED_BACKUP);
13167            serializer.endDocument();
13168            serializer.flush();
13169        } catch (Exception e) {
13170            if (DEBUG_BACKUP) {
13171                Slog.e(TAG, "Unable to write preferred activities for backup", e);
13172            }
13173            return null;
13174        }
13175
13176        return dataStream.toByteArray();
13177    }
13178
13179    @Override
13180    public void restorePreferredActivities(byte[] backup, int userId) {
13181        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13182            throw new SecurityException("Only the system may call restorePreferredActivities()");
13183        }
13184
13185        try {
13186            final XmlPullParser parser = Xml.newPullParser();
13187            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13188
13189            int type;
13190            while ((type = parser.next()) != XmlPullParser.START_TAG
13191                    && type != XmlPullParser.END_DOCUMENT) {
13192            }
13193            if (type != XmlPullParser.START_TAG) {
13194                // oops didn't find a start tag?!
13195                if (DEBUG_BACKUP) {
13196                    Slog.e(TAG, "Didn't find start tag during restore");
13197                }
13198                return;
13199            }
13200
13201            // this is supposed to be TAG_PREFERRED_BACKUP
13202            if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) {
13203                if (DEBUG_BACKUP) {
13204                    Slog.e(TAG, "Found unexpected tag " + parser.getName());
13205                }
13206                return;
13207            }
13208
13209            // skip interfering stuff, then we're aligned with the backing implementation
13210            while ((type = parser.next()) == XmlPullParser.TEXT) { }
13211            synchronized (mPackages) {
13212                mSettings.readPreferredActivitiesLPw(parser, userId);
13213            }
13214        } catch (Exception e) {
13215            if (DEBUG_BACKUP) {
13216                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13217            }
13218        }
13219    }
13220
13221    @Override
13222    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
13223            int sourceUserId, int targetUserId, int flags) {
13224        mContext.enforceCallingOrSelfPermission(
13225                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13226        int callingUid = Binder.getCallingUid();
13227        enforceOwnerRights(ownerPackage, callingUid);
13228        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13229        if (intentFilter.countActions() == 0) {
13230            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
13231            return;
13232        }
13233        synchronized (mPackages) {
13234            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
13235                    ownerPackage, targetUserId, flags);
13236            CrossProfileIntentResolver resolver =
13237                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13238            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
13239            // We have all those whose filter is equal. Now checking if the rest is equal as well.
13240            if (existing != null) {
13241                int size = existing.size();
13242                for (int i = 0; i < size; i++) {
13243                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
13244                        return;
13245                    }
13246                }
13247            }
13248            resolver.addFilter(newFilter);
13249            scheduleWritePackageRestrictionsLocked(sourceUserId);
13250        }
13251    }
13252
13253    @Override
13254    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
13255        mContext.enforceCallingOrSelfPermission(
13256                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13257        int callingUid = Binder.getCallingUid();
13258        enforceOwnerRights(ownerPackage, callingUid);
13259        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13260        synchronized (mPackages) {
13261            CrossProfileIntentResolver resolver =
13262                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13263            ArraySet<CrossProfileIntentFilter> set =
13264                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
13265            for (CrossProfileIntentFilter filter : set) {
13266                if (filter.getOwnerPackage().equals(ownerPackage)) {
13267                    resolver.removeFilter(filter);
13268                }
13269            }
13270            scheduleWritePackageRestrictionsLocked(sourceUserId);
13271        }
13272    }
13273
13274    // Enforcing that callingUid is owning pkg on userId
13275    private void enforceOwnerRights(String pkg, int callingUid) {
13276        // The system owns everything.
13277        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
13278            return;
13279        }
13280        int callingUserId = UserHandle.getUserId(callingUid);
13281        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
13282        if (pi == null) {
13283            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
13284                    + callingUserId);
13285        }
13286        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
13287            throw new SecurityException("Calling uid " + callingUid
13288                    + " does not own package " + pkg);
13289        }
13290    }
13291
13292    @Override
13293    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
13294        Intent intent = new Intent(Intent.ACTION_MAIN);
13295        intent.addCategory(Intent.CATEGORY_HOME);
13296
13297        final int callingUserId = UserHandle.getCallingUserId();
13298        List<ResolveInfo> list = queryIntentActivities(intent, null,
13299                PackageManager.GET_META_DATA, callingUserId);
13300        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
13301                true, false, false, callingUserId);
13302
13303        allHomeCandidates.clear();
13304        if (list != null) {
13305            for (ResolveInfo ri : list) {
13306                allHomeCandidates.add(ri);
13307            }
13308        }
13309        return (preferred == null || preferred.activityInfo == null)
13310                ? null
13311                : new ComponentName(preferred.activityInfo.packageName,
13312                        preferred.activityInfo.name);
13313    }
13314
13315    @Override
13316    public void setApplicationEnabledSetting(String appPackageName,
13317            int newState, int flags, int userId, String callingPackage) {
13318        if (!sUserManager.exists(userId)) return;
13319        if (callingPackage == null) {
13320            callingPackage = Integer.toString(Binder.getCallingUid());
13321        }
13322        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
13323    }
13324
13325    @Override
13326    public void setComponentEnabledSetting(ComponentName componentName,
13327            int newState, int flags, int userId) {
13328        if (!sUserManager.exists(userId)) return;
13329        setEnabledSetting(componentName.getPackageName(),
13330                componentName.getClassName(), newState, flags, userId, null);
13331    }
13332
13333    private void setEnabledSetting(final String packageName, String className, int newState,
13334            final int flags, int userId, String callingPackage) {
13335        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
13336              || newState == COMPONENT_ENABLED_STATE_ENABLED
13337              || newState == COMPONENT_ENABLED_STATE_DISABLED
13338              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
13339              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
13340            throw new IllegalArgumentException("Invalid new component state: "
13341                    + newState);
13342        }
13343        PackageSetting pkgSetting;
13344        final int uid = Binder.getCallingUid();
13345        final int permission = mContext.checkCallingOrSelfPermission(
13346                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13347        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
13348        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13349        boolean sendNow = false;
13350        boolean isApp = (className == null);
13351        String componentName = isApp ? packageName : className;
13352        int packageUid = -1;
13353        ArrayList<String> components;
13354
13355        // writer
13356        synchronized (mPackages) {
13357            pkgSetting = mSettings.mPackages.get(packageName);
13358            if (pkgSetting == null) {
13359                if (className == null) {
13360                    throw new IllegalArgumentException(
13361                            "Unknown package: " + packageName);
13362                }
13363                throw new IllegalArgumentException(
13364                        "Unknown component: " + packageName
13365                        + "/" + className);
13366            }
13367            // Allow root and verify that userId is not being specified by a different user
13368            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
13369                throw new SecurityException(
13370                        "Permission Denial: attempt to change component state from pid="
13371                        + Binder.getCallingPid()
13372                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
13373            }
13374            if (className == null) {
13375                // We're dealing with an application/package level state change
13376                if (pkgSetting.getEnabled(userId) == newState) {
13377                    // Nothing to do
13378                    return;
13379                }
13380                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
13381                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
13382                    // Don't care about who enables an app.
13383                    callingPackage = null;
13384                }
13385                pkgSetting.setEnabled(newState, userId, callingPackage);
13386                // pkgSetting.pkg.mSetEnabled = newState;
13387            } else {
13388                // We're dealing with a component level state change
13389                // First, verify that this is a valid class name.
13390                PackageParser.Package pkg = pkgSetting.pkg;
13391                if (pkg == null || !pkg.hasComponentClassName(className)) {
13392                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
13393                        throw new IllegalArgumentException("Component class " + className
13394                                + " does not exist in " + packageName);
13395                    } else {
13396                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
13397                                + className + " does not exist in " + packageName);
13398                    }
13399                }
13400                switch (newState) {
13401                case COMPONENT_ENABLED_STATE_ENABLED:
13402                    if (!pkgSetting.enableComponentLPw(className, userId)) {
13403                        return;
13404                    }
13405                    break;
13406                case COMPONENT_ENABLED_STATE_DISABLED:
13407                    if (!pkgSetting.disableComponentLPw(className, userId)) {
13408                        return;
13409                    }
13410                    break;
13411                case COMPONENT_ENABLED_STATE_DEFAULT:
13412                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
13413                        return;
13414                    }
13415                    break;
13416                default:
13417                    Slog.e(TAG, "Invalid new component state: " + newState);
13418                    return;
13419                }
13420            }
13421            scheduleWritePackageRestrictionsLocked(userId);
13422            components = mPendingBroadcasts.get(userId, packageName);
13423            final boolean newPackage = components == null;
13424            if (newPackage) {
13425                components = new ArrayList<String>();
13426            }
13427            if (!components.contains(componentName)) {
13428                components.add(componentName);
13429            }
13430            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
13431                sendNow = true;
13432                // Purge entry from pending broadcast list if another one exists already
13433                // since we are sending one right away.
13434                mPendingBroadcasts.remove(userId, packageName);
13435            } else {
13436                if (newPackage) {
13437                    mPendingBroadcasts.put(userId, packageName, components);
13438                }
13439                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
13440                    // Schedule a message
13441                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
13442                }
13443            }
13444        }
13445
13446        long callingId = Binder.clearCallingIdentity();
13447        try {
13448            if (sendNow) {
13449                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
13450                sendPackageChangedBroadcast(packageName,
13451                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
13452            }
13453        } finally {
13454            Binder.restoreCallingIdentity(callingId);
13455        }
13456    }
13457
13458    private void sendPackageChangedBroadcast(String packageName,
13459            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
13460        if (DEBUG_INSTALL)
13461            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
13462                    + componentNames);
13463        Bundle extras = new Bundle(4);
13464        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
13465        String nameList[] = new String[componentNames.size()];
13466        componentNames.toArray(nameList);
13467        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
13468        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
13469        extras.putInt(Intent.EXTRA_UID, packageUid);
13470        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
13471                new int[] {UserHandle.getUserId(packageUid)});
13472    }
13473
13474    @Override
13475    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
13476        if (!sUserManager.exists(userId)) return;
13477        final int uid = Binder.getCallingUid();
13478        final int permission = mContext.checkCallingOrSelfPermission(
13479                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13480        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13481        enforceCrossUserPermission(uid, userId, true, true, "stop package");
13482        // writer
13483        synchronized (mPackages) {
13484            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
13485                    allowedByPermission, uid, userId)) {
13486                scheduleWritePackageRestrictionsLocked(userId);
13487            }
13488        }
13489    }
13490
13491    @Override
13492    public String getInstallerPackageName(String packageName) {
13493        // reader
13494        synchronized (mPackages) {
13495            return mSettings.getInstallerPackageNameLPr(packageName);
13496        }
13497    }
13498
13499    @Override
13500    public int getApplicationEnabledSetting(String packageName, int userId) {
13501        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13502        int uid = Binder.getCallingUid();
13503        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
13504        // reader
13505        synchronized (mPackages) {
13506            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
13507        }
13508    }
13509
13510    @Override
13511    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
13512        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13513        int uid = Binder.getCallingUid();
13514        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
13515        // reader
13516        synchronized (mPackages) {
13517            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
13518        }
13519    }
13520
13521    @Override
13522    public void enterSafeMode() {
13523        enforceSystemOrRoot("Only the system can request entering safe mode");
13524
13525        if (!mSystemReady) {
13526            mSafeMode = true;
13527        }
13528    }
13529
13530    @Override
13531    public void systemReady() {
13532        mSystemReady = true;
13533
13534        // Read the compatibilty setting when the system is ready.
13535        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
13536                mContext.getContentResolver(),
13537                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
13538        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
13539        if (DEBUG_SETTINGS) {
13540            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
13541        }
13542
13543        synchronized (mPackages) {
13544            // Verify that all of the preferred activity components actually
13545            // exist.  It is possible for applications to be updated and at
13546            // that point remove a previously declared activity component that
13547            // had been set as a preferred activity.  We try to clean this up
13548            // the next time we encounter that preferred activity, but it is
13549            // possible for the user flow to never be able to return to that
13550            // situation so here we do a sanity check to make sure we haven't
13551            // left any junk around.
13552            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
13553            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13554                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13555                removed.clear();
13556                for (PreferredActivity pa : pir.filterSet()) {
13557                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
13558                        removed.add(pa);
13559                    }
13560                }
13561                if (removed.size() > 0) {
13562                    for (int r=0; r<removed.size(); r++) {
13563                        PreferredActivity pa = removed.get(r);
13564                        Slog.w(TAG, "Removing dangling preferred activity: "
13565                                + pa.mPref.mComponent);
13566                        pir.removeFilter(pa);
13567                    }
13568                    mSettings.writePackageRestrictionsLPr(
13569                            mSettings.mPreferredActivities.keyAt(i));
13570                }
13571            }
13572        }
13573        sUserManager.systemReady();
13574
13575        // Kick off any messages waiting for system ready
13576        if (mPostSystemReadyMessages != null) {
13577            for (Message msg : mPostSystemReadyMessages) {
13578                msg.sendToTarget();
13579            }
13580            mPostSystemReadyMessages = null;
13581        }
13582
13583        // Watch for external volumes that come and go over time
13584        final StorageManager storage = mContext.getSystemService(StorageManager.class);
13585        storage.registerListener(mStorageListener);
13586
13587        mInstallerService.systemReady();
13588        mPackageDexOptimizer.systemReady();
13589    }
13590
13591    @Override
13592    public boolean isSafeMode() {
13593        return mSafeMode;
13594    }
13595
13596    @Override
13597    public boolean hasSystemUidErrors() {
13598        return mHasSystemUidErrors;
13599    }
13600
13601    static String arrayToString(int[] array) {
13602        StringBuffer buf = new StringBuffer(128);
13603        buf.append('[');
13604        if (array != null) {
13605            for (int i=0; i<array.length; i++) {
13606                if (i > 0) buf.append(", ");
13607                buf.append(array[i]);
13608            }
13609        }
13610        buf.append(']');
13611        return buf.toString();
13612    }
13613
13614    static class DumpState {
13615        public static final int DUMP_LIBS = 1 << 0;
13616        public static final int DUMP_FEATURES = 1 << 1;
13617        public static final int DUMP_RESOLVERS = 1 << 2;
13618        public static final int DUMP_PERMISSIONS = 1 << 3;
13619        public static final int DUMP_PACKAGES = 1 << 4;
13620        public static final int DUMP_SHARED_USERS = 1 << 5;
13621        public static final int DUMP_MESSAGES = 1 << 6;
13622        public static final int DUMP_PROVIDERS = 1 << 7;
13623        public static final int DUMP_VERIFIERS = 1 << 8;
13624        public static final int DUMP_PREFERRED = 1 << 9;
13625        public static final int DUMP_PREFERRED_XML = 1 << 10;
13626        public static final int DUMP_KEYSETS = 1 << 11;
13627        public static final int DUMP_VERSION = 1 << 12;
13628        public static final int DUMP_INSTALLS = 1 << 13;
13629        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
13630        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
13631
13632        public static final int OPTION_SHOW_FILTERS = 1 << 0;
13633
13634        private int mTypes;
13635
13636        private int mOptions;
13637
13638        private boolean mTitlePrinted;
13639
13640        private SharedUserSetting mSharedUser;
13641
13642        public boolean isDumping(int type) {
13643            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
13644                return true;
13645            }
13646
13647            return (mTypes & type) != 0;
13648        }
13649
13650        public void setDump(int type) {
13651            mTypes |= type;
13652        }
13653
13654        public boolean isOptionEnabled(int option) {
13655            return (mOptions & option) != 0;
13656        }
13657
13658        public void setOptionEnabled(int option) {
13659            mOptions |= option;
13660        }
13661
13662        public boolean onTitlePrinted() {
13663            final boolean printed = mTitlePrinted;
13664            mTitlePrinted = true;
13665            return printed;
13666        }
13667
13668        public boolean getTitlePrinted() {
13669            return mTitlePrinted;
13670        }
13671
13672        public void setTitlePrinted(boolean enabled) {
13673            mTitlePrinted = enabled;
13674        }
13675
13676        public SharedUserSetting getSharedUser() {
13677            return mSharedUser;
13678        }
13679
13680        public void setSharedUser(SharedUserSetting user) {
13681            mSharedUser = user;
13682        }
13683    }
13684
13685    @Override
13686    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
13687        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
13688                != PackageManager.PERMISSION_GRANTED) {
13689            pw.println("Permission Denial: can't dump ActivityManager from from pid="
13690                    + Binder.getCallingPid()
13691                    + ", uid=" + Binder.getCallingUid()
13692                    + " without permission "
13693                    + android.Manifest.permission.DUMP);
13694            return;
13695        }
13696
13697        DumpState dumpState = new DumpState();
13698        boolean fullPreferred = false;
13699        boolean checkin = false;
13700
13701        String packageName = null;
13702
13703        int opti = 0;
13704        while (opti < args.length) {
13705            String opt = args[opti];
13706            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
13707                break;
13708            }
13709            opti++;
13710
13711            if ("-a".equals(opt)) {
13712                // Right now we only know how to print all.
13713            } else if ("-h".equals(opt)) {
13714                pw.println("Package manager dump options:");
13715                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
13716                pw.println("    --checkin: dump for a checkin");
13717                pw.println("    -f: print details of intent filters");
13718                pw.println("    -h: print this help");
13719                pw.println("  cmd may be one of:");
13720                pw.println("    l[ibraries]: list known shared libraries");
13721                pw.println("    f[ibraries]: list device features");
13722                pw.println("    k[eysets]: print known keysets");
13723                pw.println("    r[esolvers]: dump intent resolvers");
13724                pw.println("    perm[issions]: dump permissions");
13725                pw.println("    pref[erred]: print preferred package settings");
13726                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
13727                pw.println("    prov[iders]: dump content providers");
13728                pw.println("    p[ackages]: dump installed packages");
13729                pw.println("    s[hared-users]: dump shared user IDs");
13730                pw.println("    m[essages]: print collected runtime messages");
13731                pw.println("    v[erifiers]: print package verifier info");
13732                pw.println("    version: print database version info");
13733                pw.println("    write: write current settings now");
13734                pw.println("    <package.name>: info about given package");
13735                pw.println("    installs: details about install sessions");
13736                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
13737                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
13738                return;
13739            } else if ("--checkin".equals(opt)) {
13740                checkin = true;
13741            } else if ("-f".equals(opt)) {
13742                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
13743            } else {
13744                pw.println("Unknown argument: " + opt + "; use -h for help");
13745            }
13746        }
13747
13748        // Is the caller requesting to dump a particular piece of data?
13749        if (opti < args.length) {
13750            String cmd = args[opti];
13751            opti++;
13752            // Is this a package name?
13753            if ("android".equals(cmd) || cmd.contains(".")) {
13754                packageName = cmd;
13755                // When dumping a single package, we always dump all of its
13756                // filter information since the amount of data will be reasonable.
13757                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
13758            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
13759                dumpState.setDump(DumpState.DUMP_LIBS);
13760            } else if ("f".equals(cmd) || "features".equals(cmd)) {
13761                dumpState.setDump(DumpState.DUMP_FEATURES);
13762            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
13763                dumpState.setDump(DumpState.DUMP_RESOLVERS);
13764            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
13765                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
13766            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
13767                dumpState.setDump(DumpState.DUMP_PREFERRED);
13768            } else if ("preferred-xml".equals(cmd)) {
13769                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
13770                if (opti < args.length && "--full".equals(args[opti])) {
13771                    fullPreferred = true;
13772                    opti++;
13773                }
13774            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
13775                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
13776            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
13777                dumpState.setDump(DumpState.DUMP_PACKAGES);
13778            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
13779                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
13780            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
13781                dumpState.setDump(DumpState.DUMP_PROVIDERS);
13782            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
13783                dumpState.setDump(DumpState.DUMP_MESSAGES);
13784            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
13785                dumpState.setDump(DumpState.DUMP_VERIFIERS);
13786            } else if ("i".equals(cmd) || "ifv".equals(cmd)
13787                    || "intent-filter-verifiers".equals(cmd)) {
13788                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
13789            } else if ("version".equals(cmd)) {
13790                dumpState.setDump(DumpState.DUMP_VERSION);
13791            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
13792                dumpState.setDump(DumpState.DUMP_KEYSETS);
13793            } else if ("installs".equals(cmd)) {
13794                dumpState.setDump(DumpState.DUMP_INSTALLS);
13795            } else if ("write".equals(cmd)) {
13796                synchronized (mPackages) {
13797                    mSettings.writeLPr();
13798                    pw.println("Settings written.");
13799                    return;
13800                }
13801            }
13802        }
13803
13804        if (checkin) {
13805            pw.println("vers,1");
13806        }
13807
13808        // reader
13809        synchronized (mPackages) {
13810            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
13811                if (!checkin) {
13812                    if (dumpState.onTitlePrinted())
13813                        pw.println();
13814                    pw.println("Database versions:");
13815                    pw.print("  SDK Version:");
13816                    pw.print(" internal=");
13817                    pw.print(mSettings.mInternalSdkPlatform);
13818                    pw.print(" external=");
13819                    pw.println(mSettings.mExternalSdkPlatform);
13820                    pw.print("  DB Version:");
13821                    pw.print(" internal=");
13822                    pw.print(mSettings.mInternalDatabaseVersion);
13823                    pw.print(" external=");
13824                    pw.println(mSettings.mExternalDatabaseVersion);
13825                }
13826            }
13827
13828            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
13829                if (!checkin) {
13830                    if (dumpState.onTitlePrinted())
13831                        pw.println();
13832                    pw.println("Verifiers:");
13833                    pw.print("  Required: ");
13834                    pw.print(mRequiredVerifierPackage);
13835                    pw.print(" (uid=");
13836                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
13837                    pw.println(")");
13838                } else if (mRequiredVerifierPackage != null) {
13839                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
13840                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
13841                }
13842            }
13843
13844            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
13845                    packageName == null) {
13846                if (mIntentFilterVerifierComponent != null) {
13847                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
13848                    if (!checkin) {
13849                        if (dumpState.onTitlePrinted())
13850                            pw.println();
13851                        pw.println("Intent Filter Verifier:");
13852                        pw.print("  Using: ");
13853                        pw.print(verifierPackageName);
13854                        pw.print(" (uid=");
13855                        pw.print(getPackageUid(verifierPackageName, 0));
13856                        pw.println(")");
13857                    } else if (verifierPackageName != null) {
13858                        pw.print("ifv,"); pw.print(verifierPackageName);
13859                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
13860                    }
13861                } else {
13862                    pw.println();
13863                    pw.println("No Intent Filter Verifier available!");
13864                }
13865            }
13866
13867            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
13868                boolean printedHeader = false;
13869                final Iterator<String> it = mSharedLibraries.keySet().iterator();
13870                while (it.hasNext()) {
13871                    String name = it.next();
13872                    SharedLibraryEntry ent = mSharedLibraries.get(name);
13873                    if (!checkin) {
13874                        if (!printedHeader) {
13875                            if (dumpState.onTitlePrinted())
13876                                pw.println();
13877                            pw.println("Libraries:");
13878                            printedHeader = true;
13879                        }
13880                        pw.print("  ");
13881                    } else {
13882                        pw.print("lib,");
13883                    }
13884                    pw.print(name);
13885                    if (!checkin) {
13886                        pw.print(" -> ");
13887                    }
13888                    if (ent.path != null) {
13889                        if (!checkin) {
13890                            pw.print("(jar) ");
13891                            pw.print(ent.path);
13892                        } else {
13893                            pw.print(",jar,");
13894                            pw.print(ent.path);
13895                        }
13896                    } else {
13897                        if (!checkin) {
13898                            pw.print("(apk) ");
13899                            pw.print(ent.apk);
13900                        } else {
13901                            pw.print(",apk,");
13902                            pw.print(ent.apk);
13903                        }
13904                    }
13905                    pw.println();
13906                }
13907            }
13908
13909            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
13910                if (dumpState.onTitlePrinted())
13911                    pw.println();
13912                if (!checkin) {
13913                    pw.println("Features:");
13914                }
13915                Iterator<String> it = mAvailableFeatures.keySet().iterator();
13916                while (it.hasNext()) {
13917                    String name = it.next();
13918                    if (!checkin) {
13919                        pw.print("  ");
13920                    } else {
13921                        pw.print("feat,");
13922                    }
13923                    pw.println(name);
13924                }
13925            }
13926
13927            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
13928                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
13929                        : "Activity Resolver Table:", "  ", packageName,
13930                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13931                    dumpState.setTitlePrinted(true);
13932                }
13933                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
13934                        : "Receiver Resolver Table:", "  ", packageName,
13935                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13936                    dumpState.setTitlePrinted(true);
13937                }
13938                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
13939                        : "Service Resolver Table:", "  ", packageName,
13940                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13941                    dumpState.setTitlePrinted(true);
13942                }
13943                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
13944                        : "Provider Resolver Table:", "  ", packageName,
13945                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13946                    dumpState.setTitlePrinted(true);
13947                }
13948            }
13949
13950            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
13951                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13952                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13953                    int user = mSettings.mPreferredActivities.keyAt(i);
13954                    if (pir.dump(pw,
13955                            dumpState.getTitlePrinted()
13956                                ? "\nPreferred Activities User " + user + ":"
13957                                : "Preferred Activities User " + user + ":", "  ",
13958                            packageName, true, false)) {
13959                        dumpState.setTitlePrinted(true);
13960                    }
13961                }
13962            }
13963
13964            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
13965                pw.flush();
13966                FileOutputStream fout = new FileOutputStream(fd);
13967                BufferedOutputStream str = new BufferedOutputStream(fout);
13968                XmlSerializer serializer = new FastXmlSerializer();
13969                try {
13970                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
13971                    serializer.startDocument(null, true);
13972                    serializer.setFeature(
13973                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
13974                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
13975                    serializer.endDocument();
13976                    serializer.flush();
13977                } catch (IllegalArgumentException e) {
13978                    pw.println("Failed writing: " + e);
13979                } catch (IllegalStateException e) {
13980                    pw.println("Failed writing: " + e);
13981                } catch (IOException e) {
13982                    pw.println("Failed writing: " + e);
13983                }
13984            }
13985
13986            if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) {
13987                pw.println();
13988                int count = mSettings.mPackages.size();
13989                if (count == 0) {
13990                    pw.println("No domain preferred apps!");
13991                    pw.println();
13992                } else {
13993                    final String prefix = "  ";
13994                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
13995                    if (allPackageSettings.size() == 0) {
13996                        pw.println("No domain preferred apps!");
13997                        pw.println();
13998                    } else {
13999                        pw.println("Domain preferred apps status:");
14000                        pw.println();
14001                        count = 0;
14002                        for (PackageSetting ps : allPackageSettings) {
14003                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14004                            if (ivi == null || ivi.getPackageName() == null) continue;
14005                            pw.println(prefix + "Package Name: " + ivi.getPackageName());
14006                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
14007                            pw.println(prefix + "Status: " + ivi.getStatusString());
14008                            pw.println();
14009                            count++;
14010                        }
14011                        if (count == 0) {
14012                            pw.println(prefix + "No domain preferred app status!");
14013                            pw.println();
14014                        }
14015                        for (int userId : sUserManager.getUserIds()) {
14016                            pw.println("Domain preferred apps for User " + userId + ":");
14017                            pw.println();
14018                            count = 0;
14019                            for (PackageSetting ps : allPackageSettings) {
14020                                IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14021                                if (ivi == null || ivi.getPackageName() == null) {
14022                                    continue;
14023                                }
14024                                final int status = ps.getDomainVerificationStatusForUser(userId);
14025                                if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
14026                                    continue;
14027                                }
14028                                pw.println(prefix + "Package Name: " + ivi.getPackageName());
14029                                pw.println(prefix + "Domains: " + ivi.getDomainsString());
14030                                String statusStr = IntentFilterVerificationInfo.
14031                                        getStatusStringFromValue(status);
14032                                pw.println(prefix + "Status: " + statusStr);
14033                                pw.println();
14034                                count++;
14035                            }
14036                            if (count == 0) {
14037                                pw.println(prefix + "No domain preferred apps!");
14038                                pw.println();
14039                            }
14040                        }
14041                    }
14042                }
14043            }
14044
14045            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
14046                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
14047                if (packageName == null) {
14048                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
14049                        if (iperm == 0) {
14050                            if (dumpState.onTitlePrinted())
14051                                pw.println();
14052                            pw.println("AppOp Permissions:");
14053                        }
14054                        pw.print("  AppOp Permission ");
14055                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
14056                        pw.println(":");
14057                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
14058                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
14059                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
14060                        }
14061                    }
14062                }
14063            }
14064
14065            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
14066                boolean printedSomething = false;
14067                for (PackageParser.Provider p : mProviders.mProviders.values()) {
14068                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14069                        continue;
14070                    }
14071                    if (!printedSomething) {
14072                        if (dumpState.onTitlePrinted())
14073                            pw.println();
14074                        pw.println("Registered ContentProviders:");
14075                        printedSomething = true;
14076                    }
14077                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
14078                    pw.print("    "); pw.println(p.toString());
14079                }
14080                printedSomething = false;
14081                for (Map.Entry<String, PackageParser.Provider> entry :
14082                        mProvidersByAuthority.entrySet()) {
14083                    PackageParser.Provider p = entry.getValue();
14084                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14085                        continue;
14086                    }
14087                    if (!printedSomething) {
14088                        if (dumpState.onTitlePrinted())
14089                            pw.println();
14090                        pw.println("ContentProvider Authorities:");
14091                        printedSomething = true;
14092                    }
14093                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
14094                    pw.print("    "); pw.println(p.toString());
14095                    if (p.info != null && p.info.applicationInfo != null) {
14096                        final String appInfo = p.info.applicationInfo.toString();
14097                        pw.print("      applicationInfo="); pw.println(appInfo);
14098                    }
14099                }
14100            }
14101
14102            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
14103                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
14104            }
14105
14106            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
14107                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
14108            }
14109
14110            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
14111                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin);
14112            }
14113
14114            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
14115                // XXX should handle packageName != null by dumping only install data that
14116                // the given package is involved with.
14117                if (dumpState.onTitlePrinted()) pw.println();
14118                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
14119            }
14120
14121            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
14122                if (dumpState.onTitlePrinted()) pw.println();
14123                mSettings.dumpReadMessagesLPr(pw, dumpState);
14124
14125                pw.println();
14126                pw.println("Package warning messages:");
14127                BufferedReader in = null;
14128                String line = null;
14129                try {
14130                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14131                    while ((line = in.readLine()) != null) {
14132                        if (line.contains("ignored: updated version")) continue;
14133                        pw.println(line);
14134                    }
14135                } catch (IOException ignored) {
14136                } finally {
14137                    IoUtils.closeQuietly(in);
14138                }
14139            }
14140
14141            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
14142                BufferedReader in = null;
14143                String line = null;
14144                try {
14145                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14146                    while ((line = in.readLine()) != null) {
14147                        if (line.contains("ignored: updated version")) continue;
14148                        pw.print("msg,");
14149                        pw.println(line);
14150                    }
14151                } catch (IOException ignored) {
14152                } finally {
14153                    IoUtils.closeQuietly(in);
14154                }
14155            }
14156        }
14157    }
14158
14159    // ------- apps on sdcard specific code -------
14160    static final boolean DEBUG_SD_INSTALL = false;
14161
14162    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
14163
14164    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
14165
14166    private boolean mMediaMounted = false;
14167
14168    static String getEncryptKey() {
14169        try {
14170            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
14171                    SD_ENCRYPTION_KEYSTORE_NAME);
14172            if (sdEncKey == null) {
14173                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
14174                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
14175                if (sdEncKey == null) {
14176                    Slog.e(TAG, "Failed to create encryption keys");
14177                    return null;
14178                }
14179            }
14180            return sdEncKey;
14181        } catch (NoSuchAlgorithmException nsae) {
14182            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
14183            return null;
14184        } catch (IOException ioe) {
14185            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
14186            return null;
14187        }
14188    }
14189
14190    /*
14191     * Update media status on PackageManager.
14192     */
14193    @Override
14194    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
14195        int callingUid = Binder.getCallingUid();
14196        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
14197            throw new SecurityException("Media status can only be updated by the system");
14198        }
14199        // reader; this apparently protects mMediaMounted, but should probably
14200        // be a different lock in that case.
14201        synchronized (mPackages) {
14202            Log.i(TAG, "Updating external media status from "
14203                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
14204                    + (mediaStatus ? "mounted" : "unmounted"));
14205            if (DEBUG_SD_INSTALL)
14206                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
14207                        + ", mMediaMounted=" + mMediaMounted);
14208            if (mediaStatus == mMediaMounted) {
14209                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
14210                        : 0, -1);
14211                mHandler.sendMessage(msg);
14212                return;
14213            }
14214            mMediaMounted = mediaStatus;
14215        }
14216        // Queue up an async operation since the package installation may take a
14217        // little while.
14218        mHandler.post(new Runnable() {
14219            public void run() {
14220                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
14221            }
14222        });
14223    }
14224
14225    /**
14226     * Called by MountService when the initial ASECs to scan are available.
14227     * Should block until all the ASEC containers are finished being scanned.
14228     */
14229    public void scanAvailableAsecs() {
14230        updateExternalMediaStatusInner(true, false, false);
14231        if (mShouldRestoreconData) {
14232            SELinuxMMAC.setRestoreconDone();
14233            mShouldRestoreconData = false;
14234        }
14235    }
14236
14237    /*
14238     * Collect information of applications on external media, map them against
14239     * existing containers and update information based on current mount status.
14240     * Please note that we always have to report status if reportStatus has been
14241     * set to true especially when unloading packages.
14242     */
14243    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
14244            boolean externalStorage) {
14245        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
14246        int[] uidArr = EmptyArray.INT;
14247
14248        final String[] list = PackageHelper.getSecureContainerList();
14249        if (ArrayUtils.isEmpty(list)) {
14250            Log.i(TAG, "No secure containers found");
14251        } else {
14252            // Process list of secure containers and categorize them
14253            // as active or stale based on their package internal state.
14254
14255            // reader
14256            synchronized (mPackages) {
14257                for (String cid : list) {
14258                    // Leave stages untouched for now; installer service owns them
14259                    if (PackageInstallerService.isStageName(cid)) continue;
14260
14261                    if (DEBUG_SD_INSTALL)
14262                        Log.i(TAG, "Processing container " + cid);
14263                    String pkgName = getAsecPackageName(cid);
14264                    if (pkgName == null) {
14265                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
14266                        continue;
14267                    }
14268                    if (DEBUG_SD_INSTALL)
14269                        Log.i(TAG, "Looking for pkg : " + pkgName);
14270
14271                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
14272                    if (ps == null) {
14273                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
14274                        continue;
14275                    }
14276
14277                    /*
14278                     * Skip packages that are not external if we're unmounting
14279                     * external storage.
14280                     */
14281                    if (externalStorage && !isMounted && !isExternal(ps)) {
14282                        continue;
14283                    }
14284
14285                    final AsecInstallArgs args = new AsecInstallArgs(cid,
14286                            getAppDexInstructionSets(ps), ps.isForwardLocked());
14287                    // The package status is changed only if the code path
14288                    // matches between settings and the container id.
14289                    if (ps.codePathString != null
14290                            && ps.codePathString.startsWith(args.getCodePath())) {
14291                        if (DEBUG_SD_INSTALL) {
14292                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
14293                                    + " at code path: " + ps.codePathString);
14294                        }
14295
14296                        // We do have a valid package installed on sdcard
14297                        processCids.put(args, ps.codePathString);
14298                        final int uid = ps.appId;
14299                        if (uid != -1) {
14300                            uidArr = ArrayUtils.appendInt(uidArr, uid);
14301                        }
14302                    } else {
14303                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
14304                                + ps.codePathString);
14305                    }
14306                }
14307            }
14308
14309            Arrays.sort(uidArr);
14310        }
14311
14312        // Process packages with valid entries.
14313        if (isMounted) {
14314            if (DEBUG_SD_INSTALL)
14315                Log.i(TAG, "Loading packages");
14316            loadMediaPackages(processCids, uidArr);
14317            startCleaningPackages();
14318            mInstallerService.onSecureContainersAvailable();
14319        } else {
14320            if (DEBUG_SD_INSTALL)
14321                Log.i(TAG, "Unloading packages");
14322            unloadMediaPackages(processCids, uidArr, reportStatus);
14323        }
14324    }
14325
14326    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14327            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
14328        final int size = infos.size();
14329        final String[] packageNames = new String[size];
14330        final int[] packageUids = new int[size];
14331        for (int i = 0; i < size; i++) {
14332            final ApplicationInfo info = infos.get(i);
14333            packageNames[i] = info.packageName;
14334            packageUids[i] = info.uid;
14335        }
14336        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
14337                finishedReceiver);
14338    }
14339
14340    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14341            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14342        sendResourcesChangedBroadcast(mediaStatus, replacing,
14343                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
14344    }
14345
14346    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14347            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14348        int size = pkgList.length;
14349        if (size > 0) {
14350            // Send broadcasts here
14351            Bundle extras = new Bundle();
14352            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14353            if (uidArr != null) {
14354                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
14355            }
14356            if (replacing) {
14357                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
14358            }
14359            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
14360                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
14361            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
14362        }
14363    }
14364
14365   /*
14366     * Look at potentially valid container ids from processCids If package
14367     * information doesn't match the one on record or package scanning fails,
14368     * the cid is added to list of removeCids. We currently don't delete stale
14369     * containers.
14370     */
14371    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
14372        ArrayList<String> pkgList = new ArrayList<String>();
14373        Set<AsecInstallArgs> keys = processCids.keySet();
14374
14375        for (AsecInstallArgs args : keys) {
14376            String codePath = processCids.get(args);
14377            if (DEBUG_SD_INSTALL)
14378                Log.i(TAG, "Loading container : " + args.cid);
14379            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14380            try {
14381                // Make sure there are no container errors first.
14382                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
14383                    Slog.e(TAG, "Failed to mount cid : " + args.cid
14384                            + " when installing from sdcard");
14385                    continue;
14386                }
14387                // Check code path here.
14388                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
14389                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
14390                            + " does not match one in settings " + codePath);
14391                    continue;
14392                }
14393                // Parse package
14394                int parseFlags = mDefParseFlags;
14395                if (args.isExternalAsec()) {
14396                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
14397                }
14398                if (args.isFwdLocked()) {
14399                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
14400                }
14401
14402                synchronized (mInstallLock) {
14403                    PackageParser.Package pkg = null;
14404                    try {
14405                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
14406                    } catch (PackageManagerException e) {
14407                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
14408                    }
14409                    // Scan the package
14410                    if (pkg != null) {
14411                        /*
14412                         * TODO why is the lock being held? doPostInstall is
14413                         * called in other places without the lock. This needs
14414                         * to be straightened out.
14415                         */
14416                        // writer
14417                        synchronized (mPackages) {
14418                            retCode = PackageManager.INSTALL_SUCCEEDED;
14419                            pkgList.add(pkg.packageName);
14420                            // Post process args
14421                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
14422                                    pkg.applicationInfo.uid);
14423                        }
14424                    } else {
14425                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
14426                    }
14427                }
14428
14429            } finally {
14430                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
14431                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
14432                }
14433            }
14434        }
14435        // writer
14436        synchronized (mPackages) {
14437            // If the platform SDK has changed since the last time we booted,
14438            // we need to re-grant app permission to catch any new ones that
14439            // appear. This is really a hack, and means that apps can in some
14440            // cases get permissions that the user didn't initially explicitly
14441            // allow... it would be nice to have some better way to handle
14442            // this situation.
14443            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
14444            if (regrantPermissions)
14445                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
14446                        + mSdkVersion + "; regranting permissions for external storage");
14447            mSettings.mExternalSdkPlatform = mSdkVersion;
14448
14449            // Make sure group IDs have been assigned, and any permission
14450            // changes in other apps are accounted for
14451            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
14452                    | (regrantPermissions
14453                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
14454                            : 0));
14455
14456            mSettings.updateExternalDatabaseVersion();
14457
14458            // can downgrade to reader
14459            // Persist settings
14460            mSettings.writeLPr();
14461        }
14462        // Send a broadcast to let everyone know we are done processing
14463        if (pkgList.size() > 0) {
14464            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
14465        }
14466    }
14467
14468   /*
14469     * Utility method to unload a list of specified containers
14470     */
14471    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
14472        // Just unmount all valid containers.
14473        for (AsecInstallArgs arg : cidArgs) {
14474            synchronized (mInstallLock) {
14475                arg.doPostDeleteLI(false);
14476           }
14477       }
14478   }
14479
14480    /*
14481     * Unload packages mounted on external media. This involves deleting package
14482     * data from internal structures, sending broadcasts about diabled packages,
14483     * gc'ing to free up references, unmounting all secure containers
14484     * corresponding to packages on external media, and posting a
14485     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
14486     * that we always have to post this message if status has been requested no
14487     * matter what.
14488     */
14489    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
14490            final boolean reportStatus) {
14491        if (DEBUG_SD_INSTALL)
14492            Log.i(TAG, "unloading media packages");
14493        ArrayList<String> pkgList = new ArrayList<String>();
14494        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
14495        final Set<AsecInstallArgs> keys = processCids.keySet();
14496        for (AsecInstallArgs args : keys) {
14497            String pkgName = args.getPackageName();
14498            if (DEBUG_SD_INSTALL)
14499                Log.i(TAG, "Trying to unload pkg : " + pkgName);
14500            // Delete package internally
14501            PackageRemovedInfo outInfo = new PackageRemovedInfo();
14502            synchronized (mInstallLock) {
14503                boolean res = deletePackageLI(pkgName, null, false, null, null,
14504                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
14505                if (res) {
14506                    pkgList.add(pkgName);
14507                } else {
14508                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
14509                    failedList.add(args);
14510                }
14511            }
14512        }
14513
14514        // reader
14515        synchronized (mPackages) {
14516            // We didn't update the settings after removing each package;
14517            // write them now for all packages.
14518            mSettings.writeLPr();
14519        }
14520
14521        // We have to absolutely send UPDATED_MEDIA_STATUS only
14522        // after confirming that all the receivers processed the ordered
14523        // broadcast when packages get disabled, force a gc to clean things up.
14524        // and unload all the containers.
14525        if (pkgList.size() > 0) {
14526            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
14527                    new IIntentReceiver.Stub() {
14528                public void performReceive(Intent intent, int resultCode, String data,
14529                        Bundle extras, boolean ordered, boolean sticky,
14530                        int sendingUser) throws RemoteException {
14531                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
14532                            reportStatus ? 1 : 0, 1, keys);
14533                    mHandler.sendMessage(msg);
14534                }
14535            });
14536        } else {
14537            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
14538                    keys);
14539            mHandler.sendMessage(msg);
14540        }
14541    }
14542
14543    private void loadPrivatePackages(VolumeInfo vol) {
14544        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
14545        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
14546        synchronized (mInstallLock) {
14547        synchronized (mPackages) {
14548            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14549            for (PackageSetting ps : packages) {
14550                final PackageParser.Package pkg;
14551                try {
14552                    pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null);
14553                    loaded.add(pkg.applicationInfo);
14554                } catch (PackageManagerException e) {
14555                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
14556                }
14557            }
14558
14559            // TODO: regrant any permissions that changed based since original install
14560
14561            mSettings.writeLPr();
14562        }
14563        }
14564
14565        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
14566        sendResourcesChangedBroadcast(true, false, loaded, null);
14567    }
14568
14569    private void unloadPrivatePackages(VolumeInfo vol) {
14570        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
14571        synchronized (mInstallLock) {
14572        synchronized (mPackages) {
14573            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14574            for (PackageSetting ps : packages) {
14575                if (ps.pkg == null) continue;
14576
14577                final ApplicationInfo info = ps.pkg.applicationInfo;
14578                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
14579                if (deletePackageLI(ps.name, null, false, null, null,
14580                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
14581                    unloaded.add(info);
14582                } else {
14583                    Slog.w(TAG, "Failed to unload " + ps.codePath);
14584                }
14585            }
14586
14587            mSettings.writeLPr();
14588        }
14589        }
14590
14591        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
14592        sendResourcesChangedBroadcast(false, false, unloaded, null);
14593    }
14594
14595    private void unfreezePackage(String packageName) {
14596        synchronized (mPackages) {
14597            final PackageSetting ps = mSettings.mPackages.get(packageName);
14598            if (ps != null) {
14599                ps.frozen = false;
14600            }
14601        }
14602    }
14603
14604    @Override
14605    public int movePackage(final String packageName, final String volumeUuid) {
14606        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
14607
14608        final int moveId = mNextMoveId.getAndIncrement();
14609        try {
14610            movePackageInternal(packageName, volumeUuid, moveId);
14611        } catch (PackageManagerException e) {
14612            Slog.w(TAG, "Failed to move " + packageName, e);
14613            mMoveCallbacks.notifyStatusChanged(moveId,
14614                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
14615        }
14616        return moveId;
14617    }
14618
14619    private void movePackageInternal(final String packageName, final String volumeUuid,
14620            final int moveId) throws PackageManagerException {
14621        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
14622        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14623        final PackageManager pm = mContext.getPackageManager();
14624
14625        final boolean currentAsec;
14626        final String currentVolumeUuid;
14627        final File codeFile;
14628        final String installerPackageName;
14629        final String packageAbiOverride;
14630        final int appId;
14631        final String seinfo;
14632        final String label;
14633
14634        // reader
14635        synchronized (mPackages) {
14636            final PackageParser.Package pkg = mPackages.get(packageName);
14637            final PackageSetting ps = mSettings.mPackages.get(packageName);
14638            if (pkg == null || ps == null) {
14639                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
14640            }
14641
14642            if (pkg.applicationInfo.isSystemApp()) {
14643                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
14644                        "Cannot move system application");
14645            }
14646
14647            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
14648                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14649                        "Package already moved to " + volumeUuid);
14650            }
14651
14652            final File probe = new File(pkg.codePath);
14653            final File probeOat = new File(probe, "oat");
14654            if (!probe.isDirectory() || !probeOat.isDirectory()) {
14655                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14656                        "Move only supported for modern cluster style installs");
14657            }
14658
14659            if (ps.frozen) {
14660                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
14661                        "Failed to move already frozen package");
14662            }
14663            ps.frozen = true;
14664
14665            currentAsec = pkg.applicationInfo.isForwardLocked()
14666                    || pkg.applicationInfo.isExternalAsec();
14667            currentVolumeUuid = ps.volumeUuid;
14668            codeFile = new File(pkg.codePath);
14669            installerPackageName = ps.installerPackageName;
14670            packageAbiOverride = ps.cpuAbiOverrideString;
14671            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
14672            seinfo = pkg.applicationInfo.seinfo;
14673            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
14674        }
14675
14676        // Now that we're guarded by frozen state, kill app during move
14677        killApplication(packageName, appId, "move pkg");
14678
14679        final Bundle extras = new Bundle();
14680        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
14681        extras.putString(Intent.EXTRA_TITLE, label);
14682        mMoveCallbacks.notifyCreated(moveId, extras);
14683
14684        int installFlags;
14685        final boolean moveCompleteApp;
14686        final File measurePath;
14687
14688        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
14689            installFlags = INSTALL_INTERNAL;
14690            moveCompleteApp = !currentAsec;
14691            measurePath = Environment.getDataAppDirectory(volumeUuid);
14692        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
14693            installFlags = INSTALL_EXTERNAL;
14694            moveCompleteApp = false;
14695            measurePath = storage.getPrimaryPhysicalVolume().getPath();
14696        } else {
14697            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
14698            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
14699                    || !volume.isMountedWritable()) {
14700                unfreezePackage(packageName);
14701                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14702                        "Move location not mounted private volume");
14703            }
14704
14705            Preconditions.checkState(!currentAsec);
14706
14707            installFlags = INSTALL_INTERNAL;
14708            moveCompleteApp = true;
14709            measurePath = Environment.getDataAppDirectory(volumeUuid);
14710        }
14711
14712        final PackageStats stats = new PackageStats(null, -1);
14713        synchronized (mInstaller) {
14714            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
14715                unfreezePackage(packageName);
14716                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14717                        "Failed to measure package size");
14718            }
14719        }
14720
14721        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
14722                + stats.dataSize);
14723
14724        final long startFreeBytes = measurePath.getFreeSpace();
14725        final long sizeBytes;
14726        if (moveCompleteApp) {
14727            sizeBytes = stats.codeSize + stats.dataSize;
14728        } else {
14729            sizeBytes = stats.codeSize;
14730        }
14731
14732        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
14733            unfreezePackage(packageName);
14734            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14735                    "Not enough free space to move");
14736        }
14737
14738        mMoveCallbacks.notifyStatusChanged(moveId, 10);
14739
14740        final CountDownLatch installedLatch = new CountDownLatch(1);
14741        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
14742            @Override
14743            public void onUserActionRequired(Intent intent) throws RemoteException {
14744                throw new IllegalStateException();
14745            }
14746
14747            @Override
14748            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
14749                    Bundle extras) throws RemoteException {
14750                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
14751                        + PackageManager.installStatusToString(returnCode, msg));
14752
14753                installedLatch.countDown();
14754
14755                // Regardless of success or failure of the move operation,
14756                // always unfreeze the package
14757                unfreezePackage(packageName);
14758
14759                final int status = PackageManager.installStatusToPublicStatus(returnCode);
14760                switch (status) {
14761                    case PackageInstaller.STATUS_SUCCESS:
14762                        mMoveCallbacks.notifyStatusChanged(moveId,
14763                                PackageManager.MOVE_SUCCEEDED);
14764                        break;
14765                    case PackageInstaller.STATUS_FAILURE_STORAGE:
14766                        mMoveCallbacks.notifyStatusChanged(moveId,
14767                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
14768                        break;
14769                    default:
14770                        mMoveCallbacks.notifyStatusChanged(moveId,
14771                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
14772                        break;
14773                }
14774            }
14775        };
14776
14777        final MoveInfo move;
14778        if (moveCompleteApp) {
14779            // Kick off a thread to report progress estimates
14780            new Thread() {
14781                @Override
14782                public void run() {
14783                    while (true) {
14784                        try {
14785                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
14786                                break;
14787                            }
14788                        } catch (InterruptedException ignored) {
14789                        }
14790
14791                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
14792                        final int progress = 10 + (int) MathUtils.constrain(
14793                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
14794                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
14795                    }
14796                }
14797            }.start();
14798
14799            final String dataAppName = codeFile.getName();
14800            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
14801                    dataAppName, appId, seinfo);
14802        } else {
14803            move = null;
14804        }
14805
14806        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
14807
14808        final Message msg = mHandler.obtainMessage(INIT_COPY);
14809        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
14810        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
14811                installerPackageName, volumeUuid, null, user, packageAbiOverride);
14812        mHandler.sendMessage(msg);
14813    }
14814
14815    @Override
14816    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
14817        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
14818
14819        final int realMoveId = mNextMoveId.getAndIncrement();
14820        final Bundle extras = new Bundle();
14821        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
14822        mMoveCallbacks.notifyCreated(realMoveId, extras);
14823
14824        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
14825            @Override
14826            public void onCreated(int moveId, Bundle extras) {
14827                // Ignored
14828            }
14829
14830            @Override
14831            public void onStatusChanged(int moveId, int status, long estMillis) {
14832                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
14833            }
14834        };
14835
14836        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14837        storage.setPrimaryStorageUuid(volumeUuid, callback);
14838        return realMoveId;
14839    }
14840
14841    @Override
14842    public int getMoveStatus(int moveId) {
14843        mContext.enforceCallingOrSelfPermission(
14844                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
14845        return mMoveCallbacks.mLastStatus.get(moveId);
14846    }
14847
14848    @Override
14849    public void registerMoveCallback(IPackageMoveObserver callback) {
14850        mContext.enforceCallingOrSelfPermission(
14851                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
14852        mMoveCallbacks.register(callback);
14853    }
14854
14855    @Override
14856    public void unregisterMoveCallback(IPackageMoveObserver callback) {
14857        mContext.enforceCallingOrSelfPermission(
14858                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
14859        mMoveCallbacks.unregister(callback);
14860    }
14861
14862    @Override
14863    public boolean setInstallLocation(int loc) {
14864        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
14865                null);
14866        if (getInstallLocation() == loc) {
14867            return true;
14868        }
14869        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
14870                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
14871            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
14872                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
14873            return true;
14874        }
14875        return false;
14876   }
14877
14878    @Override
14879    public int getInstallLocation() {
14880        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14881                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
14882                PackageHelper.APP_INSTALL_AUTO);
14883    }
14884
14885    /** Called by UserManagerService */
14886    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
14887        mDirtyUsers.remove(userHandle);
14888        mSettings.removeUserLPw(userHandle);
14889        mPendingBroadcasts.remove(userHandle);
14890        if (mInstaller != null) {
14891            // Technically, we shouldn't be doing this with the package lock
14892            // held.  However, this is very rare, and there is already so much
14893            // other disk I/O going on, that we'll let it slide for now.
14894            final StorageManager storage = StorageManager.from(mContext);
14895            final List<VolumeInfo> vols = storage.getVolumes();
14896            for (VolumeInfo vol : vols) {
14897                if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) {
14898                    final String volumeUuid = vol.getFsUuid();
14899                    if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
14900                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
14901                }
14902            }
14903        }
14904        mUserNeedsBadging.delete(userHandle);
14905        removeUnusedPackagesLILPw(userManager, userHandle);
14906    }
14907
14908    /**
14909     * We're removing userHandle and would like to remove any downloaded packages
14910     * that are no longer in use by any other user.
14911     * @param userHandle the user being removed
14912     */
14913    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
14914        final boolean DEBUG_CLEAN_APKS = false;
14915        int [] users = userManager.getUserIdsLPr();
14916        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
14917        while (psit.hasNext()) {
14918            PackageSetting ps = psit.next();
14919            if (ps.pkg == null) {
14920                continue;
14921            }
14922            final String packageName = ps.pkg.packageName;
14923            // Skip over if system app
14924            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14925                continue;
14926            }
14927            if (DEBUG_CLEAN_APKS) {
14928                Slog.i(TAG, "Checking package " + packageName);
14929            }
14930            boolean keep = false;
14931            for (int i = 0; i < users.length; i++) {
14932                if (users[i] != userHandle && ps.getInstalled(users[i])) {
14933                    keep = true;
14934                    if (DEBUG_CLEAN_APKS) {
14935                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
14936                                + users[i]);
14937                    }
14938                    break;
14939                }
14940            }
14941            if (!keep) {
14942                if (DEBUG_CLEAN_APKS) {
14943                    Slog.i(TAG, "  Removing package " + packageName);
14944                }
14945                mHandler.post(new Runnable() {
14946                    public void run() {
14947                        deletePackageX(packageName, userHandle, 0);
14948                    } //end run
14949                });
14950            }
14951        }
14952    }
14953
14954    /** Called by UserManagerService */
14955    void createNewUserLILPw(int userHandle, File path) {
14956        if (mInstaller != null) {
14957            mInstaller.createUserConfig(userHandle);
14958            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
14959        }
14960    }
14961
14962    void newUserCreatedLILPw(int userHandle) {
14963        // Adding a user requires updating runtime permissions for system apps.
14964        updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
14965    }
14966
14967    @Override
14968    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
14969        mContext.enforceCallingOrSelfPermission(
14970                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14971                "Only package verification agents can read the verifier device identity");
14972
14973        synchronized (mPackages) {
14974            return mSettings.getVerifierDeviceIdentityLPw();
14975        }
14976    }
14977
14978    @Override
14979    public void setPermissionEnforced(String permission, boolean enforced) {
14980        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
14981        if (READ_EXTERNAL_STORAGE.equals(permission)) {
14982            synchronized (mPackages) {
14983                if (mSettings.mReadExternalStorageEnforced == null
14984                        || mSettings.mReadExternalStorageEnforced != enforced) {
14985                    mSettings.mReadExternalStorageEnforced = enforced;
14986                    mSettings.writeLPr();
14987                }
14988            }
14989            // kill any non-foreground processes so we restart them and
14990            // grant/revoke the GID.
14991            final IActivityManager am = ActivityManagerNative.getDefault();
14992            if (am != null) {
14993                final long token = Binder.clearCallingIdentity();
14994                try {
14995                    am.killProcessesBelowForeground("setPermissionEnforcement");
14996                } catch (RemoteException e) {
14997                } finally {
14998                    Binder.restoreCallingIdentity(token);
14999                }
15000            }
15001        } else {
15002            throw new IllegalArgumentException("No selective enforcement for " + permission);
15003        }
15004    }
15005
15006    @Override
15007    @Deprecated
15008    public boolean isPermissionEnforced(String permission) {
15009        return true;
15010    }
15011
15012    @Override
15013    public boolean isStorageLow() {
15014        final long token = Binder.clearCallingIdentity();
15015        try {
15016            final DeviceStorageMonitorInternal
15017                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
15018            if (dsm != null) {
15019                return dsm.isMemoryLow();
15020            } else {
15021                return false;
15022            }
15023        } finally {
15024            Binder.restoreCallingIdentity(token);
15025        }
15026    }
15027
15028    @Override
15029    public IPackageInstaller getPackageInstaller() {
15030        return mInstallerService;
15031    }
15032
15033    private boolean userNeedsBadging(int userId) {
15034        int index = mUserNeedsBadging.indexOfKey(userId);
15035        if (index < 0) {
15036            final UserInfo userInfo;
15037            final long token = Binder.clearCallingIdentity();
15038            try {
15039                userInfo = sUserManager.getUserInfo(userId);
15040            } finally {
15041                Binder.restoreCallingIdentity(token);
15042            }
15043            final boolean b;
15044            if (userInfo != null && userInfo.isManagedProfile()) {
15045                b = true;
15046            } else {
15047                b = false;
15048            }
15049            mUserNeedsBadging.put(userId, b);
15050            return b;
15051        }
15052        return mUserNeedsBadging.valueAt(index);
15053    }
15054
15055    @Override
15056    public KeySet getKeySetByAlias(String packageName, String alias) {
15057        if (packageName == null || alias == null) {
15058            return null;
15059        }
15060        synchronized(mPackages) {
15061            final PackageParser.Package pkg = mPackages.get(packageName);
15062            if (pkg == null) {
15063                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15064                throw new IllegalArgumentException("Unknown package: " + packageName);
15065            }
15066            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15067            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
15068        }
15069    }
15070
15071    @Override
15072    public KeySet getSigningKeySet(String packageName) {
15073        if (packageName == null) {
15074            return null;
15075        }
15076        synchronized(mPackages) {
15077            final PackageParser.Package pkg = mPackages.get(packageName);
15078            if (pkg == null) {
15079                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15080                throw new IllegalArgumentException("Unknown package: " + packageName);
15081            }
15082            if (pkg.applicationInfo.uid != Binder.getCallingUid()
15083                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
15084                throw new SecurityException("May not access signing KeySet of other apps.");
15085            }
15086            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15087            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
15088        }
15089    }
15090
15091    @Override
15092    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
15093        if (packageName == null || ks == null) {
15094            return false;
15095        }
15096        synchronized(mPackages) {
15097            final PackageParser.Package pkg = mPackages.get(packageName);
15098            if (pkg == null) {
15099                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15100                throw new IllegalArgumentException("Unknown package: " + packageName);
15101            }
15102            IBinder ksh = ks.getToken();
15103            if (ksh instanceof KeySetHandle) {
15104                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15105                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
15106            }
15107            return false;
15108        }
15109    }
15110
15111    @Override
15112    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
15113        if (packageName == null || ks == null) {
15114            return false;
15115        }
15116        synchronized(mPackages) {
15117            final PackageParser.Package pkg = mPackages.get(packageName);
15118            if (pkg == null) {
15119                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15120                throw new IllegalArgumentException("Unknown package: " + packageName);
15121            }
15122            IBinder ksh = ks.getToken();
15123            if (ksh instanceof KeySetHandle) {
15124                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15125                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
15126            }
15127            return false;
15128        }
15129    }
15130
15131    public void getUsageStatsIfNoPackageUsageInfo() {
15132        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
15133            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
15134            if (usm == null) {
15135                throw new IllegalStateException("UsageStatsManager must be initialized");
15136            }
15137            long now = System.currentTimeMillis();
15138            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
15139            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
15140                String packageName = entry.getKey();
15141                PackageParser.Package pkg = mPackages.get(packageName);
15142                if (pkg == null) {
15143                    continue;
15144                }
15145                UsageStats usage = entry.getValue();
15146                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
15147                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
15148            }
15149        }
15150    }
15151
15152    /**
15153     * Check and throw if the given before/after packages would be considered a
15154     * downgrade.
15155     */
15156    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
15157            throws PackageManagerException {
15158        if (after.versionCode < before.mVersionCode) {
15159            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15160                    "Update version code " + after.versionCode + " is older than current "
15161                    + before.mVersionCode);
15162        } else if (after.versionCode == before.mVersionCode) {
15163            if (after.baseRevisionCode < before.baseRevisionCode) {
15164                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15165                        "Update base revision code " + after.baseRevisionCode
15166                        + " is older than current " + before.baseRevisionCode);
15167            }
15168
15169            if (!ArrayUtils.isEmpty(after.splitNames)) {
15170                for (int i = 0; i < after.splitNames.length; i++) {
15171                    final String splitName = after.splitNames[i];
15172                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
15173                    if (j != -1) {
15174                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
15175                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15176                                    "Update split " + splitName + " revision code "
15177                                    + after.splitRevisionCodes[i] + " is older than current "
15178                                    + before.splitRevisionCodes[j]);
15179                        }
15180                    }
15181                }
15182            }
15183        }
15184    }
15185
15186    private static class MoveCallbacks extends Handler {
15187        private static final int MSG_CREATED = 1;
15188        private static final int MSG_STATUS_CHANGED = 2;
15189
15190        private final RemoteCallbackList<IPackageMoveObserver>
15191                mCallbacks = new RemoteCallbackList<>();
15192
15193        private final SparseIntArray mLastStatus = new SparseIntArray();
15194
15195        public MoveCallbacks(Looper looper) {
15196            super(looper);
15197        }
15198
15199        public void register(IPackageMoveObserver callback) {
15200            mCallbacks.register(callback);
15201        }
15202
15203        public void unregister(IPackageMoveObserver callback) {
15204            mCallbacks.unregister(callback);
15205        }
15206
15207        @Override
15208        public void handleMessage(Message msg) {
15209            final SomeArgs args = (SomeArgs) msg.obj;
15210            final int n = mCallbacks.beginBroadcast();
15211            for (int i = 0; i < n; i++) {
15212                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
15213                try {
15214                    invokeCallback(callback, msg.what, args);
15215                } catch (RemoteException ignored) {
15216                }
15217            }
15218            mCallbacks.finishBroadcast();
15219            args.recycle();
15220        }
15221
15222        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
15223                throws RemoteException {
15224            switch (what) {
15225                case MSG_CREATED: {
15226                    callback.onCreated(args.argi1, (Bundle) args.arg2);
15227                    break;
15228                }
15229                case MSG_STATUS_CHANGED: {
15230                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
15231                    break;
15232                }
15233            }
15234        }
15235
15236        private void notifyCreated(int moveId, Bundle extras) {
15237            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
15238
15239            final SomeArgs args = SomeArgs.obtain();
15240            args.argi1 = moveId;
15241            args.arg2 = extras;
15242            obtainMessage(MSG_CREATED, args).sendToTarget();
15243        }
15244
15245        private void notifyStatusChanged(int moveId, int status) {
15246            notifyStatusChanged(moveId, status, -1);
15247        }
15248
15249        private void notifyStatusChanged(int moveId, int status, long estMillis) {
15250            Slog.v(TAG, "Move " + moveId + " status " + status);
15251
15252            final SomeArgs args = SomeArgs.obtain();
15253            args.argi1 = moveId;
15254            args.argi2 = status;
15255            args.arg3 = estMillis;
15256            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
15257
15258            synchronized (mLastStatus) {
15259                mLastStatus.put(moveId, status);
15260            }
15261        }
15262    }
15263}
15264