PackageManagerService.java revision 25bb4553f379c70244f52d4864eab18530aa0a2e
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS;
20import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
26import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
27import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
28import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
29import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
30import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
32import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
33import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
34import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
36import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
37import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
38import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
39import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
41import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
42import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
44import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
45import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
46import static android.content.pm.PackageManager.INSTALL_INTERNAL;
47import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
48import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
49import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
50import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
51import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
52import static android.content.pm.PackageManager.MATCH_ALL;
53import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
54import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
55import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
56import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
57import static android.content.pm.PackageParser.isApkFile;
58import static android.os.Process.FIRST_APPLICATION_UID;
59import static android.os.Process.PACKAGE_INFO_GID;
60import static android.os.Process.SYSTEM_UID;
61import static android.system.OsConstants.O_CREAT;
62import static android.system.OsConstants.O_RDWR;
63import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
64import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
65import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
66import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
67import static com.android.internal.util.ArrayUtils.appendInt;
68import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
69import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
70import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
71import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
72import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
73
74import android.Manifest;
75import android.app.ActivityManager;
76import android.app.ActivityManagerNative;
77import android.app.AppGlobals;
78import android.app.IActivityManager;
79import android.app.admin.IDevicePolicyManager;
80import android.app.backup.IBackupManager;
81import android.app.usage.UsageStats;
82import android.app.usage.UsageStatsManager;
83import android.content.BroadcastReceiver;
84import android.content.ComponentName;
85import android.content.Context;
86import android.content.IIntentReceiver;
87import android.content.Intent;
88import android.content.IntentFilter;
89import android.content.IntentSender;
90import android.content.IntentSender.SendIntentException;
91import android.content.ServiceConnection;
92import android.content.pm.ActivityInfo;
93import android.content.pm.ApplicationInfo;
94import android.content.pm.FeatureInfo;
95import android.content.pm.IPackageDataObserver;
96import android.content.pm.IPackageDeleteObserver;
97import android.content.pm.IPackageDeleteObserver2;
98import android.content.pm.IPackageInstallObserver2;
99import android.content.pm.IPackageInstaller;
100import android.content.pm.IPackageManager;
101import android.content.pm.IPackageMoveObserver;
102import android.content.pm.IPackageStatsObserver;
103import android.content.pm.InstrumentationInfo;
104import android.content.pm.IntentFilterVerificationInfo;
105import android.content.pm.KeySet;
106import android.content.pm.ManifestDigest;
107import android.content.pm.PackageCleanItem;
108import android.content.pm.PackageInfo;
109import android.content.pm.PackageInfoLite;
110import android.content.pm.PackageInstaller;
111import android.content.pm.PackageManager;
112import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
113import android.content.pm.PackageParser;
114import android.content.pm.PackageParser.ActivityIntentInfo;
115import android.content.pm.PackageParser.PackageLite;
116import android.content.pm.PackageParser.PackageParserException;
117import android.content.pm.PackageStats;
118import android.content.pm.PackageUserState;
119import android.content.pm.ParceledListSlice;
120import android.content.pm.PermissionGroupInfo;
121import android.content.pm.PermissionInfo;
122import android.content.pm.ProviderInfo;
123import android.content.pm.ResolveInfo;
124import android.content.pm.ServiceInfo;
125import android.content.pm.Signature;
126import android.content.pm.UserInfo;
127import android.content.pm.VerificationParams;
128import android.content.pm.VerifierDeviceIdentity;
129import android.content.pm.VerifierInfo;
130import android.content.res.Resources;
131import android.hardware.display.DisplayManager;
132import android.net.Uri;
133import android.os.Binder;
134import android.os.Build;
135import android.os.Bundle;
136import android.os.Debug;
137import android.os.Environment;
138import android.os.Environment.UserEnvironment;
139import android.os.FileUtils;
140import android.os.Handler;
141import android.os.IBinder;
142import android.os.Looper;
143import android.os.Message;
144import android.os.Parcel;
145import android.os.ParcelFileDescriptor;
146import android.os.Process;
147import android.os.RemoteCallbackList;
148import android.os.RemoteException;
149import android.os.SELinux;
150import android.os.ServiceManager;
151import android.os.SystemClock;
152import android.os.SystemProperties;
153import android.os.UserHandle;
154import android.os.UserManager;
155import android.os.storage.IMountService;
156import android.os.storage.StorageEventListener;
157import android.os.storage.StorageManager;
158import android.os.storage.VolumeInfo;
159import android.os.storage.VolumeRecord;
160import android.security.KeyStore;
161import android.security.SystemKeyStore;
162import android.system.ErrnoException;
163import android.system.Os;
164import android.system.StructStat;
165import android.text.TextUtils;
166import android.text.format.DateUtils;
167import android.util.ArrayMap;
168import android.util.ArraySet;
169import android.util.AtomicFile;
170import android.util.DisplayMetrics;
171import android.util.EventLog;
172import android.util.ExceptionUtils;
173import android.util.Log;
174import android.util.LogPrinter;
175import android.util.MathUtils;
176import android.util.PrintStreamPrinter;
177import android.util.Slog;
178import android.util.SparseArray;
179import android.util.SparseBooleanArray;
180import android.util.SparseIntArray;
181import android.util.Xml;
182import android.view.Display;
183
184import dalvik.system.DexFile;
185import dalvik.system.VMRuntime;
186
187import libcore.io.IoUtils;
188import libcore.util.EmptyArray;
189
190import com.android.internal.R;
191import com.android.internal.app.IMediaContainerService;
192import com.android.internal.app.ResolverActivity;
193import com.android.internal.content.NativeLibraryHelper;
194import com.android.internal.content.PackageHelper;
195import com.android.internal.os.IParcelFileDescriptorFactory;
196import com.android.internal.os.SomeArgs;
197import com.android.internal.util.ArrayUtils;
198import com.android.internal.util.FastPrintWriter;
199import com.android.internal.util.FastXmlSerializer;
200import com.android.internal.util.IndentingPrintWriter;
201import com.android.internal.util.Preconditions;
202import com.android.server.EventLogTags;
203import com.android.server.FgThread;
204import com.android.server.IntentResolver;
205import com.android.server.LocalServices;
206import com.android.server.ServiceThread;
207import com.android.server.SystemConfig;
208import com.android.server.Watchdog;
209import com.android.server.pm.Settings.DatabaseVersion;
210import com.android.server.pm.PermissionsState.PermissionState;
211import com.android.server.storage.DeviceStorageMonitorInternal;
212
213import org.xmlpull.v1.XmlPullParser;
214import org.xmlpull.v1.XmlSerializer;
215
216import java.io.BufferedInputStream;
217import java.io.BufferedOutputStream;
218import java.io.BufferedReader;
219import java.io.ByteArrayInputStream;
220import java.io.ByteArrayOutputStream;
221import java.io.File;
222import java.io.FileDescriptor;
223import java.io.FileNotFoundException;
224import java.io.FileOutputStream;
225import java.io.FileReader;
226import java.io.FilenameFilter;
227import java.io.IOException;
228import java.io.InputStream;
229import java.io.PrintWriter;
230import java.nio.charset.StandardCharsets;
231import java.security.NoSuchAlgorithmException;
232import java.security.PublicKey;
233import java.security.cert.CertificateEncodingException;
234import java.security.cert.CertificateException;
235import java.text.SimpleDateFormat;
236import java.util.ArrayList;
237import java.util.Arrays;
238import java.util.Collection;
239import java.util.Collections;
240import java.util.Comparator;
241import java.util.Date;
242import java.util.Iterator;
243import java.util.List;
244import java.util.Map;
245import java.util.Objects;
246import java.util.Set;
247import java.util.concurrent.CountDownLatch;
248import java.util.concurrent.TimeUnit;
249import java.util.concurrent.atomic.AtomicBoolean;
250import java.util.concurrent.atomic.AtomicInteger;
251import java.util.concurrent.atomic.AtomicLong;
252
253/**
254 * Keep track of all those .apks everywhere.
255 *
256 * This is very central to the platform's security; please run the unit
257 * tests whenever making modifications here:
258 *
259mmm frameworks/base/tests/AndroidTests
260adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
261adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
262 *
263 * {@hide}
264 */
265public class PackageManagerService extends IPackageManager.Stub {
266    static final String TAG = "PackageManager";
267    static final boolean DEBUG_SETTINGS = false;
268    static final boolean DEBUG_PREFERRED = false;
269    static final boolean DEBUG_UPGRADE = false;
270    private static final boolean DEBUG_BACKUP = true;
271    private static final boolean DEBUG_INSTALL = false;
272    private static final boolean DEBUG_REMOVE = false;
273    private static final boolean DEBUG_BROADCASTS = false;
274    private static final boolean DEBUG_SHOW_INFO = false;
275    private static final boolean DEBUG_PACKAGE_INFO = false;
276    private static final boolean DEBUG_INTENT_MATCHING = false;
277    private static final boolean DEBUG_PACKAGE_SCANNING = false;
278    private static final boolean DEBUG_VERIFY = false;
279    private static final boolean DEBUG_DEXOPT = false;
280    private static final boolean DEBUG_ABI_SELECTION = false;
281
282    private static final int RADIO_UID = Process.PHONE_UID;
283    private static final int LOG_UID = Process.LOG_UID;
284    private static final int NFC_UID = Process.NFC_UID;
285    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
286    private static final int SHELL_UID = Process.SHELL_UID;
287
288    // Cap the size of permission trees that 3rd party apps can define
289    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
290
291    // Suffix used during package installation when copying/moving
292    // package apks to install directory.
293    private static final String INSTALL_PACKAGE_SUFFIX = "-";
294
295    static final int SCAN_NO_DEX = 1<<1;
296    static final int SCAN_FORCE_DEX = 1<<2;
297    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
298    static final int SCAN_NEW_INSTALL = 1<<4;
299    static final int SCAN_NO_PATHS = 1<<5;
300    static final int SCAN_UPDATE_TIME = 1<<6;
301    static final int SCAN_DEFER_DEX = 1<<7;
302    static final int SCAN_BOOTING = 1<<8;
303    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
304    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
305    static final int SCAN_REQUIRE_KNOWN = 1<<12;
306    static final int SCAN_MOVE = 1<<13;
307
308    static final int REMOVE_CHATTY = 1<<16;
309
310    private static final int[] EMPTY_INT_ARRAY = new int[0];
311
312    /**
313     * Timeout (in milliseconds) after which the watchdog should declare that
314     * our handler thread is wedged.  The usual default for such things is one
315     * minute but we sometimes do very lengthy I/O operations on this thread,
316     * such as installing multi-gigabyte applications, so ours needs to be longer.
317     */
318    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
319
320    /**
321     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
322     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
323     * settings entry if available, otherwise we use the hardcoded default.  If it's been
324     * more than this long since the last fstrim, we force one during the boot sequence.
325     *
326     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
327     * one gets run at the next available charging+idle time.  This final mandatory
328     * no-fstrim check kicks in only of the other scheduling criteria is never met.
329     */
330    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
331
332    /**
333     * Whether verification is enabled by default.
334     */
335    private static final boolean DEFAULT_VERIFY_ENABLE = true;
336
337    /**
338     * The default maximum time to wait for the verification agent to return in
339     * milliseconds.
340     */
341    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
342
343    /**
344     * The default response for package verification timeout.
345     *
346     * This can be either PackageManager.VERIFICATION_ALLOW or
347     * PackageManager.VERIFICATION_REJECT.
348     */
349    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
350
351    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
352
353    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
354            DEFAULT_CONTAINER_PACKAGE,
355            "com.android.defcontainer.DefaultContainerService");
356
357    private static final String KILL_APP_REASON_GIDS_CHANGED =
358            "permission grant or revoke changed gids";
359
360    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
361            "permissions revoked";
362
363    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
364
365    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
366
367    /** Permission grant: not grant the permission. */
368    private static final int GRANT_DENIED = 1;
369
370    /** Permission grant: grant the permission as an install permission. */
371    private static final int GRANT_INSTALL = 2;
372
373    /** Permission grant: grant the permission as an install permission for a legacy app. */
374    private static final int GRANT_INSTALL_LEGACY = 3;
375
376    /** Permission grant: grant the permission as a runtime one. */
377    private static final int GRANT_RUNTIME = 4;
378
379    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
380    private static final int GRANT_UPGRADE = 5;
381
382    final ServiceThread mHandlerThread;
383
384    final PackageHandler mHandler;
385
386    /**
387     * Messages for {@link #mHandler} that need to wait for system ready before
388     * being dispatched.
389     */
390    private ArrayList<Message> mPostSystemReadyMessages;
391
392    final int mSdkVersion = Build.VERSION.SDK_INT;
393
394    final Context mContext;
395    final boolean mFactoryTest;
396    final boolean mOnlyCore;
397    final boolean mLazyDexOpt;
398    final long mDexOptLRUThresholdInMills;
399    final DisplayMetrics mMetrics;
400    final int mDefParseFlags;
401    final String[] mSeparateProcesses;
402    final boolean mIsUpgrade;
403
404    // This is where all application persistent data goes.
405    final File mAppDataDir;
406
407    // This is where all application persistent data goes for secondary users.
408    final File mUserAppDataDir;
409
410    /** The location for ASEC container files on internal storage. */
411    final String mAsecInternalPath;
412
413    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
414    // LOCK HELD.  Can be called with mInstallLock held.
415    final Installer mInstaller;
416
417    /** Directory where installed third-party apps stored */
418    final File mAppInstallDir;
419
420    /**
421     * Directory to which applications installed internally have their
422     * 32 bit native libraries copied.
423     */
424    private File mAppLib32InstallDir;
425
426    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
427    // apps.
428    final File mDrmAppPrivateInstallDir;
429
430    // ----------------------------------------------------------------
431
432    // Lock for state used when installing and doing other long running
433    // operations.  Methods that must be called with this lock held have
434    // the suffix "LI".
435    final Object mInstallLock = new Object();
436
437    // ----------------------------------------------------------------
438
439    // Keys are String (package name), values are Package.  This also serves
440    // as the lock for the global state.  Methods that must be called with
441    // this lock held have the prefix "LP".
442    final ArrayMap<String, PackageParser.Package> mPackages =
443            new ArrayMap<String, PackageParser.Package>();
444
445    // Tracks available target package names -> overlay package paths.
446    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
447        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
448
449    final Settings mSettings;
450    boolean mRestoredSettings;
451
452    // System configuration read by SystemConfig.
453    final int[] mGlobalGids;
454    final SparseArray<ArraySet<String>> mSystemPermissions;
455    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
456
457    // If mac_permissions.xml was found for seinfo labeling.
458    boolean mFoundPolicyFile;
459
460    // If a recursive restorecon of /data/data/<pkg> is needed.
461    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
462
463    public static final class SharedLibraryEntry {
464        public final String path;
465        public final String apk;
466
467        SharedLibraryEntry(String _path, String _apk) {
468            path = _path;
469            apk = _apk;
470        }
471    }
472
473    // Currently known shared libraries.
474    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
475            new ArrayMap<String, SharedLibraryEntry>();
476
477    // All available activities, for your resolving pleasure.
478    final ActivityIntentResolver mActivities =
479            new ActivityIntentResolver();
480
481    // All available receivers, for your resolving pleasure.
482    final ActivityIntentResolver mReceivers =
483            new ActivityIntentResolver();
484
485    // All available services, for your resolving pleasure.
486    final ServiceIntentResolver mServices = new ServiceIntentResolver();
487
488    // All available providers, for your resolving pleasure.
489    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
490
491    // Mapping from provider base names (first directory in content URI codePath)
492    // to the provider information.
493    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
494            new ArrayMap<String, PackageParser.Provider>();
495
496    // Mapping from instrumentation class names to info about them.
497    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
498            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
499
500    // Mapping from permission names to info about them.
501    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
502            new ArrayMap<String, PackageParser.PermissionGroup>();
503
504    // Packages whose data we have transfered into another package, thus
505    // should no longer exist.
506    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
507
508    // Broadcast actions that are only available to the system.
509    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
510
511    /** List of packages waiting for verification. */
512    final SparseArray<PackageVerificationState> mPendingVerification
513            = new SparseArray<PackageVerificationState>();
514
515    /** Set of packages associated with each app op permission. */
516    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
517
518    final PackageInstallerService mInstallerService;
519
520    private final PackageDexOptimizer mPackageDexOptimizer;
521
522    private AtomicInteger mNextMoveId = new AtomicInteger();
523    private final MoveCallbacks mMoveCallbacks;
524
525    // Cache of users who need badging.
526    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
527
528    /** Token for keys in mPendingVerification. */
529    private int mPendingVerificationToken = 0;
530
531    volatile boolean mSystemReady;
532    volatile boolean mSafeMode;
533    volatile boolean mHasSystemUidErrors;
534
535    ApplicationInfo mAndroidApplication;
536    final ActivityInfo mResolveActivity = new ActivityInfo();
537    final ResolveInfo mResolveInfo = new ResolveInfo();
538    ComponentName mResolveComponentName;
539    PackageParser.Package mPlatformPackage;
540    ComponentName mCustomResolverComponentName;
541
542    boolean mResolverReplaced = false;
543
544    private final ComponentName mIntentFilterVerifierComponent;
545    private int mIntentFilterVerificationToken = 0;
546
547    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
548            = new SparseArray<IntentFilterVerificationState>();
549
550    private interface IntentFilterVerifier<T extends IntentFilter> {
551        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
552                                               T filter, String packageName);
553        void startVerifications(int userId);
554        void receiveVerificationResponse(int verificationId);
555    }
556
557    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
558        private Context mContext;
559        private ComponentName mIntentFilterVerifierComponent;
560        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
561
562        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
563            mContext = context;
564            mIntentFilterVerifierComponent = verifierComponent;
565        }
566
567        private String getDefaultScheme() {
568            // TODO: replace SCHEME_HTTP with SCHEME_HTTPS
569            return IntentFilter.SCHEME_HTTP;
570        }
571
572        @Override
573        public void startVerifications(int userId) {
574            // Launch verifications requests
575            int count = mCurrentIntentFilterVerifications.size();
576            for (int n=0; n<count; n++) {
577                int verificationId = mCurrentIntentFilterVerifications.get(n);
578                final IntentFilterVerificationState ivs =
579                        mIntentFilterVerificationStates.get(verificationId);
580
581                String packageName = ivs.getPackageName();
582
583                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
584                final int filterCount = filters.size();
585                ArraySet<String> domainsSet = new ArraySet<>();
586                for (int m=0; m<filterCount; m++) {
587                    PackageParser.ActivityIntentInfo filter = filters.get(m);
588                    domainsSet.addAll(filter.getHostsList());
589                }
590                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
591                synchronized (mPackages) {
592                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
593                            packageName, domainsList) != null) {
594                        scheduleWriteSettingsLocked();
595                    }
596                }
597                sendVerificationRequest(userId, verificationId, ivs);
598            }
599            mCurrentIntentFilterVerifications.clear();
600        }
601
602        private void sendVerificationRequest(int userId, int verificationId,
603                IntentFilterVerificationState ivs) {
604
605            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
606            verificationIntent.putExtra(
607                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
608                    verificationId);
609            verificationIntent.putExtra(
610                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
611                    getDefaultScheme());
612            verificationIntent.putExtra(
613                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
614                    ivs.getHostsString());
615            verificationIntent.putExtra(
616                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
617                    ivs.getPackageName());
618            verificationIntent.setComponent(mIntentFilterVerifierComponent);
619            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
620
621            UserHandle user = new UserHandle(userId);
622            mContext.sendBroadcastAsUser(verificationIntent, user);
623            Slog.d(TAG, "Sending IntenFilter verification broadcast");
624        }
625
626        public void receiveVerificationResponse(int verificationId) {
627            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
628
629            final boolean verified = ivs.isVerified();
630
631            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
632            final int count = filters.size();
633            for (int n=0; n<count; n++) {
634                PackageParser.ActivityIntentInfo filter = filters.get(n);
635                filter.setVerified(verified);
636
637                Slog.d(TAG, "IntentFilter " + filter.toString() + " verified with result:"
638                        + verified + " and hosts:" + ivs.getHostsString());
639            }
640
641            mIntentFilterVerificationStates.remove(verificationId);
642
643            final String packageName = ivs.getPackageName();
644            IntentFilterVerificationInfo ivi = null;
645
646            synchronized (mPackages) {
647                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
648            }
649            if (ivi == null) {
650                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
651                        + verificationId + " packageName:" + packageName);
652                return;
653            }
654            Slog.d(TAG, "Updating IntentFilterVerificationInfo for verificationId:"
655                    + verificationId);
656
657            synchronized (mPackages) {
658                if (verified) {
659                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
660                } else {
661                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
662                }
663                scheduleWriteSettingsLocked();
664
665                final int userId = ivs.getUserId();
666                if (userId != UserHandle.USER_ALL) {
667                    final int userStatus =
668                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
669
670                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
671                    boolean needUpdate = false;
672
673                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
674                    // already been set by the User thru the Disambiguation dialog
675                    switch (userStatus) {
676                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
677                            if (verified) {
678                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
679                            } else {
680                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
681                            }
682                            needUpdate = true;
683                            break;
684
685                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
686                            if (verified) {
687                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
688                                needUpdate = true;
689                            }
690                            break;
691
692                        default:
693                            // Nothing to do
694                    }
695
696                    if (needUpdate) {
697                        mSettings.updateIntentFilterVerificationStatusLPw(
698                                packageName, updatedStatus, userId);
699                        scheduleWritePackageRestrictionsLocked(userId);
700                    }
701                }
702            }
703        }
704
705        @Override
706        public boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
707                    ActivityIntentInfo filter, String packageName) {
708            if (!(filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
709                    filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
710                Slog.d(TAG, "IntentFilter does not contain HTTP nor HTTPS data scheme");
711                return false;
712            }
713            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
714            if (ivs == null) {
715                ivs = createDomainVerificationState(verifierId, userId, verificationId,
716                        packageName);
717            }
718            if (!hasValidDomains(filter)) {
719                return false;
720            }
721            ivs.addFilter(filter);
722            return true;
723        }
724
725        private IntentFilterVerificationState createDomainVerificationState(int verifierId,
726                int userId, int verificationId, String packageName) {
727            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
728                    verifierId, userId, packageName);
729            ivs.setPendingState();
730            synchronized (mPackages) {
731                mIntentFilterVerificationStates.append(verificationId, ivs);
732                mCurrentIntentFilterVerifications.add(verificationId);
733            }
734            return ivs;
735        }
736    }
737
738    private static boolean hasValidDomains(ActivityIntentInfo filter) {
739        return hasValidDomains(filter, true);
740    }
741
742    private static boolean hasValidDomains(ActivityIntentInfo filter, boolean logging) {
743        boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
744                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS);
745        if (!hasHTTPorHTTPS) {
746            if (logging) {
747                Slog.d(TAG, "IntentFilter does not contain any HTTP or HTTPS data scheme");
748            }
749            return false;
750        }
751        return true;
752    }
753
754    private IntentFilterVerifier mIntentFilterVerifier;
755
756    // Set of pending broadcasts for aggregating enable/disable of components.
757    static class PendingPackageBroadcasts {
758        // for each user id, a map of <package name -> components within that package>
759        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
760
761        public PendingPackageBroadcasts() {
762            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
763        }
764
765        public ArrayList<String> get(int userId, String packageName) {
766            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
767            return packages.get(packageName);
768        }
769
770        public void put(int userId, String packageName, ArrayList<String> components) {
771            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
772            packages.put(packageName, components);
773        }
774
775        public void remove(int userId, String packageName) {
776            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
777            if (packages != null) {
778                packages.remove(packageName);
779            }
780        }
781
782        public void remove(int userId) {
783            mUidMap.remove(userId);
784        }
785
786        public int userIdCount() {
787            return mUidMap.size();
788        }
789
790        public int userIdAt(int n) {
791            return mUidMap.keyAt(n);
792        }
793
794        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
795            return mUidMap.get(userId);
796        }
797
798        public int size() {
799            // total number of pending broadcast entries across all userIds
800            int num = 0;
801            for (int i = 0; i< mUidMap.size(); i++) {
802                num += mUidMap.valueAt(i).size();
803            }
804            return num;
805        }
806
807        public void clear() {
808            mUidMap.clear();
809        }
810
811        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
812            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
813            if (map == null) {
814                map = new ArrayMap<String, ArrayList<String>>();
815                mUidMap.put(userId, map);
816            }
817            return map;
818        }
819    }
820    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
821
822    // Service Connection to remote media container service to copy
823    // package uri's from external media onto secure containers
824    // or internal storage.
825    private IMediaContainerService mContainerService = null;
826
827    static final int SEND_PENDING_BROADCAST = 1;
828    static final int MCS_BOUND = 3;
829    static final int END_COPY = 4;
830    static final int INIT_COPY = 5;
831    static final int MCS_UNBIND = 6;
832    static final int START_CLEANING_PACKAGE = 7;
833    static final int FIND_INSTALL_LOC = 8;
834    static final int POST_INSTALL = 9;
835    static final int MCS_RECONNECT = 10;
836    static final int MCS_GIVE_UP = 11;
837    static final int UPDATED_MEDIA_STATUS = 12;
838    static final int WRITE_SETTINGS = 13;
839    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
840    static final int PACKAGE_VERIFIED = 15;
841    static final int CHECK_PENDING_VERIFICATION = 16;
842    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
843    static final int INTENT_FILTER_VERIFIED = 18;
844
845    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
846
847    // Delay time in millisecs
848    static final int BROADCAST_DELAY = 10 * 1000;
849
850    static UserManagerService sUserManager;
851
852    // Stores a list of users whose package restrictions file needs to be updated
853    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
854
855    final private DefaultContainerConnection mDefContainerConn =
856            new DefaultContainerConnection();
857    class DefaultContainerConnection implements ServiceConnection {
858        public void onServiceConnected(ComponentName name, IBinder service) {
859            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
860            IMediaContainerService imcs =
861                IMediaContainerService.Stub.asInterface(service);
862            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
863        }
864
865        public void onServiceDisconnected(ComponentName name) {
866            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
867        }
868    };
869
870    // Recordkeeping of restore-after-install operations that are currently in flight
871    // between the Package Manager and the Backup Manager
872    class PostInstallData {
873        public InstallArgs args;
874        public PackageInstalledInfo res;
875
876        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
877            args = _a;
878            res = _r;
879        }
880    };
881    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
882    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
883
884    // backup/restore of preferred activity state
885    private static final String TAG_PREFERRED_BACKUP = "pa";
886
887    private final String mRequiredVerifierPackage;
888
889    private final PackageUsage mPackageUsage = new PackageUsage();
890
891    private class PackageUsage {
892        private static final int WRITE_INTERVAL
893            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
894
895        private final Object mFileLock = new Object();
896        private final AtomicLong mLastWritten = new AtomicLong(0);
897        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
898
899        private boolean mIsHistoricalPackageUsageAvailable = true;
900
901        boolean isHistoricalPackageUsageAvailable() {
902            return mIsHistoricalPackageUsageAvailable;
903        }
904
905        void write(boolean force) {
906            if (force) {
907                writeInternal();
908                return;
909            }
910            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
911                && !DEBUG_DEXOPT) {
912                return;
913            }
914            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
915                new Thread("PackageUsage_DiskWriter") {
916                    @Override
917                    public void run() {
918                        try {
919                            writeInternal();
920                        } finally {
921                            mBackgroundWriteRunning.set(false);
922                        }
923                    }
924                }.start();
925            }
926        }
927
928        private void writeInternal() {
929            synchronized (mPackages) {
930                synchronized (mFileLock) {
931                    AtomicFile file = getFile();
932                    FileOutputStream f = null;
933                    try {
934                        f = file.startWrite();
935                        BufferedOutputStream out = new BufferedOutputStream(f);
936                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
937                        StringBuilder sb = new StringBuilder();
938                        for (PackageParser.Package pkg : mPackages.values()) {
939                            if (pkg.mLastPackageUsageTimeInMills == 0) {
940                                continue;
941                            }
942                            sb.setLength(0);
943                            sb.append(pkg.packageName);
944                            sb.append(' ');
945                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
946                            sb.append('\n');
947                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
948                        }
949                        out.flush();
950                        file.finishWrite(f);
951                    } catch (IOException e) {
952                        if (f != null) {
953                            file.failWrite(f);
954                        }
955                        Log.e(TAG, "Failed to write package usage times", e);
956                    }
957                }
958            }
959            mLastWritten.set(SystemClock.elapsedRealtime());
960        }
961
962        void readLP() {
963            synchronized (mFileLock) {
964                AtomicFile file = getFile();
965                BufferedInputStream in = null;
966                try {
967                    in = new BufferedInputStream(file.openRead());
968                    StringBuffer sb = new StringBuffer();
969                    while (true) {
970                        String packageName = readToken(in, sb, ' ');
971                        if (packageName == null) {
972                            break;
973                        }
974                        String timeInMillisString = readToken(in, sb, '\n');
975                        if (timeInMillisString == null) {
976                            throw new IOException("Failed to find last usage time for package "
977                                                  + packageName);
978                        }
979                        PackageParser.Package pkg = mPackages.get(packageName);
980                        if (pkg == null) {
981                            continue;
982                        }
983                        long timeInMillis;
984                        try {
985                            timeInMillis = Long.parseLong(timeInMillisString.toString());
986                        } catch (NumberFormatException e) {
987                            throw new IOException("Failed to parse " + timeInMillisString
988                                                  + " as a long.", e);
989                        }
990                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
991                    }
992                } catch (FileNotFoundException expected) {
993                    mIsHistoricalPackageUsageAvailable = false;
994                } catch (IOException e) {
995                    Log.w(TAG, "Failed to read package usage times", e);
996                } finally {
997                    IoUtils.closeQuietly(in);
998                }
999            }
1000            mLastWritten.set(SystemClock.elapsedRealtime());
1001        }
1002
1003        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1004                throws IOException {
1005            sb.setLength(0);
1006            while (true) {
1007                int ch = in.read();
1008                if (ch == -1) {
1009                    if (sb.length() == 0) {
1010                        return null;
1011                    }
1012                    throw new IOException("Unexpected EOF");
1013                }
1014                if (ch == endOfToken) {
1015                    return sb.toString();
1016                }
1017                sb.append((char)ch);
1018            }
1019        }
1020
1021        private AtomicFile getFile() {
1022            File dataDir = Environment.getDataDirectory();
1023            File systemDir = new File(dataDir, "system");
1024            File fname = new File(systemDir, "package-usage.list");
1025            return new AtomicFile(fname);
1026        }
1027    }
1028
1029    class PackageHandler extends Handler {
1030        private boolean mBound = false;
1031        final ArrayList<HandlerParams> mPendingInstalls =
1032            new ArrayList<HandlerParams>();
1033
1034        private boolean connectToService() {
1035            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1036                    " DefaultContainerService");
1037            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1038            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1039            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1040                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1041                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1042                mBound = true;
1043                return true;
1044            }
1045            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1046            return false;
1047        }
1048
1049        private void disconnectService() {
1050            mContainerService = null;
1051            mBound = false;
1052            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1053            mContext.unbindService(mDefContainerConn);
1054            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1055        }
1056
1057        PackageHandler(Looper looper) {
1058            super(looper);
1059        }
1060
1061        public void handleMessage(Message msg) {
1062            try {
1063                doHandleMessage(msg);
1064            } finally {
1065                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1066            }
1067        }
1068
1069        void doHandleMessage(Message msg) {
1070            switch (msg.what) {
1071                case INIT_COPY: {
1072                    HandlerParams params = (HandlerParams) msg.obj;
1073                    int idx = mPendingInstalls.size();
1074                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1075                    // If a bind was already initiated we dont really
1076                    // need to do anything. The pending install
1077                    // will be processed later on.
1078                    if (!mBound) {
1079                        // If this is the only one pending we might
1080                        // have to bind to the service again.
1081                        if (!connectToService()) {
1082                            Slog.e(TAG, "Failed to bind to media container service");
1083                            params.serviceError();
1084                            return;
1085                        } else {
1086                            // Once we bind to the service, the first
1087                            // pending request will be processed.
1088                            mPendingInstalls.add(idx, params);
1089                        }
1090                    } else {
1091                        mPendingInstalls.add(idx, params);
1092                        // Already bound to the service. Just make
1093                        // sure we trigger off processing the first request.
1094                        if (idx == 0) {
1095                            mHandler.sendEmptyMessage(MCS_BOUND);
1096                        }
1097                    }
1098                    break;
1099                }
1100                case MCS_BOUND: {
1101                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1102                    if (msg.obj != null) {
1103                        mContainerService = (IMediaContainerService) msg.obj;
1104                    }
1105                    if (mContainerService == null) {
1106                        // Something seriously wrong. Bail out
1107                        Slog.e(TAG, "Cannot bind to media container service");
1108                        for (HandlerParams params : mPendingInstalls) {
1109                            // Indicate service bind error
1110                            params.serviceError();
1111                        }
1112                        mPendingInstalls.clear();
1113                    } else if (mPendingInstalls.size() > 0) {
1114                        HandlerParams params = mPendingInstalls.get(0);
1115                        if (params != null) {
1116                            if (params.startCopy()) {
1117                                // We are done...  look for more work or to
1118                                // go idle.
1119                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1120                                        "Checking for more work or unbind...");
1121                                // Delete pending install
1122                                if (mPendingInstalls.size() > 0) {
1123                                    mPendingInstalls.remove(0);
1124                                }
1125                                if (mPendingInstalls.size() == 0) {
1126                                    if (mBound) {
1127                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1128                                                "Posting delayed MCS_UNBIND");
1129                                        removeMessages(MCS_UNBIND);
1130                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1131                                        // Unbind after a little delay, to avoid
1132                                        // continual thrashing.
1133                                        sendMessageDelayed(ubmsg, 10000);
1134                                    }
1135                                } else {
1136                                    // There are more pending requests in queue.
1137                                    // Just post MCS_BOUND message to trigger processing
1138                                    // of next pending install.
1139                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1140                                            "Posting MCS_BOUND for next work");
1141                                    mHandler.sendEmptyMessage(MCS_BOUND);
1142                                }
1143                            }
1144                        }
1145                    } else {
1146                        // Should never happen ideally.
1147                        Slog.w(TAG, "Empty queue");
1148                    }
1149                    break;
1150                }
1151                case MCS_RECONNECT: {
1152                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1153                    if (mPendingInstalls.size() > 0) {
1154                        if (mBound) {
1155                            disconnectService();
1156                        }
1157                        if (!connectToService()) {
1158                            Slog.e(TAG, "Failed to bind to media container service");
1159                            for (HandlerParams params : mPendingInstalls) {
1160                                // Indicate service bind error
1161                                params.serviceError();
1162                            }
1163                            mPendingInstalls.clear();
1164                        }
1165                    }
1166                    break;
1167                }
1168                case MCS_UNBIND: {
1169                    // If there is no actual work left, then time to unbind.
1170                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1171
1172                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1173                        if (mBound) {
1174                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1175
1176                            disconnectService();
1177                        }
1178                    } else if (mPendingInstalls.size() > 0) {
1179                        // There are more pending requests in queue.
1180                        // Just post MCS_BOUND message to trigger processing
1181                        // of next pending install.
1182                        mHandler.sendEmptyMessage(MCS_BOUND);
1183                    }
1184
1185                    break;
1186                }
1187                case MCS_GIVE_UP: {
1188                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1189                    mPendingInstalls.remove(0);
1190                    break;
1191                }
1192                case SEND_PENDING_BROADCAST: {
1193                    String packages[];
1194                    ArrayList<String> components[];
1195                    int size = 0;
1196                    int uids[];
1197                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1198                    synchronized (mPackages) {
1199                        if (mPendingBroadcasts == null) {
1200                            return;
1201                        }
1202                        size = mPendingBroadcasts.size();
1203                        if (size <= 0) {
1204                            // Nothing to be done. Just return
1205                            return;
1206                        }
1207                        packages = new String[size];
1208                        components = new ArrayList[size];
1209                        uids = new int[size];
1210                        int i = 0;  // filling out the above arrays
1211
1212                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1213                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1214                            Iterator<Map.Entry<String, ArrayList<String>>> it
1215                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1216                                            .entrySet().iterator();
1217                            while (it.hasNext() && i < size) {
1218                                Map.Entry<String, ArrayList<String>> ent = it.next();
1219                                packages[i] = ent.getKey();
1220                                components[i] = ent.getValue();
1221                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1222                                uids[i] = (ps != null)
1223                                        ? UserHandle.getUid(packageUserId, ps.appId)
1224                                        : -1;
1225                                i++;
1226                            }
1227                        }
1228                        size = i;
1229                        mPendingBroadcasts.clear();
1230                    }
1231                    // Send broadcasts
1232                    for (int i = 0; i < size; i++) {
1233                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1234                    }
1235                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1236                    break;
1237                }
1238                case START_CLEANING_PACKAGE: {
1239                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1240                    final String packageName = (String)msg.obj;
1241                    final int userId = msg.arg1;
1242                    final boolean andCode = msg.arg2 != 0;
1243                    synchronized (mPackages) {
1244                        if (userId == UserHandle.USER_ALL) {
1245                            int[] users = sUserManager.getUserIds();
1246                            for (int user : users) {
1247                                mSettings.addPackageToCleanLPw(
1248                                        new PackageCleanItem(user, packageName, andCode));
1249                            }
1250                        } else {
1251                            mSettings.addPackageToCleanLPw(
1252                                    new PackageCleanItem(userId, packageName, andCode));
1253                        }
1254                    }
1255                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1256                    startCleaningPackages();
1257                } break;
1258                case POST_INSTALL: {
1259                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1260                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1261                    mRunningInstalls.delete(msg.arg1);
1262                    boolean deleteOld = false;
1263
1264                    if (data != null) {
1265                        InstallArgs args = data.args;
1266                        PackageInstalledInfo res = data.res;
1267
1268                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1269                            res.removedInfo.sendBroadcast(false, true, false);
1270                            Bundle extras = new Bundle(1);
1271                            extras.putInt(Intent.EXTRA_UID, res.uid);
1272
1273                            // Now that we successfully installed the package, grant runtime
1274                            // permissions if requested before broadcasting the install.
1275                            if ((args.installFlags
1276                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1277                                grantRequestedRuntimePermissions(res.pkg,
1278                                        args.user.getIdentifier());
1279                            }
1280
1281                            // Determine the set of users who are adding this
1282                            // package for the first time vs. those who are seeing
1283                            // an update.
1284                            int[] firstUsers;
1285                            int[] updateUsers = new int[0];
1286                            if (res.origUsers == null || res.origUsers.length == 0) {
1287                                firstUsers = res.newUsers;
1288                            } else {
1289                                firstUsers = new int[0];
1290                                for (int i=0; i<res.newUsers.length; i++) {
1291                                    int user = res.newUsers[i];
1292                                    boolean isNew = true;
1293                                    for (int j=0; j<res.origUsers.length; j++) {
1294                                        if (res.origUsers[j] == user) {
1295                                            isNew = false;
1296                                            break;
1297                                        }
1298                                    }
1299                                    if (isNew) {
1300                                        int[] newFirst = new int[firstUsers.length+1];
1301                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1302                                                firstUsers.length);
1303                                        newFirst[firstUsers.length] = user;
1304                                        firstUsers = newFirst;
1305                                    } else {
1306                                        int[] newUpdate = new int[updateUsers.length+1];
1307                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1308                                                updateUsers.length);
1309                                        newUpdate[updateUsers.length] = user;
1310                                        updateUsers = newUpdate;
1311                                    }
1312                                }
1313                            }
1314                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1315                                    res.pkg.applicationInfo.packageName,
1316                                    extras, null, null, firstUsers);
1317                            final boolean update = res.removedInfo.removedPackage != null;
1318                            if (update) {
1319                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1320                            }
1321                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1322                                    res.pkg.applicationInfo.packageName,
1323                                    extras, null, null, updateUsers);
1324                            if (update) {
1325                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1326                                        res.pkg.applicationInfo.packageName,
1327                                        extras, null, null, updateUsers);
1328                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1329                                        null, null,
1330                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1331
1332                                // treat asec-hosted packages like removable media on upgrade
1333                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1334                                    if (DEBUG_INSTALL) {
1335                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1336                                                + " is ASEC-hosted -> AVAILABLE");
1337                                    }
1338                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1339                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1340                                    pkgList.add(res.pkg.applicationInfo.packageName);
1341                                    sendResourcesChangedBroadcast(true, true,
1342                                            pkgList,uidArray, null);
1343                                }
1344                            }
1345                            if (res.removedInfo.args != null) {
1346                                // Remove the replaced package's older resources safely now
1347                                deleteOld = true;
1348                            }
1349
1350                            // Log current value of "unknown sources" setting
1351                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1352                                getUnknownSourcesSettings());
1353                        }
1354                        // Force a gc to clear up things
1355                        Runtime.getRuntime().gc();
1356                        // We delete after a gc for applications  on sdcard.
1357                        if (deleteOld) {
1358                            synchronized (mInstallLock) {
1359                                res.removedInfo.args.doPostDeleteLI(true);
1360                            }
1361                        }
1362                        if (args.observer != null) {
1363                            try {
1364                                Bundle extras = extrasForInstallResult(res);
1365                                args.observer.onPackageInstalled(res.name, res.returnCode,
1366                                        res.returnMsg, extras);
1367                            } catch (RemoteException e) {
1368                                Slog.i(TAG, "Observer no longer exists.");
1369                            }
1370                        }
1371                    } else {
1372                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1373                    }
1374                } break;
1375                case UPDATED_MEDIA_STATUS: {
1376                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1377                    boolean reportStatus = msg.arg1 == 1;
1378                    boolean doGc = msg.arg2 == 1;
1379                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1380                    if (doGc) {
1381                        // Force a gc to clear up stale containers.
1382                        Runtime.getRuntime().gc();
1383                    }
1384                    if (msg.obj != null) {
1385                        @SuppressWarnings("unchecked")
1386                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1387                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1388                        // Unload containers
1389                        unloadAllContainers(args);
1390                    }
1391                    if (reportStatus) {
1392                        try {
1393                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1394                            PackageHelper.getMountService().finishMediaUpdate();
1395                        } catch (RemoteException e) {
1396                            Log.e(TAG, "MountService not running?");
1397                        }
1398                    }
1399                } break;
1400                case WRITE_SETTINGS: {
1401                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1402                    synchronized (mPackages) {
1403                        removeMessages(WRITE_SETTINGS);
1404                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1405                        mSettings.writeLPr();
1406                        mDirtyUsers.clear();
1407                    }
1408                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1409                } break;
1410                case WRITE_PACKAGE_RESTRICTIONS: {
1411                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1412                    synchronized (mPackages) {
1413                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1414                        for (int userId : mDirtyUsers) {
1415                            mSettings.writePackageRestrictionsLPr(userId);
1416                        }
1417                        mDirtyUsers.clear();
1418                    }
1419                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1420                } break;
1421                case CHECK_PENDING_VERIFICATION: {
1422                    final int verificationId = msg.arg1;
1423                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1424
1425                    if ((state != null) && !state.timeoutExtended()) {
1426                        final InstallArgs args = state.getInstallArgs();
1427                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1428
1429                        Slog.i(TAG, "Verification timed out for " + originUri);
1430                        mPendingVerification.remove(verificationId);
1431
1432                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1433
1434                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1435                            Slog.i(TAG, "Continuing with installation of " + originUri);
1436                            state.setVerifierResponse(Binder.getCallingUid(),
1437                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1438                            broadcastPackageVerified(verificationId, originUri,
1439                                    PackageManager.VERIFICATION_ALLOW,
1440                                    state.getInstallArgs().getUser());
1441                            try {
1442                                ret = args.copyApk(mContainerService, true);
1443                            } catch (RemoteException e) {
1444                                Slog.e(TAG, "Could not contact the ContainerService");
1445                            }
1446                        } else {
1447                            broadcastPackageVerified(verificationId, originUri,
1448                                    PackageManager.VERIFICATION_REJECT,
1449                                    state.getInstallArgs().getUser());
1450                        }
1451
1452                        processPendingInstall(args, ret);
1453                        mHandler.sendEmptyMessage(MCS_UNBIND);
1454                    }
1455                    break;
1456                }
1457                case PACKAGE_VERIFIED: {
1458                    final int verificationId = msg.arg1;
1459
1460                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1461                    if (state == null) {
1462                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1463                        break;
1464                    }
1465
1466                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1467
1468                    state.setVerifierResponse(response.callerUid, response.code);
1469
1470                    if (state.isVerificationComplete()) {
1471                        mPendingVerification.remove(verificationId);
1472
1473                        final InstallArgs args = state.getInstallArgs();
1474                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1475
1476                        int ret;
1477                        if (state.isInstallAllowed()) {
1478                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1479                            broadcastPackageVerified(verificationId, originUri,
1480                                    response.code, state.getInstallArgs().getUser());
1481                            try {
1482                                ret = args.copyApk(mContainerService, true);
1483                            } catch (RemoteException e) {
1484                                Slog.e(TAG, "Could not contact the ContainerService");
1485                            }
1486                        } else {
1487                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1488                        }
1489
1490                        processPendingInstall(args, ret);
1491
1492                        mHandler.sendEmptyMessage(MCS_UNBIND);
1493                    }
1494
1495                    break;
1496                }
1497                case START_INTENT_FILTER_VERIFICATIONS: {
1498                    int userId = msg.arg1;
1499                    int verifierUid = msg.arg2;
1500                    PackageParser.Package pkg = (PackageParser.Package)msg.obj;
1501
1502                    verifyIntentFiltersIfNeeded(userId, verifierUid, pkg);
1503                    break;
1504                }
1505                case INTENT_FILTER_VERIFIED: {
1506                    final int verificationId = msg.arg1;
1507
1508                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1509                            verificationId);
1510                    if (state == null) {
1511                        Slog.w(TAG, "Invalid IntentFilter verification token "
1512                                + verificationId + " received");
1513                        break;
1514                    }
1515
1516                    final int userId = state.getUserId();
1517
1518                    Slog.d(TAG, "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                    Slog.d(TAG, "IntentFilter verification with token:" + verificationId
1527                            + " and userId:" + userId
1528                            + " is settings verifier response with response code:"
1529                            + response.code);
1530
1531                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1532                        Slog.d(TAG, "Domains failing verification: "
1533                                + response.getFailedDomainsString());
1534                    }
1535
1536                    if (state.isVerificationComplete()) {
1537                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1538                    } else {
1539                        Slog.d(TAG, "IntentFilter verification with token:" + verificationId
1540                                + " was not said to be complete");
1541                    }
1542
1543                    break;
1544                }
1545            }
1546        }
1547    }
1548
1549    private StorageEventListener mStorageListener = new StorageEventListener() {
1550        @Override
1551        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1552            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1553                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1554                    // TODO: ensure that private directories exist for all active users
1555                    // TODO: remove user data whose serial number doesn't match
1556                    loadPrivatePackages(vol);
1557                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1558                    unloadPrivatePackages(vol);
1559                }
1560            }
1561
1562            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1563                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1564                    updateExternalMediaStatus(true, false);
1565                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1566                    updateExternalMediaStatus(false, false);
1567                }
1568            }
1569        }
1570
1571        @Override
1572        public void onVolumeForgotten(String fsUuid) {
1573            // TODO: remove all packages hosted on this uuid
1574        }
1575    };
1576
1577    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) {
1578        if (userId >= UserHandle.USER_OWNER) {
1579            grantRequestedRuntimePermissionsForUser(pkg, userId);
1580        } else if (userId == UserHandle.USER_ALL) {
1581            for (int someUserId : UserManagerService.getInstance().getUserIds()) {
1582                grantRequestedRuntimePermissionsForUser(pkg, someUserId);
1583            }
1584        }
1585    }
1586
1587    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) {
1588        SettingBase sb = (SettingBase) pkg.mExtras;
1589        if (sb == null) {
1590            return;
1591        }
1592
1593        PermissionsState permissionsState = sb.getPermissionsState();
1594
1595        for (String permission : pkg.requestedPermissions) {
1596            BasePermission bp = mSettings.mPermissions.get(permission);
1597            if (bp != null && bp.isRuntime()) {
1598                permissionsState.grantRuntimePermission(bp, userId);
1599            }
1600        }
1601    }
1602
1603    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1604        Bundle extras = null;
1605        switch (res.returnCode) {
1606            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1607                extras = new Bundle();
1608                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1609                        res.origPermission);
1610                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1611                        res.origPackage);
1612                break;
1613            }
1614            case PackageManager.INSTALL_SUCCEEDED: {
1615                extras = new Bundle();
1616                extras.putBoolean(Intent.EXTRA_REPLACING,
1617                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1618                break;
1619            }
1620        }
1621        return extras;
1622    }
1623
1624    void scheduleWriteSettingsLocked() {
1625        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1626            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1627        }
1628    }
1629
1630    void scheduleWritePackageRestrictionsLocked(int userId) {
1631        if (!sUserManager.exists(userId)) return;
1632        mDirtyUsers.add(userId);
1633        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1634            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1635        }
1636    }
1637
1638    public static PackageManagerService main(Context context, Installer installer,
1639            boolean factoryTest, boolean onlyCore) {
1640        PackageManagerService m = new PackageManagerService(context, installer,
1641                factoryTest, onlyCore);
1642        ServiceManager.addService("package", m);
1643        return m;
1644    }
1645
1646    static String[] splitString(String str, char sep) {
1647        int count = 1;
1648        int i = 0;
1649        while ((i=str.indexOf(sep, i)) >= 0) {
1650            count++;
1651            i++;
1652        }
1653
1654        String[] res = new String[count];
1655        i=0;
1656        count = 0;
1657        int lastI=0;
1658        while ((i=str.indexOf(sep, i)) >= 0) {
1659            res[count] = str.substring(lastI, i);
1660            count++;
1661            i++;
1662            lastI = i;
1663        }
1664        res[count] = str.substring(lastI, str.length());
1665        return res;
1666    }
1667
1668    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1669        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1670                Context.DISPLAY_SERVICE);
1671        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1672    }
1673
1674    public PackageManagerService(Context context, Installer installer,
1675            boolean factoryTest, boolean onlyCore) {
1676        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1677                SystemClock.uptimeMillis());
1678
1679        if (mSdkVersion <= 0) {
1680            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1681        }
1682
1683        mContext = context;
1684        mFactoryTest = factoryTest;
1685        mOnlyCore = onlyCore;
1686        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1687        mMetrics = new DisplayMetrics();
1688        mSettings = new Settings(mPackages);
1689        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1690                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1691        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1692                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1693        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1694                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1695        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1696                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1697        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1698                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1699        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1700                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1701
1702        // TODO: add a property to control this?
1703        long dexOptLRUThresholdInMinutes;
1704        if (mLazyDexOpt) {
1705            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1706        } else {
1707            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1708        }
1709        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1710
1711        String separateProcesses = SystemProperties.get("debug.separate_processes");
1712        if (separateProcesses != null && separateProcesses.length() > 0) {
1713            if ("*".equals(separateProcesses)) {
1714                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1715                mSeparateProcesses = null;
1716                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1717            } else {
1718                mDefParseFlags = 0;
1719                mSeparateProcesses = separateProcesses.split(",");
1720                Slog.w(TAG, "Running with debug.separate_processes: "
1721                        + separateProcesses);
1722            }
1723        } else {
1724            mDefParseFlags = 0;
1725            mSeparateProcesses = null;
1726        }
1727
1728        mInstaller = installer;
1729        mPackageDexOptimizer = new PackageDexOptimizer(this);
1730        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1731
1732        getDefaultDisplayMetrics(context, mMetrics);
1733
1734        SystemConfig systemConfig = SystemConfig.getInstance();
1735        mGlobalGids = systemConfig.getGlobalGids();
1736        mSystemPermissions = systemConfig.getSystemPermissions();
1737        mAvailableFeatures = systemConfig.getAvailableFeatures();
1738
1739        synchronized (mInstallLock) {
1740        // writer
1741        synchronized (mPackages) {
1742            mHandlerThread = new ServiceThread(TAG,
1743                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1744            mHandlerThread.start();
1745            mHandler = new PackageHandler(mHandlerThread.getLooper());
1746            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1747
1748            File dataDir = Environment.getDataDirectory();
1749            mAppDataDir = new File(dataDir, "data");
1750            mAppInstallDir = new File(dataDir, "app");
1751            mAppLib32InstallDir = new File(dataDir, "app-lib");
1752            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1753            mUserAppDataDir = new File(dataDir, "user");
1754            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1755
1756            sUserManager = new UserManagerService(context, this,
1757                    mInstallLock, mPackages);
1758
1759            // Propagate permission configuration in to package manager.
1760            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1761                    = systemConfig.getPermissions();
1762            for (int i=0; i<permConfig.size(); i++) {
1763                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1764                BasePermission bp = mSettings.mPermissions.get(perm.name);
1765                if (bp == null) {
1766                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1767                    mSettings.mPermissions.put(perm.name, bp);
1768                }
1769                if (perm.gids != null) {
1770                    bp.setGids(perm.gids, perm.perUser);
1771                }
1772            }
1773
1774            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1775            for (int i=0; i<libConfig.size(); i++) {
1776                mSharedLibraries.put(libConfig.keyAt(i),
1777                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1778            }
1779
1780            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1781
1782            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1783                    mSdkVersion, mOnlyCore);
1784
1785            String customResolverActivity = Resources.getSystem().getString(
1786                    R.string.config_customResolverActivity);
1787            if (TextUtils.isEmpty(customResolverActivity)) {
1788                customResolverActivity = null;
1789            } else {
1790                mCustomResolverComponentName = ComponentName.unflattenFromString(
1791                        customResolverActivity);
1792            }
1793
1794            long startTime = SystemClock.uptimeMillis();
1795
1796            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1797                    startTime);
1798
1799            // Set flag to monitor and not change apk file paths when
1800            // scanning install directories.
1801            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1802
1803            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1804
1805            /**
1806             * Add everything in the in the boot class path to the
1807             * list of process files because dexopt will have been run
1808             * if necessary during zygote startup.
1809             */
1810            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1811            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1812
1813            if (bootClassPath != null) {
1814                String[] bootClassPathElements = splitString(bootClassPath, ':');
1815                for (String element : bootClassPathElements) {
1816                    alreadyDexOpted.add(element);
1817                }
1818            } else {
1819                Slog.w(TAG, "No BOOTCLASSPATH found!");
1820            }
1821
1822            if (systemServerClassPath != null) {
1823                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1824                for (String element : systemServerClassPathElements) {
1825                    alreadyDexOpted.add(element);
1826                }
1827            } else {
1828                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1829            }
1830
1831            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1832            final String[] dexCodeInstructionSets =
1833                    getDexCodeInstructionSets(
1834                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1835
1836            /**
1837             * Ensure all external libraries have had dexopt run on them.
1838             */
1839            if (mSharedLibraries.size() > 0) {
1840                // NOTE: For now, we're compiling these system "shared libraries"
1841                // (and framework jars) into all available architectures. It's possible
1842                // to compile them only when we come across an app that uses them (there's
1843                // already logic for that in scanPackageLI) but that adds some complexity.
1844                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1845                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1846                        final String lib = libEntry.path;
1847                        if (lib == null) {
1848                            continue;
1849                        }
1850
1851                        try {
1852                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1853                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1854                                alreadyDexOpted.add(lib);
1855                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1856                            }
1857                        } catch (FileNotFoundException e) {
1858                            Slog.w(TAG, "Library not found: " + lib);
1859                        } catch (IOException e) {
1860                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1861                                    + e.getMessage());
1862                        }
1863                    }
1864                }
1865            }
1866
1867            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1868
1869            // Gross hack for now: we know this file doesn't contain any
1870            // code, so don't dexopt it to avoid the resulting log spew.
1871            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1872
1873            // Gross hack for now: we know this file is only part of
1874            // the boot class path for art, so don't dexopt it to
1875            // avoid the resulting log spew.
1876            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1877
1878            /**
1879             * There are a number of commands implemented in Java, which
1880             * we currently need to do the dexopt on so that they can be
1881             * run from a non-root shell.
1882             */
1883            String[] frameworkFiles = frameworkDir.list();
1884            if (frameworkFiles != null) {
1885                // TODO: We could compile these only for the most preferred ABI. We should
1886                // first double check that the dex files for these commands are not referenced
1887                // by other system apps.
1888                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1889                    for (int i=0; i<frameworkFiles.length; i++) {
1890                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1891                        String path = libPath.getPath();
1892                        // Skip the file if we already did it.
1893                        if (alreadyDexOpted.contains(path)) {
1894                            continue;
1895                        }
1896                        // Skip the file if it is not a type we want to dexopt.
1897                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1898                            continue;
1899                        }
1900                        try {
1901                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
1902                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1903                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1904                            }
1905                        } catch (FileNotFoundException e) {
1906                            Slog.w(TAG, "Jar not found: " + path);
1907                        } catch (IOException e) {
1908                            Slog.w(TAG, "Exception reading jar: " + path, e);
1909                        }
1910                    }
1911                }
1912            }
1913
1914            // Collect vendor overlay packages.
1915            // (Do this before scanning any apps.)
1916            // For security and version matching reason, only consider
1917            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1918            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1919            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1920                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1921
1922            // Find base frameworks (resource packages without code).
1923            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1924                    | PackageParser.PARSE_IS_SYSTEM_DIR
1925                    | PackageParser.PARSE_IS_PRIVILEGED,
1926                    scanFlags | SCAN_NO_DEX, 0);
1927
1928            // Collected privileged system packages.
1929            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1930            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1931                    | PackageParser.PARSE_IS_SYSTEM_DIR
1932                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1933
1934            // Collect ordinary system packages.
1935            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
1936            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1937                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1938
1939            // Collect all vendor packages.
1940            File vendorAppDir = new File("/vendor/app");
1941            try {
1942                vendorAppDir = vendorAppDir.getCanonicalFile();
1943            } catch (IOException e) {
1944                // failed to look up canonical path, continue with original one
1945            }
1946            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1947                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1948
1949            // Collect all OEM packages.
1950            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
1951            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1952                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1953
1954            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1955            mInstaller.moveFiles();
1956
1957            // Prune any system packages that no longer exist.
1958            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1959            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
1960            if (!mOnlyCore) {
1961                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1962                while (psit.hasNext()) {
1963                    PackageSetting ps = psit.next();
1964
1965                    /*
1966                     * If this is not a system app, it can't be a
1967                     * disable system app.
1968                     */
1969                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1970                        continue;
1971                    }
1972
1973                    /*
1974                     * If the package is scanned, it's not erased.
1975                     */
1976                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1977                    if (scannedPkg != null) {
1978                        /*
1979                         * If the system app is both scanned and in the
1980                         * disabled packages list, then it must have been
1981                         * added via OTA. Remove it from the currently
1982                         * scanned package so the previously user-installed
1983                         * application can be scanned.
1984                         */
1985                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1986                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
1987                                    + ps.name + "; removing system app.  Last known codePath="
1988                                    + ps.codePathString + ", installStatus=" + ps.installStatus
1989                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
1990                                    + scannedPkg.mVersionCode);
1991                            removePackageLI(ps, true);
1992                            expectingBetter.put(ps.name, ps.codePath);
1993                        }
1994
1995                        continue;
1996                    }
1997
1998                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1999                        psit.remove();
2000                        logCriticalInfo(Log.WARN, "System package " + ps.name
2001                                + " no longer exists; wiping its data");
2002                        removeDataDirsLI(null, ps.name);
2003                    } else {
2004                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2005                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2006                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2007                        }
2008                    }
2009                }
2010            }
2011
2012            //look for any incomplete package installations
2013            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2014            //clean up list
2015            for(int i = 0; i < deletePkgsList.size(); i++) {
2016                //clean up here
2017                cleanupInstallFailedPackage(deletePkgsList.get(i));
2018            }
2019            //delete tmp files
2020            deleteTempPackageFiles();
2021
2022            // Remove any shared userIDs that have no associated packages
2023            mSettings.pruneSharedUsersLPw();
2024
2025            if (!mOnlyCore) {
2026                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2027                        SystemClock.uptimeMillis());
2028                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2029
2030                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2031                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2032
2033                /**
2034                 * Remove disable package settings for any updated system
2035                 * apps that were removed via an OTA. If they're not a
2036                 * previously-updated app, remove them completely.
2037                 * Otherwise, just revoke their system-level permissions.
2038                 */
2039                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2040                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2041                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2042
2043                    String msg;
2044                    if (deletedPkg == null) {
2045                        msg = "Updated system package " + deletedAppName
2046                                + " no longer exists; wiping its data";
2047                        removeDataDirsLI(null, deletedAppName);
2048                    } else {
2049                        msg = "Updated system app + " + deletedAppName
2050                                + " no longer present; removing system privileges for "
2051                                + deletedAppName;
2052
2053                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2054
2055                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2056                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2057                    }
2058                    logCriticalInfo(Log.WARN, msg);
2059                }
2060
2061                /**
2062                 * Make sure all system apps that we expected to appear on
2063                 * the userdata partition actually showed up. If they never
2064                 * appeared, crawl back and revive the system version.
2065                 */
2066                for (int i = 0; i < expectingBetter.size(); i++) {
2067                    final String packageName = expectingBetter.keyAt(i);
2068                    if (!mPackages.containsKey(packageName)) {
2069                        final File scanFile = expectingBetter.valueAt(i);
2070
2071                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2072                                + " but never showed up; reverting to system");
2073
2074                        final int reparseFlags;
2075                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2076                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2077                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2078                                    | PackageParser.PARSE_IS_PRIVILEGED;
2079                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2080                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2081                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2082                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2083                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2084                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2085                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2086                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2087                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2088                        } else {
2089                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2090                            continue;
2091                        }
2092
2093                        mSettings.enableSystemPackageLPw(packageName);
2094
2095                        try {
2096                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2097                        } catch (PackageManagerException e) {
2098                            Slog.e(TAG, "Failed to parse original system package: "
2099                                    + e.getMessage());
2100                        }
2101                    }
2102                }
2103            }
2104
2105            // Now that we know all of the shared libraries, update all clients to have
2106            // the correct library paths.
2107            updateAllSharedLibrariesLPw();
2108
2109            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2110                // NOTE: We ignore potential failures here during a system scan (like
2111                // the rest of the commands above) because there's precious little we
2112                // can do about it. A settings error is reported, though.
2113                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2114                        false /* force dexopt */, false /* defer dexopt */);
2115            }
2116
2117            // Now that we know all the packages we are keeping,
2118            // read and update their last usage times.
2119            mPackageUsage.readLP();
2120
2121            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2122                    SystemClock.uptimeMillis());
2123            Slog.i(TAG, "Time to scan packages: "
2124                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2125                    + " seconds");
2126
2127            // If the platform SDK has changed since the last time we booted,
2128            // we need to re-grant app permission to catch any new ones that
2129            // appear.  This is really a hack, and means that apps can in some
2130            // cases get permissions that the user didn't initially explicitly
2131            // allow...  it would be nice to have some better way to handle
2132            // this situation.
2133            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
2134                    != mSdkVersion;
2135            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
2136                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
2137                    + "; regranting permissions for internal storage");
2138            mSettings.mInternalSdkPlatform = mSdkVersion;
2139
2140            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
2141                    | (regrantPermissions
2142                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
2143                            : 0));
2144
2145            // If this is the first boot, and it is a normal boot, then
2146            // we need to initialize the default preferred apps.
2147            if (!mRestoredSettings && !onlyCore) {
2148                mSettings.readDefaultPreferredAppsLPw(this, 0);
2149            }
2150
2151            // If this is first boot after an OTA, and a normal boot, then
2152            // we need to clear code cache directories.
2153            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
2154            if (mIsUpgrade && !onlyCore) {
2155                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2156                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2157                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2158                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2159                }
2160                mSettings.mFingerprint = Build.FINGERPRINT;
2161            }
2162
2163            primeDomainVerificationsLPw(false);
2164            checkDefaultBrowser();
2165
2166            // All the changes are done during package scanning.
2167            mSettings.updateInternalDatabaseVersion();
2168
2169            // can downgrade to reader
2170            mSettings.writeLPr();
2171
2172            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2173                    SystemClock.uptimeMillis());
2174
2175            mRequiredVerifierPackage = getRequiredVerifierLPr();
2176
2177            mInstallerService = new PackageInstallerService(context, this);
2178
2179            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2180            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2181                    mIntentFilterVerifierComponent);
2182
2183        } // synchronized (mPackages)
2184        } // synchronized (mInstallLock)
2185
2186        // Now after opening every single application zip, make sure they
2187        // are all flushed.  Not really needed, but keeps things nice and
2188        // tidy.
2189        Runtime.getRuntime().gc();
2190    }
2191
2192    @Override
2193    public boolean isFirstBoot() {
2194        return !mRestoredSettings;
2195    }
2196
2197    @Override
2198    public boolean isOnlyCoreApps() {
2199        return mOnlyCore;
2200    }
2201
2202    @Override
2203    public boolean isUpgrade() {
2204        return mIsUpgrade;
2205    }
2206
2207    private String getRequiredVerifierLPr() {
2208        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2209        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2210                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2211
2212        String requiredVerifier = null;
2213
2214        final int N = receivers.size();
2215        for (int i = 0; i < N; i++) {
2216            final ResolveInfo info = receivers.get(i);
2217
2218            if (info.activityInfo == null) {
2219                continue;
2220            }
2221
2222            final String packageName = info.activityInfo.packageName;
2223
2224            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2225                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2226                continue;
2227            }
2228
2229            if (requiredVerifier != null) {
2230                throw new RuntimeException("There can be only one required verifier");
2231            }
2232
2233            requiredVerifier = packageName;
2234        }
2235
2236        return requiredVerifier;
2237    }
2238
2239    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2240        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2241        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2242                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2243
2244        ComponentName verifierComponentName = null;
2245
2246        int priority = -1000;
2247        final int N = receivers.size();
2248        for (int i = 0; i < N; i++) {
2249            final ResolveInfo info = receivers.get(i);
2250
2251            if (info.activityInfo == null) {
2252                continue;
2253            }
2254
2255            final String packageName = info.activityInfo.packageName;
2256
2257            final PackageSetting ps = mSettings.mPackages.get(packageName);
2258            if (ps == null) {
2259                continue;
2260            }
2261
2262            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2263                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2264                continue;
2265            }
2266
2267            // Select the IntentFilterVerifier with the highest priority
2268            if (priority < info.priority) {
2269                priority = info.priority;
2270                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2271                Slog.d(TAG, "Selecting IntentFilterVerifier: " + verifierComponentName +
2272                        " with priority: " + info.priority);
2273            }
2274        }
2275
2276        return verifierComponentName;
2277    }
2278
2279    private void primeDomainVerificationsLPw(boolean logging) {
2280        Slog.d(TAG, "Start priming domain verifications");
2281        boolean updated = false;
2282        ArraySet<String> allHostsSet = new ArraySet<>();
2283        for (PackageParser.Package pkg : mPackages.values()) {
2284            final String packageName = pkg.packageName;
2285            if (!hasDomainURLs(pkg)) {
2286                if (logging) {
2287                    Slog.d(TAG, "No priming domain verifications for " +
2288                            "package with no domain URLs: " + packageName);
2289                }
2290                continue;
2291            }
2292            if (!pkg.isSystemApp()) {
2293                if (logging) {
2294                    Slog.d(TAG, "No priming domain verifications for a non system package : " +
2295                            packageName);
2296                }
2297                continue;
2298            }
2299            for (PackageParser.Activity a : pkg.activities) {
2300                for (ActivityIntentInfo filter : a.intents) {
2301                    if (hasValidDomains(filter, false)) {
2302                        allHostsSet.addAll(filter.getHostsList());
2303                    }
2304                }
2305            }
2306            if (allHostsSet.size() == 0) {
2307                allHostsSet.add("*");
2308            }
2309            ArrayList<String> allHostsList = new ArrayList<>(allHostsSet);
2310            IntentFilterVerificationInfo ivi =
2311                    mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList);
2312            if (ivi != null) {
2313                // We will always log this
2314                Slog.d(TAG, "Priming domain verifications for package: " + packageName +
2315                        " with hosts:" + ivi.getDomainsString());
2316                ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
2317                updated = true;
2318            }
2319            else {
2320                if (logging) {
2321                    Slog.d(TAG, "No priming domain verifications for package: " + packageName);
2322                }
2323            }
2324            allHostsSet.clear();
2325        }
2326        if (updated) {
2327            if (logging) {
2328                Slog.d(TAG, "Will need to write primed domain verifications");
2329            }
2330        }
2331        Slog.d(TAG, "End priming domain verifications");
2332    }
2333
2334    private void checkDefaultBrowser() {
2335        final int myUserId = UserHandle.myUserId();
2336        final String packageName = getDefaultBrowserPackageName(myUserId);
2337        PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2338        if (info == null) {
2339            Slog.w(TAG, "Clearing default Browser as its package is no more installed: " +
2340                    packageName);
2341            setDefaultBrowserPackageName(null, myUserId);
2342        }
2343    }
2344
2345    @Override
2346    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2347            throws RemoteException {
2348        try {
2349            return super.onTransact(code, data, reply, flags);
2350        } catch (RuntimeException e) {
2351            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2352                Slog.wtf(TAG, "Package Manager Crash", e);
2353            }
2354            throw e;
2355        }
2356    }
2357
2358    void cleanupInstallFailedPackage(PackageSetting ps) {
2359        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2360
2361        removeDataDirsLI(ps.volumeUuid, ps.name);
2362        if (ps.codePath != null) {
2363            if (ps.codePath.isDirectory()) {
2364                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2365            } else {
2366                ps.codePath.delete();
2367            }
2368        }
2369        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2370            if (ps.resourcePath.isDirectory()) {
2371                FileUtils.deleteContents(ps.resourcePath);
2372            }
2373            ps.resourcePath.delete();
2374        }
2375        mSettings.removePackageLPw(ps.name);
2376    }
2377
2378    static int[] appendInts(int[] cur, int[] add) {
2379        if (add == null) return cur;
2380        if (cur == null) return add;
2381        final int N = add.length;
2382        for (int i=0; i<N; i++) {
2383            cur = appendInt(cur, add[i]);
2384        }
2385        return cur;
2386    }
2387
2388    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2389        if (!sUserManager.exists(userId)) return null;
2390        final PackageSetting ps = (PackageSetting) p.mExtras;
2391        if (ps == null) {
2392            return null;
2393        }
2394
2395        final PermissionsState permissionsState = ps.getPermissionsState();
2396
2397        final int[] gids = permissionsState.computeGids(userId);
2398        final Set<String> permissions = permissionsState.getPermissions(userId);
2399        final PackageUserState state = ps.readUserState(userId);
2400
2401        return PackageParser.generatePackageInfo(p, gids, flags,
2402                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2403    }
2404
2405    @Override
2406    public boolean isPackageFrozen(String packageName) {
2407        synchronized (mPackages) {
2408            final PackageSetting ps = mSettings.mPackages.get(packageName);
2409            if (ps != null) {
2410                return ps.frozen;
2411            }
2412        }
2413        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2414        return true;
2415    }
2416
2417    @Override
2418    public boolean isPackageAvailable(String packageName, int userId) {
2419        if (!sUserManager.exists(userId)) return false;
2420        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2421        synchronized (mPackages) {
2422            PackageParser.Package p = mPackages.get(packageName);
2423            if (p != null) {
2424                final PackageSetting ps = (PackageSetting) p.mExtras;
2425                if (ps != null) {
2426                    final PackageUserState state = ps.readUserState(userId);
2427                    if (state != null) {
2428                        return PackageParser.isAvailable(state);
2429                    }
2430                }
2431            }
2432        }
2433        return false;
2434    }
2435
2436    @Override
2437    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2438        if (!sUserManager.exists(userId)) return null;
2439        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2440        // reader
2441        synchronized (mPackages) {
2442            PackageParser.Package p = mPackages.get(packageName);
2443            if (DEBUG_PACKAGE_INFO)
2444                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2445            if (p != null) {
2446                return generatePackageInfo(p, flags, userId);
2447            }
2448            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2449                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2450            }
2451        }
2452        return null;
2453    }
2454
2455    @Override
2456    public String[] currentToCanonicalPackageNames(String[] names) {
2457        String[] out = new String[names.length];
2458        // reader
2459        synchronized (mPackages) {
2460            for (int i=names.length-1; i>=0; i--) {
2461                PackageSetting ps = mSettings.mPackages.get(names[i]);
2462                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2463            }
2464        }
2465        return out;
2466    }
2467
2468    @Override
2469    public String[] canonicalToCurrentPackageNames(String[] names) {
2470        String[] out = new String[names.length];
2471        // reader
2472        synchronized (mPackages) {
2473            for (int i=names.length-1; i>=0; i--) {
2474                String cur = mSettings.mRenamedPackages.get(names[i]);
2475                out[i] = cur != null ? cur : names[i];
2476            }
2477        }
2478        return out;
2479    }
2480
2481    @Override
2482    public int getPackageUid(String packageName, int userId) {
2483        if (!sUserManager.exists(userId)) return -1;
2484        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2485
2486        // reader
2487        synchronized (mPackages) {
2488            PackageParser.Package p = mPackages.get(packageName);
2489            if(p != null) {
2490                return UserHandle.getUid(userId, p.applicationInfo.uid);
2491            }
2492            PackageSetting ps = mSettings.mPackages.get(packageName);
2493            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2494                return -1;
2495            }
2496            p = ps.pkg;
2497            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2498        }
2499    }
2500
2501    @Override
2502    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2503        if (!sUserManager.exists(userId)) {
2504            return null;
2505        }
2506
2507        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2508                "getPackageGids");
2509
2510        // reader
2511        synchronized (mPackages) {
2512            PackageParser.Package p = mPackages.get(packageName);
2513            if (DEBUG_PACKAGE_INFO) {
2514                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2515            }
2516            if (p != null) {
2517                PackageSetting ps = (PackageSetting) p.mExtras;
2518                return ps.getPermissionsState().computeGids(userId);
2519            }
2520        }
2521
2522        return null;
2523    }
2524
2525    static PermissionInfo generatePermissionInfo(
2526            BasePermission bp, int flags) {
2527        if (bp.perm != null) {
2528            return PackageParser.generatePermissionInfo(bp.perm, flags);
2529        }
2530        PermissionInfo pi = new PermissionInfo();
2531        pi.name = bp.name;
2532        pi.packageName = bp.sourcePackage;
2533        pi.nonLocalizedLabel = bp.name;
2534        pi.protectionLevel = bp.protectionLevel;
2535        return pi;
2536    }
2537
2538    @Override
2539    public PermissionInfo getPermissionInfo(String name, int flags) {
2540        // reader
2541        synchronized (mPackages) {
2542            final BasePermission p = mSettings.mPermissions.get(name);
2543            if (p != null) {
2544                return generatePermissionInfo(p, flags);
2545            }
2546            return null;
2547        }
2548    }
2549
2550    @Override
2551    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2552        // reader
2553        synchronized (mPackages) {
2554            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2555            for (BasePermission p : mSettings.mPermissions.values()) {
2556                if (group == null) {
2557                    if (p.perm == null || p.perm.info.group == null) {
2558                        out.add(generatePermissionInfo(p, flags));
2559                    }
2560                } else {
2561                    if (p.perm != null && group.equals(p.perm.info.group)) {
2562                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2563                    }
2564                }
2565            }
2566
2567            if (out.size() > 0) {
2568                return out;
2569            }
2570            return mPermissionGroups.containsKey(group) ? out : null;
2571        }
2572    }
2573
2574    @Override
2575    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2576        // reader
2577        synchronized (mPackages) {
2578            return PackageParser.generatePermissionGroupInfo(
2579                    mPermissionGroups.get(name), flags);
2580        }
2581    }
2582
2583    @Override
2584    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2585        // reader
2586        synchronized (mPackages) {
2587            final int N = mPermissionGroups.size();
2588            ArrayList<PermissionGroupInfo> out
2589                    = new ArrayList<PermissionGroupInfo>(N);
2590            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2591                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2592            }
2593            return out;
2594        }
2595    }
2596
2597    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2598            int userId) {
2599        if (!sUserManager.exists(userId)) return null;
2600        PackageSetting ps = mSettings.mPackages.get(packageName);
2601        if (ps != null) {
2602            if (ps.pkg == null) {
2603                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2604                        flags, userId);
2605                if (pInfo != null) {
2606                    return pInfo.applicationInfo;
2607                }
2608                return null;
2609            }
2610            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2611                    ps.readUserState(userId), userId);
2612        }
2613        return null;
2614    }
2615
2616    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2617            int userId) {
2618        if (!sUserManager.exists(userId)) return null;
2619        PackageSetting ps = mSettings.mPackages.get(packageName);
2620        if (ps != null) {
2621            PackageParser.Package pkg = ps.pkg;
2622            if (pkg == null) {
2623                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2624                    return null;
2625                }
2626                // Only data remains, so we aren't worried about code paths
2627                pkg = new PackageParser.Package(packageName);
2628                pkg.applicationInfo.packageName = packageName;
2629                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2630                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2631                pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid,
2632                        packageName, userId).getAbsolutePath();
2633                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2634                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2635            }
2636            return generatePackageInfo(pkg, flags, userId);
2637        }
2638        return null;
2639    }
2640
2641    @Override
2642    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2643        if (!sUserManager.exists(userId)) return null;
2644        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2645        // writer
2646        synchronized (mPackages) {
2647            PackageParser.Package p = mPackages.get(packageName);
2648            if (DEBUG_PACKAGE_INFO) Log.v(
2649                    TAG, "getApplicationInfo " + packageName
2650                    + ": " + p);
2651            if (p != null) {
2652                PackageSetting ps = mSettings.mPackages.get(packageName);
2653                if (ps == null) return null;
2654                // Note: isEnabledLP() does not apply here - always return info
2655                return PackageParser.generateApplicationInfo(
2656                        p, flags, ps.readUserState(userId), userId);
2657            }
2658            if ("android".equals(packageName)||"system".equals(packageName)) {
2659                return mAndroidApplication;
2660            }
2661            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2662                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2663            }
2664        }
2665        return null;
2666    }
2667
2668    @Override
2669    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2670            final IPackageDataObserver observer) {
2671        mContext.enforceCallingOrSelfPermission(
2672                android.Manifest.permission.CLEAR_APP_CACHE, null);
2673        // Queue up an async operation since clearing cache may take a little while.
2674        mHandler.post(new Runnable() {
2675            public void run() {
2676                mHandler.removeCallbacks(this);
2677                int retCode = -1;
2678                synchronized (mInstallLock) {
2679                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2680                    if (retCode < 0) {
2681                        Slog.w(TAG, "Couldn't clear application caches");
2682                    }
2683                }
2684                if (observer != null) {
2685                    try {
2686                        observer.onRemoveCompleted(null, (retCode >= 0));
2687                    } catch (RemoteException e) {
2688                        Slog.w(TAG, "RemoveException when invoking call back");
2689                    }
2690                }
2691            }
2692        });
2693    }
2694
2695    @Override
2696    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2697            final IntentSender pi) {
2698        mContext.enforceCallingOrSelfPermission(
2699                android.Manifest.permission.CLEAR_APP_CACHE, null);
2700        // Queue up an async operation since clearing cache may take a little while.
2701        mHandler.post(new Runnable() {
2702            public void run() {
2703                mHandler.removeCallbacks(this);
2704                int retCode = -1;
2705                synchronized (mInstallLock) {
2706                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2707                    if (retCode < 0) {
2708                        Slog.w(TAG, "Couldn't clear application caches");
2709                    }
2710                }
2711                if(pi != null) {
2712                    try {
2713                        // Callback via pending intent
2714                        int code = (retCode >= 0) ? 1 : 0;
2715                        pi.sendIntent(null, code, null,
2716                                null, null);
2717                    } catch (SendIntentException e1) {
2718                        Slog.i(TAG, "Failed to send pending intent");
2719                    }
2720                }
2721            }
2722        });
2723    }
2724
2725    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2726        synchronized (mInstallLock) {
2727            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2728                throw new IOException("Failed to free enough space");
2729            }
2730        }
2731    }
2732
2733    @Override
2734    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2735        if (!sUserManager.exists(userId)) return null;
2736        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2737        synchronized (mPackages) {
2738            PackageParser.Activity a = mActivities.mActivities.get(component);
2739
2740            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2741            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2742                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2743                if (ps == null) return null;
2744                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2745                        userId);
2746            }
2747            if (mResolveComponentName.equals(component)) {
2748                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2749                        new PackageUserState(), userId);
2750            }
2751        }
2752        return null;
2753    }
2754
2755    @Override
2756    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2757            String resolvedType) {
2758        synchronized (mPackages) {
2759            PackageParser.Activity a = mActivities.mActivities.get(component);
2760            if (a == null) {
2761                return false;
2762            }
2763            for (int i=0; i<a.intents.size(); i++) {
2764                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2765                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2766                    return true;
2767                }
2768            }
2769            return false;
2770        }
2771    }
2772
2773    @Override
2774    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2775        if (!sUserManager.exists(userId)) return null;
2776        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2777        synchronized (mPackages) {
2778            PackageParser.Activity a = mReceivers.mActivities.get(component);
2779            if (DEBUG_PACKAGE_INFO) Log.v(
2780                TAG, "getReceiverInfo " + component + ": " + a);
2781            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2782                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2783                if (ps == null) return null;
2784                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2785                        userId);
2786            }
2787        }
2788        return null;
2789    }
2790
2791    @Override
2792    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2793        if (!sUserManager.exists(userId)) return null;
2794        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2795        synchronized (mPackages) {
2796            PackageParser.Service s = mServices.mServices.get(component);
2797            if (DEBUG_PACKAGE_INFO) Log.v(
2798                TAG, "getServiceInfo " + component + ": " + s);
2799            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2800                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2801                if (ps == null) return null;
2802                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2803                        userId);
2804            }
2805        }
2806        return null;
2807    }
2808
2809    @Override
2810    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2811        if (!sUserManager.exists(userId)) return null;
2812        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2813        synchronized (mPackages) {
2814            PackageParser.Provider p = mProviders.mProviders.get(component);
2815            if (DEBUG_PACKAGE_INFO) Log.v(
2816                TAG, "getProviderInfo " + component + ": " + p);
2817            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2818                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2819                if (ps == null) return null;
2820                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2821                        userId);
2822            }
2823        }
2824        return null;
2825    }
2826
2827    @Override
2828    public String[] getSystemSharedLibraryNames() {
2829        Set<String> libSet;
2830        synchronized (mPackages) {
2831            libSet = mSharedLibraries.keySet();
2832            int size = libSet.size();
2833            if (size > 0) {
2834                String[] libs = new String[size];
2835                libSet.toArray(libs);
2836                return libs;
2837            }
2838        }
2839        return null;
2840    }
2841
2842    /**
2843     * @hide
2844     */
2845    PackageParser.Package findSharedNonSystemLibrary(String libName) {
2846        synchronized (mPackages) {
2847            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
2848            if (lib != null && lib.apk != null) {
2849                return mPackages.get(lib.apk);
2850            }
2851        }
2852        return null;
2853    }
2854
2855    @Override
2856    public FeatureInfo[] getSystemAvailableFeatures() {
2857        Collection<FeatureInfo> featSet;
2858        synchronized (mPackages) {
2859            featSet = mAvailableFeatures.values();
2860            int size = featSet.size();
2861            if (size > 0) {
2862                FeatureInfo[] features = new FeatureInfo[size+1];
2863                featSet.toArray(features);
2864                FeatureInfo fi = new FeatureInfo();
2865                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2866                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2867                features[size] = fi;
2868                return features;
2869            }
2870        }
2871        return null;
2872    }
2873
2874    @Override
2875    public boolean hasSystemFeature(String name) {
2876        synchronized (mPackages) {
2877            return mAvailableFeatures.containsKey(name);
2878        }
2879    }
2880
2881    private void checkValidCaller(int uid, int userId) {
2882        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2883            return;
2884
2885        throw new SecurityException("Caller uid=" + uid
2886                + " is not privileged to communicate with user=" + userId);
2887    }
2888
2889    @Override
2890    public int checkPermission(String permName, String pkgName, int userId) {
2891        if (!sUserManager.exists(userId)) {
2892            return PackageManager.PERMISSION_DENIED;
2893        }
2894
2895        synchronized (mPackages) {
2896            final PackageParser.Package p = mPackages.get(pkgName);
2897            if (p != null && p.mExtras != null) {
2898                final PackageSetting ps = (PackageSetting) p.mExtras;
2899                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2900                    return PackageManager.PERMISSION_GRANTED;
2901                }
2902            }
2903        }
2904
2905        return PackageManager.PERMISSION_DENIED;
2906    }
2907
2908    @Override
2909    public int checkUidPermission(String permName, int uid) {
2910        final int userId = UserHandle.getUserId(uid);
2911
2912        if (!sUserManager.exists(userId)) {
2913            return PackageManager.PERMISSION_DENIED;
2914        }
2915
2916        synchronized (mPackages) {
2917            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2918            if (obj != null) {
2919                final SettingBase ps = (SettingBase) obj;
2920                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2921                    return PackageManager.PERMISSION_GRANTED;
2922                }
2923            } else {
2924                ArraySet<String> perms = mSystemPermissions.get(uid);
2925                if (perms != null && perms.contains(permName)) {
2926                    return PackageManager.PERMISSION_GRANTED;
2927                }
2928            }
2929        }
2930
2931        return PackageManager.PERMISSION_DENIED;
2932    }
2933
2934    /**
2935     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2936     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2937     * @param checkShell TODO(yamasani):
2938     * @param message the message to log on security exception
2939     */
2940    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2941            boolean checkShell, String message) {
2942        if (userId < 0) {
2943            throw new IllegalArgumentException("Invalid userId " + userId);
2944        }
2945        if (checkShell) {
2946            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
2947        }
2948        if (userId == UserHandle.getUserId(callingUid)) return;
2949        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2950            if (requireFullPermission) {
2951                mContext.enforceCallingOrSelfPermission(
2952                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2953            } else {
2954                try {
2955                    mContext.enforceCallingOrSelfPermission(
2956                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2957                } catch (SecurityException se) {
2958                    mContext.enforceCallingOrSelfPermission(
2959                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2960                }
2961            }
2962        }
2963    }
2964
2965    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
2966        if (callingUid == Process.SHELL_UID) {
2967            if (userHandle >= 0
2968                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
2969                throw new SecurityException("Shell does not have permission to access user "
2970                        + userHandle);
2971            } else if (userHandle < 0) {
2972                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
2973                        + Debug.getCallers(3));
2974            }
2975        }
2976    }
2977
2978    private BasePermission findPermissionTreeLP(String permName) {
2979        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2980            if (permName.startsWith(bp.name) &&
2981                    permName.length() > bp.name.length() &&
2982                    permName.charAt(bp.name.length()) == '.') {
2983                return bp;
2984            }
2985        }
2986        return null;
2987    }
2988
2989    private BasePermission checkPermissionTreeLP(String permName) {
2990        if (permName != null) {
2991            BasePermission bp = findPermissionTreeLP(permName);
2992            if (bp != null) {
2993                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2994                    return bp;
2995                }
2996                throw new SecurityException("Calling uid "
2997                        + Binder.getCallingUid()
2998                        + " is not allowed to add to permission tree "
2999                        + bp.name + " owned by uid " + bp.uid);
3000            }
3001        }
3002        throw new SecurityException("No permission tree found for " + permName);
3003    }
3004
3005    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3006        if (s1 == null) {
3007            return s2 == null;
3008        }
3009        if (s2 == null) {
3010            return false;
3011        }
3012        if (s1.getClass() != s2.getClass()) {
3013            return false;
3014        }
3015        return s1.equals(s2);
3016    }
3017
3018    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3019        if (pi1.icon != pi2.icon) return false;
3020        if (pi1.logo != pi2.logo) return false;
3021        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3022        if (!compareStrings(pi1.name, pi2.name)) return false;
3023        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3024        // We'll take care of setting this one.
3025        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3026        // These are not currently stored in settings.
3027        //if (!compareStrings(pi1.group, pi2.group)) return false;
3028        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3029        //if (pi1.labelRes != pi2.labelRes) return false;
3030        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3031        return true;
3032    }
3033
3034    int permissionInfoFootprint(PermissionInfo info) {
3035        int size = info.name.length();
3036        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3037        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3038        return size;
3039    }
3040
3041    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3042        int size = 0;
3043        for (BasePermission perm : mSettings.mPermissions.values()) {
3044            if (perm.uid == tree.uid) {
3045                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3046            }
3047        }
3048        return size;
3049    }
3050
3051    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3052        // We calculate the max size of permissions defined by this uid and throw
3053        // if that plus the size of 'info' would exceed our stated maximum.
3054        if (tree.uid != Process.SYSTEM_UID) {
3055            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3056            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3057                throw new SecurityException("Permission tree size cap exceeded");
3058            }
3059        }
3060    }
3061
3062    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3063        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3064            throw new SecurityException("Label must be specified in permission");
3065        }
3066        BasePermission tree = checkPermissionTreeLP(info.name);
3067        BasePermission bp = mSettings.mPermissions.get(info.name);
3068        boolean added = bp == null;
3069        boolean changed = true;
3070        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3071        if (added) {
3072            enforcePermissionCapLocked(info, tree);
3073            bp = new BasePermission(info.name, tree.sourcePackage,
3074                    BasePermission.TYPE_DYNAMIC);
3075        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3076            throw new SecurityException(
3077                    "Not allowed to modify non-dynamic permission "
3078                    + info.name);
3079        } else {
3080            if (bp.protectionLevel == fixedLevel
3081                    && bp.perm.owner.equals(tree.perm.owner)
3082                    && bp.uid == tree.uid
3083                    && comparePermissionInfos(bp.perm.info, info)) {
3084                changed = false;
3085            }
3086        }
3087        bp.protectionLevel = fixedLevel;
3088        info = new PermissionInfo(info);
3089        info.protectionLevel = fixedLevel;
3090        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3091        bp.perm.info.packageName = tree.perm.info.packageName;
3092        bp.uid = tree.uid;
3093        if (added) {
3094            mSettings.mPermissions.put(info.name, bp);
3095        }
3096        if (changed) {
3097            if (!async) {
3098                mSettings.writeLPr();
3099            } else {
3100                scheduleWriteSettingsLocked();
3101            }
3102        }
3103        return added;
3104    }
3105
3106    @Override
3107    public boolean addPermission(PermissionInfo info) {
3108        synchronized (mPackages) {
3109            return addPermissionLocked(info, false);
3110        }
3111    }
3112
3113    @Override
3114    public boolean addPermissionAsync(PermissionInfo info) {
3115        synchronized (mPackages) {
3116            return addPermissionLocked(info, true);
3117        }
3118    }
3119
3120    @Override
3121    public void removePermission(String name) {
3122        synchronized (mPackages) {
3123            checkPermissionTreeLP(name);
3124            BasePermission bp = mSettings.mPermissions.get(name);
3125            if (bp != null) {
3126                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3127                    throw new SecurityException(
3128                            "Not allowed to modify non-dynamic permission "
3129                            + name);
3130                }
3131                mSettings.mPermissions.remove(name);
3132                mSettings.writeLPr();
3133            }
3134        }
3135    }
3136
3137    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3138            BasePermission bp) {
3139        int index = pkg.requestedPermissions.indexOf(bp.name);
3140        if (index == -1) {
3141            throw new SecurityException("Package " + pkg.packageName
3142                    + " has not requested permission " + bp.name);
3143        }
3144        if (!bp.isRuntime()) {
3145            throw new SecurityException("Permission " + bp.name
3146                    + " is not a changeable permission type");
3147        }
3148    }
3149
3150    @Override
3151    public void grantRuntimePermission(String packageName, String name, int userId) {
3152        if (!sUserManager.exists(userId)) {
3153            Log.e(TAG, "No such user:" + userId);
3154            return;
3155        }
3156
3157        mContext.enforceCallingOrSelfPermission(
3158                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3159                "grantRuntimePermission");
3160
3161        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3162                "grantRuntimePermission");
3163
3164        boolean gidsChanged = false;
3165        final SettingBase sb;
3166
3167        synchronized (mPackages) {
3168            final PackageParser.Package pkg = mPackages.get(packageName);
3169            if (pkg == null) {
3170                throw new IllegalArgumentException("Unknown package: " + packageName);
3171            }
3172
3173            final BasePermission bp = mSettings.mPermissions.get(name);
3174            if (bp == null) {
3175                throw new IllegalArgumentException("Unknown permission: " + name);
3176            }
3177
3178            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3179
3180            sb = (SettingBase) pkg.mExtras;
3181            if (sb == null) {
3182                throw new IllegalArgumentException("Unknown package: " + packageName);
3183            }
3184
3185            final PermissionsState permissionsState = sb.getPermissionsState();
3186
3187            final int flags = permissionsState.getPermissionFlags(name, userId);
3188            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3189                throw new SecurityException("Cannot grant system fixed permission: "
3190                        + name + " for package: " + packageName);
3191            }
3192
3193            final int result = permissionsState.grantRuntimePermission(bp, userId);
3194            switch (result) {
3195                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3196                    return;
3197                }
3198
3199                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3200                    gidsChanged = true;
3201                }
3202                break;
3203            }
3204
3205            // Not critical if that is lost - app has to request again.
3206            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3207        }
3208
3209        if (gidsChanged) {
3210            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3211        }
3212    }
3213
3214    @Override
3215    public void revokeRuntimePermission(String packageName, String name, int userId) {
3216        if (!sUserManager.exists(userId)) {
3217            Log.e(TAG, "No such user:" + userId);
3218            return;
3219        }
3220
3221        mContext.enforceCallingOrSelfPermission(
3222                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3223                "revokeRuntimePermission");
3224
3225        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3226                "revokeRuntimePermission");
3227
3228        final SettingBase sb;
3229
3230        synchronized (mPackages) {
3231            final PackageParser.Package pkg = mPackages.get(packageName);
3232            if (pkg == null) {
3233                throw new IllegalArgumentException("Unknown package: " + packageName);
3234            }
3235
3236            final BasePermission bp = mSettings.mPermissions.get(name);
3237            if (bp == null) {
3238                throw new IllegalArgumentException("Unknown permission: " + name);
3239            }
3240
3241            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3242
3243            sb = (SettingBase) pkg.mExtras;
3244            if (sb == null) {
3245                throw new IllegalArgumentException("Unknown package: " + packageName);
3246            }
3247
3248            final PermissionsState permissionsState = sb.getPermissionsState();
3249
3250            final int flags = permissionsState.getPermissionFlags(name, userId);
3251            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3252                throw new SecurityException("Cannot revoke system fixed permission: "
3253                        + name + " for package: " + packageName);
3254            }
3255
3256            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3257                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3258                return;
3259            }
3260
3261            // Critical, after this call app should never have the permission.
3262            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3263        }
3264
3265        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3266    }
3267
3268    @Override
3269    public int getPermissionFlags(String name, String packageName, int userId) {
3270        if (!sUserManager.exists(userId)) {
3271            return 0;
3272        }
3273
3274        mContext.enforceCallingOrSelfPermission(
3275                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3276                "getPermissionFlags");
3277
3278        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3279                "getPermissionFlags");
3280
3281        synchronized (mPackages) {
3282            final PackageParser.Package pkg = mPackages.get(packageName);
3283            if (pkg == null) {
3284                throw new IllegalArgumentException("Unknown package: " + packageName);
3285            }
3286
3287            final BasePermission bp = mSettings.mPermissions.get(name);
3288            if (bp == null) {
3289                throw new IllegalArgumentException("Unknown permission: " + name);
3290            }
3291
3292            SettingBase sb = (SettingBase) pkg.mExtras;
3293            if (sb == null) {
3294                throw new IllegalArgumentException("Unknown package: " + packageName);
3295            }
3296
3297            PermissionsState permissionsState = sb.getPermissionsState();
3298            return permissionsState.getPermissionFlags(name, userId);
3299        }
3300    }
3301
3302    @Override
3303    public void updatePermissionFlags(String name, String packageName, int flagMask,
3304            int flagValues, int userId) {
3305        if (!sUserManager.exists(userId)) {
3306            return;
3307        }
3308
3309        mContext.enforceCallingOrSelfPermission(
3310                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3311                "updatePermissionFlags");
3312
3313        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3314                "updatePermissionFlags");
3315
3316        // Only the system can change policy flags.
3317        if (getCallingUid() != Process.SYSTEM_UID) {
3318            flagMask &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED;
3319            flagValues &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED;
3320        }
3321
3322        // Only the package manager can change system flags.
3323        flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3324        flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3325
3326        synchronized (mPackages) {
3327            final PackageParser.Package pkg = mPackages.get(packageName);
3328            if (pkg == null) {
3329                throw new IllegalArgumentException("Unknown package: " + packageName);
3330            }
3331
3332            final BasePermission bp = mSettings.mPermissions.get(name);
3333            if (bp == null) {
3334                throw new IllegalArgumentException("Unknown permission: " + name);
3335            }
3336
3337            SettingBase sb = (SettingBase) pkg.mExtras;
3338            if (sb == null) {
3339                throw new IllegalArgumentException("Unknown package: " + packageName);
3340            }
3341
3342            PermissionsState permissionsState = sb.getPermissionsState();
3343
3344            // Only the package manager can change flags for system component permissions.
3345            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3346            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3347                return;
3348            }
3349
3350            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3351                // Install and runtime permissions are stored in different places,
3352                // so figure out what permission changed and persist the change.
3353                if (permissionsState.getInstallPermissionState(name) != null) {
3354                    scheduleWriteSettingsLocked();
3355                } else if (permissionsState.getRuntimePermissionState(name, userId) != null) {
3356                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3357                }
3358            }
3359        }
3360    }
3361
3362    @Override
3363    public boolean shouldShowRequestPermissionRationale(String permissionName,
3364            String packageName, int userId) {
3365        if (UserHandle.getCallingUserId() != userId) {
3366            mContext.enforceCallingPermission(
3367                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3368                    "canShowRequestPermissionRationale for user " + userId);
3369        }
3370
3371        final int uid = getPackageUid(packageName, userId);
3372        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3373            return false;
3374        }
3375
3376        if (checkPermission(permissionName, packageName, userId)
3377                == PackageManager.PERMISSION_GRANTED) {
3378            return false;
3379        }
3380
3381        final int flags;
3382
3383        final long identity = Binder.clearCallingIdentity();
3384        try {
3385            flags = getPermissionFlags(permissionName,
3386                    packageName, userId);
3387        } finally {
3388            Binder.restoreCallingIdentity(identity);
3389        }
3390
3391        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3392                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3393                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3394
3395        if ((flags & fixedFlags) != 0) {
3396            return false;
3397        }
3398
3399        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3400    }
3401
3402    @Override
3403    public boolean isProtectedBroadcast(String actionName) {
3404        synchronized (mPackages) {
3405            return mProtectedBroadcasts.contains(actionName);
3406        }
3407    }
3408
3409    @Override
3410    public int checkSignatures(String pkg1, String pkg2) {
3411        synchronized (mPackages) {
3412            final PackageParser.Package p1 = mPackages.get(pkg1);
3413            final PackageParser.Package p2 = mPackages.get(pkg2);
3414            if (p1 == null || p1.mExtras == null
3415                    || p2 == null || p2.mExtras == null) {
3416                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3417            }
3418            return compareSignatures(p1.mSignatures, p2.mSignatures);
3419        }
3420    }
3421
3422    @Override
3423    public int checkUidSignatures(int uid1, int uid2) {
3424        // Map to base uids.
3425        uid1 = UserHandle.getAppId(uid1);
3426        uid2 = UserHandle.getAppId(uid2);
3427        // reader
3428        synchronized (mPackages) {
3429            Signature[] s1;
3430            Signature[] s2;
3431            Object obj = mSettings.getUserIdLPr(uid1);
3432            if (obj != null) {
3433                if (obj instanceof SharedUserSetting) {
3434                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3435                } else if (obj instanceof PackageSetting) {
3436                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3437                } else {
3438                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3439                }
3440            } else {
3441                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3442            }
3443            obj = mSettings.getUserIdLPr(uid2);
3444            if (obj != null) {
3445                if (obj instanceof SharedUserSetting) {
3446                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3447                } else if (obj instanceof PackageSetting) {
3448                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3449                } else {
3450                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3451                }
3452            } else {
3453                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3454            }
3455            return compareSignatures(s1, s2);
3456        }
3457    }
3458
3459    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3460        final long identity = Binder.clearCallingIdentity();
3461        try {
3462            if (sb instanceof SharedUserSetting) {
3463                SharedUserSetting sus = (SharedUserSetting) sb;
3464                final int packageCount = sus.packages.size();
3465                for (int i = 0; i < packageCount; i++) {
3466                    PackageSetting susPs = sus.packages.valueAt(i);
3467                    if (userId == UserHandle.USER_ALL) {
3468                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3469                    } else {
3470                        final int uid = UserHandle.getUid(userId, susPs.appId);
3471                        killUid(uid, reason);
3472                    }
3473                }
3474            } else if (sb instanceof PackageSetting) {
3475                PackageSetting ps = (PackageSetting) sb;
3476                if (userId == UserHandle.USER_ALL) {
3477                    killApplication(ps.pkg.packageName, ps.appId, reason);
3478                } else {
3479                    final int uid = UserHandle.getUid(userId, ps.appId);
3480                    killUid(uid, reason);
3481                }
3482            }
3483        } finally {
3484            Binder.restoreCallingIdentity(identity);
3485        }
3486    }
3487
3488    private static void killUid(int uid, String reason) {
3489        IActivityManager am = ActivityManagerNative.getDefault();
3490        if (am != null) {
3491            try {
3492                am.killUid(uid, reason);
3493            } catch (RemoteException e) {
3494                /* ignore - same process */
3495            }
3496        }
3497    }
3498
3499    /**
3500     * Compares two sets of signatures. Returns:
3501     * <br />
3502     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3503     * <br />
3504     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3505     * <br />
3506     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3507     * <br />
3508     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3509     * <br />
3510     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3511     */
3512    static int compareSignatures(Signature[] s1, Signature[] s2) {
3513        if (s1 == null) {
3514            return s2 == null
3515                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3516                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3517        }
3518
3519        if (s2 == null) {
3520            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3521        }
3522
3523        if (s1.length != s2.length) {
3524            return PackageManager.SIGNATURE_NO_MATCH;
3525        }
3526
3527        // Since both signature sets are of size 1, we can compare without HashSets.
3528        if (s1.length == 1) {
3529            return s1[0].equals(s2[0]) ?
3530                    PackageManager.SIGNATURE_MATCH :
3531                    PackageManager.SIGNATURE_NO_MATCH;
3532        }
3533
3534        ArraySet<Signature> set1 = new ArraySet<Signature>();
3535        for (Signature sig : s1) {
3536            set1.add(sig);
3537        }
3538        ArraySet<Signature> set2 = new ArraySet<Signature>();
3539        for (Signature sig : s2) {
3540            set2.add(sig);
3541        }
3542        // Make sure s2 contains all signatures in s1.
3543        if (set1.equals(set2)) {
3544            return PackageManager.SIGNATURE_MATCH;
3545        }
3546        return PackageManager.SIGNATURE_NO_MATCH;
3547    }
3548
3549    /**
3550     * If the database version for this type of package (internal storage or
3551     * external storage) is less than the version where package signatures
3552     * were updated, return true.
3553     */
3554    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3555        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3556                DatabaseVersion.SIGNATURE_END_ENTITY))
3557                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3558                        DatabaseVersion.SIGNATURE_END_ENTITY));
3559    }
3560
3561    /**
3562     * Used for backward compatibility to make sure any packages with
3563     * certificate chains get upgraded to the new style. {@code existingSigs}
3564     * will be in the old format (since they were stored on disk from before the
3565     * system upgrade) and {@code scannedSigs} will be in the newer format.
3566     */
3567    private int compareSignaturesCompat(PackageSignatures existingSigs,
3568            PackageParser.Package scannedPkg) {
3569        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3570            return PackageManager.SIGNATURE_NO_MATCH;
3571        }
3572
3573        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3574        for (Signature sig : existingSigs.mSignatures) {
3575            existingSet.add(sig);
3576        }
3577        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3578        for (Signature sig : scannedPkg.mSignatures) {
3579            try {
3580                Signature[] chainSignatures = sig.getChainSignatures();
3581                for (Signature chainSig : chainSignatures) {
3582                    scannedCompatSet.add(chainSig);
3583                }
3584            } catch (CertificateEncodingException e) {
3585                scannedCompatSet.add(sig);
3586            }
3587        }
3588        /*
3589         * Make sure the expanded scanned set contains all signatures in the
3590         * existing one.
3591         */
3592        if (scannedCompatSet.equals(existingSet)) {
3593            // Migrate the old signatures to the new scheme.
3594            existingSigs.assignSignatures(scannedPkg.mSignatures);
3595            // The new KeySets will be re-added later in the scanning process.
3596            synchronized (mPackages) {
3597                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3598            }
3599            return PackageManager.SIGNATURE_MATCH;
3600        }
3601        return PackageManager.SIGNATURE_NO_MATCH;
3602    }
3603
3604    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3605        if (isExternal(scannedPkg)) {
3606            return mSettings.isExternalDatabaseVersionOlderThan(
3607                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3608        } else {
3609            return mSettings.isInternalDatabaseVersionOlderThan(
3610                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3611        }
3612    }
3613
3614    private int compareSignaturesRecover(PackageSignatures existingSigs,
3615            PackageParser.Package scannedPkg) {
3616        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3617            return PackageManager.SIGNATURE_NO_MATCH;
3618        }
3619
3620        String msg = null;
3621        try {
3622            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3623                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3624                        + scannedPkg.packageName);
3625                return PackageManager.SIGNATURE_MATCH;
3626            }
3627        } catch (CertificateException e) {
3628            msg = e.getMessage();
3629        }
3630
3631        logCriticalInfo(Log.INFO,
3632                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3633        return PackageManager.SIGNATURE_NO_MATCH;
3634    }
3635
3636    @Override
3637    public String[] getPackagesForUid(int uid) {
3638        uid = UserHandle.getAppId(uid);
3639        // reader
3640        synchronized (mPackages) {
3641            Object obj = mSettings.getUserIdLPr(uid);
3642            if (obj instanceof SharedUserSetting) {
3643                final SharedUserSetting sus = (SharedUserSetting) obj;
3644                final int N = sus.packages.size();
3645                final String[] res = new String[N];
3646                final Iterator<PackageSetting> it = sus.packages.iterator();
3647                int i = 0;
3648                while (it.hasNext()) {
3649                    res[i++] = it.next().name;
3650                }
3651                return res;
3652            } else if (obj instanceof PackageSetting) {
3653                final PackageSetting ps = (PackageSetting) obj;
3654                return new String[] { ps.name };
3655            }
3656        }
3657        return null;
3658    }
3659
3660    @Override
3661    public String getNameForUid(int uid) {
3662        // reader
3663        synchronized (mPackages) {
3664            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3665            if (obj instanceof SharedUserSetting) {
3666                final SharedUserSetting sus = (SharedUserSetting) obj;
3667                return sus.name + ":" + sus.userId;
3668            } else if (obj instanceof PackageSetting) {
3669                final PackageSetting ps = (PackageSetting) obj;
3670                return ps.name;
3671            }
3672        }
3673        return null;
3674    }
3675
3676    @Override
3677    public int getUidForSharedUser(String sharedUserName) {
3678        if(sharedUserName == null) {
3679            return -1;
3680        }
3681        // reader
3682        synchronized (mPackages) {
3683            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
3684            if (suid == null) {
3685                return -1;
3686            }
3687            return suid.userId;
3688        }
3689    }
3690
3691    @Override
3692    public int getFlagsForUid(int uid) {
3693        synchronized (mPackages) {
3694            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3695            if (obj instanceof SharedUserSetting) {
3696                final SharedUserSetting sus = (SharedUserSetting) obj;
3697                return sus.pkgFlags;
3698            } else if (obj instanceof PackageSetting) {
3699                final PackageSetting ps = (PackageSetting) obj;
3700                return ps.pkgFlags;
3701            }
3702        }
3703        return 0;
3704    }
3705
3706    @Override
3707    public int getPrivateFlagsForUid(int uid) {
3708        synchronized (mPackages) {
3709            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3710            if (obj instanceof SharedUserSetting) {
3711                final SharedUserSetting sus = (SharedUserSetting) obj;
3712                return sus.pkgPrivateFlags;
3713            } else if (obj instanceof PackageSetting) {
3714                final PackageSetting ps = (PackageSetting) obj;
3715                return ps.pkgPrivateFlags;
3716            }
3717        }
3718        return 0;
3719    }
3720
3721    @Override
3722    public boolean isUidPrivileged(int uid) {
3723        uid = UserHandle.getAppId(uid);
3724        // reader
3725        synchronized (mPackages) {
3726            Object obj = mSettings.getUserIdLPr(uid);
3727            if (obj instanceof SharedUserSetting) {
3728                final SharedUserSetting sus = (SharedUserSetting) obj;
3729                final Iterator<PackageSetting> it = sus.packages.iterator();
3730                while (it.hasNext()) {
3731                    if (it.next().isPrivileged()) {
3732                        return true;
3733                    }
3734                }
3735            } else if (obj instanceof PackageSetting) {
3736                final PackageSetting ps = (PackageSetting) obj;
3737                return ps.isPrivileged();
3738            }
3739        }
3740        return false;
3741    }
3742
3743    @Override
3744    public String[] getAppOpPermissionPackages(String permissionName) {
3745        synchronized (mPackages) {
3746            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
3747            if (pkgs == null) {
3748                return null;
3749            }
3750            return pkgs.toArray(new String[pkgs.size()]);
3751        }
3752    }
3753
3754    @Override
3755    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3756            int flags, int userId) {
3757        if (!sUserManager.exists(userId)) return null;
3758        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
3759        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3760        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3761    }
3762
3763    @Override
3764    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3765            IntentFilter filter, int match, ComponentName activity) {
3766        final int userId = UserHandle.getCallingUserId();
3767        if (DEBUG_PREFERRED) {
3768            Log.v(TAG, "setLastChosenActivity intent=" + intent
3769                + " resolvedType=" + resolvedType
3770                + " flags=" + flags
3771                + " filter=" + filter
3772                + " match=" + match
3773                + " activity=" + activity);
3774            filter.dump(new PrintStreamPrinter(System.out), "    ");
3775        }
3776        intent.setComponent(null);
3777        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3778        // Find any earlier preferred or last chosen entries and nuke them
3779        findPreferredActivity(intent, resolvedType,
3780                flags, query, 0, false, true, false, userId);
3781        // Add the new activity as the last chosen for this filter
3782        addPreferredActivityInternal(filter, match, null, activity, false, userId,
3783                "Setting last chosen");
3784    }
3785
3786    @Override
3787    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
3788        final int userId = UserHandle.getCallingUserId();
3789        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
3790        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3791        return findPreferredActivity(intent, resolvedType, flags, query, 0,
3792                false, false, false, userId);
3793    }
3794
3795    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
3796            int flags, List<ResolveInfo> query, int userId) {
3797        if (query != null) {
3798            final int N = query.size();
3799            if (N == 1) {
3800                return query.get(0);
3801            } else if (N > 1) {
3802                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3803                // If there is more than one activity with the same priority,
3804                // then let the user decide between them.
3805                ResolveInfo r0 = query.get(0);
3806                ResolveInfo r1 = query.get(1);
3807                if (DEBUG_INTENT_MATCHING || debug) {
3808                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
3809                            + r1.activityInfo.name + "=" + r1.priority);
3810                }
3811                // If the first activity has a higher priority, or a different
3812                // default, then it is always desireable to pick it.
3813                if (r0.priority != r1.priority
3814                        || r0.preferredOrder != r1.preferredOrder
3815                        || r0.isDefault != r1.isDefault) {
3816                    return query.get(0);
3817                }
3818                // If we have saved a preference for a preferred activity for
3819                // this Intent, use that.
3820                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3821                        flags, query, r0.priority, true, false, debug, userId);
3822                if (ri != null) {
3823                    return ri;
3824                }
3825                if (userId != 0) {
3826                    ri = new ResolveInfo(mResolveInfo);
3827                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3828                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3829                            ri.activityInfo.applicationInfo);
3830                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3831                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3832                    return ri;
3833                }
3834                return mResolveInfo;
3835            }
3836        }
3837        return null;
3838    }
3839
3840    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3841            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3842        final int N = query.size();
3843        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3844                .get(userId);
3845        // Get the list of persistent preferred activities that handle the intent
3846        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3847        List<PersistentPreferredActivity> pprefs = ppir != null
3848                ? ppir.queryIntent(intent, resolvedType,
3849                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3850                : null;
3851        if (pprefs != null && pprefs.size() > 0) {
3852            final int M = pprefs.size();
3853            for (int i=0; i<M; i++) {
3854                final PersistentPreferredActivity ppa = pprefs.get(i);
3855                if (DEBUG_PREFERRED || debug) {
3856                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3857                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3858                            + "\n  component=" + ppa.mComponent);
3859                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3860                }
3861                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3862                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3863                if (DEBUG_PREFERRED || debug) {
3864                    Slog.v(TAG, "Found persistent preferred activity:");
3865                    if (ai != null) {
3866                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3867                    } else {
3868                        Slog.v(TAG, "  null");
3869                    }
3870                }
3871                if (ai == null) {
3872                    // This previously registered persistent preferred activity
3873                    // component is no longer known. Ignore it and do NOT remove it.
3874                    continue;
3875                }
3876                for (int j=0; j<N; j++) {
3877                    final ResolveInfo ri = query.get(j);
3878                    if (!ri.activityInfo.applicationInfo.packageName
3879                            .equals(ai.applicationInfo.packageName)) {
3880                        continue;
3881                    }
3882                    if (!ri.activityInfo.name.equals(ai.name)) {
3883                        continue;
3884                    }
3885                    //  Found a persistent preference that can handle the intent.
3886                    if (DEBUG_PREFERRED || debug) {
3887                        Slog.v(TAG, "Returning persistent preferred activity: " +
3888                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3889                    }
3890                    return ri;
3891                }
3892            }
3893        }
3894        return null;
3895    }
3896
3897    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3898            List<ResolveInfo> query, int priority, boolean always,
3899            boolean removeMatches, boolean debug, int userId) {
3900        if (!sUserManager.exists(userId)) return null;
3901        // writer
3902        synchronized (mPackages) {
3903            if (intent.getSelector() != null) {
3904                intent = intent.getSelector();
3905            }
3906            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3907
3908            // Try to find a matching persistent preferred activity.
3909            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3910                    debug, userId);
3911
3912            // If a persistent preferred activity matched, use it.
3913            if (pri != null) {
3914                return pri;
3915            }
3916
3917            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3918            // Get the list of preferred activities that handle the intent
3919            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3920            List<PreferredActivity> prefs = pir != null
3921                    ? pir.queryIntent(intent, resolvedType,
3922                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3923                    : null;
3924            if (prefs != null && prefs.size() > 0) {
3925                boolean changed = false;
3926                try {
3927                    // First figure out how good the original match set is.
3928                    // We will only allow preferred activities that came
3929                    // from the same match quality.
3930                    int match = 0;
3931
3932                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3933
3934                    final int N = query.size();
3935                    for (int j=0; j<N; j++) {
3936                        final ResolveInfo ri = query.get(j);
3937                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3938                                + ": 0x" + Integer.toHexString(match));
3939                        if (ri.match > match) {
3940                            match = ri.match;
3941                        }
3942                    }
3943
3944                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3945                            + Integer.toHexString(match));
3946
3947                    match &= IntentFilter.MATCH_CATEGORY_MASK;
3948                    final int M = prefs.size();
3949                    for (int i=0; i<M; i++) {
3950                        final PreferredActivity pa = prefs.get(i);
3951                        if (DEBUG_PREFERRED || debug) {
3952                            Slog.v(TAG, "Checking PreferredActivity ds="
3953                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3954                                    + "\n  component=" + pa.mPref.mComponent);
3955                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3956                        }
3957                        if (pa.mPref.mMatch != match) {
3958                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3959                                    + Integer.toHexString(pa.mPref.mMatch));
3960                            continue;
3961                        }
3962                        // If it's not an "always" type preferred activity and that's what we're
3963                        // looking for, skip it.
3964                        if (always && !pa.mPref.mAlways) {
3965                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3966                            continue;
3967                        }
3968                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3969                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3970                        if (DEBUG_PREFERRED || debug) {
3971                            Slog.v(TAG, "Found preferred activity:");
3972                            if (ai != null) {
3973                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3974                            } else {
3975                                Slog.v(TAG, "  null");
3976                            }
3977                        }
3978                        if (ai == null) {
3979                            // This previously registered preferred activity
3980                            // component is no longer known.  Most likely an update
3981                            // to the app was installed and in the new version this
3982                            // component no longer exists.  Clean it up by removing
3983                            // it from the preferred activities list, and skip it.
3984                            Slog.w(TAG, "Removing dangling preferred activity: "
3985                                    + pa.mPref.mComponent);
3986                            pir.removeFilter(pa);
3987                            changed = true;
3988                            continue;
3989                        }
3990                        for (int j=0; j<N; j++) {
3991                            final ResolveInfo ri = query.get(j);
3992                            if (!ri.activityInfo.applicationInfo.packageName
3993                                    .equals(ai.applicationInfo.packageName)) {
3994                                continue;
3995                            }
3996                            if (!ri.activityInfo.name.equals(ai.name)) {
3997                                continue;
3998                            }
3999
4000                            if (removeMatches) {
4001                                pir.removeFilter(pa);
4002                                changed = true;
4003                                if (DEBUG_PREFERRED) {
4004                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4005                                }
4006                                break;
4007                            }
4008
4009                            // Okay we found a previously set preferred or last chosen app.
4010                            // If the result set is different from when this
4011                            // was created, we need to clear it and re-ask the
4012                            // user their preference, if we're looking for an "always" type entry.
4013                            if (always && !pa.mPref.sameSet(query)) {
4014                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4015                                        + intent + " type " + resolvedType);
4016                                if (DEBUG_PREFERRED) {
4017                                    Slog.v(TAG, "Removing preferred activity since set changed "
4018                                            + pa.mPref.mComponent);
4019                                }
4020                                pir.removeFilter(pa);
4021                                // Re-add the filter as a "last chosen" entry (!always)
4022                                PreferredActivity lastChosen = new PreferredActivity(
4023                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4024                                pir.addFilter(lastChosen);
4025                                changed = true;
4026                                return null;
4027                            }
4028
4029                            // Yay! Either the set matched or we're looking for the last chosen
4030                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4031                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4032                            return ri;
4033                        }
4034                    }
4035                } finally {
4036                    if (changed) {
4037                        if (DEBUG_PREFERRED) {
4038                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4039                        }
4040                        scheduleWritePackageRestrictionsLocked(userId);
4041                    }
4042                }
4043            }
4044        }
4045        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4046        return null;
4047    }
4048
4049    /*
4050     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4051     */
4052    @Override
4053    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4054            int targetUserId) {
4055        mContext.enforceCallingOrSelfPermission(
4056                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4057        List<CrossProfileIntentFilter> matches =
4058                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4059        if (matches != null) {
4060            int size = matches.size();
4061            for (int i = 0; i < size; i++) {
4062                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4063            }
4064        }
4065        return false;
4066    }
4067
4068    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4069            String resolvedType, int userId) {
4070        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4071        if (resolver != null) {
4072            return resolver.queryIntent(intent, resolvedType, false, userId);
4073        }
4074        return null;
4075    }
4076
4077    @Override
4078    public List<ResolveInfo> queryIntentActivities(Intent intent,
4079            String resolvedType, int flags, int userId) {
4080        if (!sUserManager.exists(userId)) return Collections.emptyList();
4081        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4082        ComponentName comp = intent.getComponent();
4083        if (comp == null) {
4084            if (intent.getSelector() != null) {
4085                intent = intent.getSelector();
4086                comp = intent.getComponent();
4087            }
4088        }
4089
4090        if (comp != null) {
4091            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4092            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4093            if (ai != null) {
4094                final ResolveInfo ri = new ResolveInfo();
4095                ri.activityInfo = ai;
4096                list.add(ri);
4097            }
4098            return list;
4099        }
4100
4101        // reader
4102        synchronized (mPackages) {
4103            final String pkgName = intent.getPackage();
4104            if (pkgName == null) {
4105                List<CrossProfileIntentFilter> matchingFilters =
4106                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4107                // Check for results that need to skip the current profile.
4108                ResolveInfo resolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4109                        resolvedType, flags, userId);
4110                if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) {
4111                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4112                    result.add(resolveInfo);
4113                    return filterIfNotPrimaryUser(result, userId);
4114                }
4115
4116                // Check for results in the current profile.
4117                List<ResolveInfo> result = mActivities.queryIntent(
4118                        intent, resolvedType, flags, userId);
4119
4120                // Check for cross profile results.
4121                resolveInfo = queryCrossProfileIntents(
4122                        matchingFilters, intent, resolvedType, flags, userId);
4123                if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) {
4124                    result.add(resolveInfo);
4125                    Collections.sort(result, mResolvePrioritySorter);
4126                }
4127                result = filterIfNotPrimaryUser(result, userId);
4128                if (result.size() > 1 && hasWebURI(intent)) {
4129                    return filterCandidatesWithDomainPreferedActivitiesLPr(flags, result);
4130                }
4131                return result;
4132            }
4133            final PackageParser.Package pkg = mPackages.get(pkgName);
4134            if (pkg != null) {
4135                return filterIfNotPrimaryUser(
4136                        mActivities.queryIntentForPackage(
4137                                intent, resolvedType, flags, pkg.activities, userId),
4138                        userId);
4139            }
4140            return new ArrayList<ResolveInfo>();
4141        }
4142    }
4143
4144    private boolean isUserEnabled(int userId) {
4145        long callingId = Binder.clearCallingIdentity();
4146        try {
4147            UserInfo userInfo = sUserManager.getUserInfo(userId);
4148            return userInfo != null && userInfo.isEnabled();
4149        } finally {
4150            Binder.restoreCallingIdentity(callingId);
4151        }
4152    }
4153
4154    /**
4155     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4156     *
4157     * @return filtered list
4158     */
4159    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4160        if (userId == UserHandle.USER_OWNER) {
4161            return resolveInfos;
4162        }
4163        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4164            ResolveInfo info = resolveInfos.get(i);
4165            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4166                resolveInfos.remove(i);
4167            }
4168        }
4169        return resolveInfos;
4170    }
4171
4172    private static boolean hasWebURI(Intent intent) {
4173        if (intent.getData() == null) {
4174            return false;
4175        }
4176        final String scheme = intent.getScheme();
4177        if (TextUtils.isEmpty(scheme)) {
4178            return false;
4179        }
4180        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4181    }
4182
4183    private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPr(
4184            int flags, List<ResolveInfo> candidates) {
4185        if (DEBUG_PREFERRED) {
4186            Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " +
4187                    candidates.size());
4188        }
4189
4190        final int userId = UserHandle.getCallingUserId();
4191        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4192        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4193        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4194        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4195        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4196
4197        synchronized (mPackages) {
4198            final int count = candidates.size();
4199            // First, try to use the domain prefered App. Partition the candidates into four lists:
4200            // one for the final results, one for the "do not use ever", one for "undefined status"
4201            // and finally one for "Browser App type".
4202            for (int n=0; n<count; n++) {
4203                ResolveInfo info = candidates.get(n);
4204                String packageName = info.activityInfo.packageName;
4205                PackageSetting ps = mSettings.mPackages.get(packageName);
4206                if (ps != null) {
4207                    // Add to the special match all list (Browser use case)
4208                    if (info.handleAllWebDataURI) {
4209                        matchAllList.add(info);
4210                        continue;
4211                    }
4212                    // Try to get the status from User settings first
4213                    int status = getDomainVerificationStatusLPr(ps, userId);
4214                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4215                        alwaysList.add(info);
4216                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4217                        neverList.add(info);
4218                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4219                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4220                        undefinedList.add(info);
4221                    }
4222                }
4223            }
4224            // First try to add the "always" if there is any
4225            if (alwaysList.size() > 0) {
4226                result.addAll(alwaysList);
4227            } else {
4228                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4229                result.addAll(undefinedList);
4230                // Also add Browsers (all of them or only the default one)
4231                if ((flags & MATCH_ALL) != 0) {
4232                    result.addAll(matchAllList);
4233                } else {
4234                    // Try to add the Default Browser if we can
4235                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(
4236                            UserHandle.myUserId());
4237                    if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
4238                        boolean defaultBrowserFound = false;
4239                        final int browserCount = matchAllList.size();
4240                        for (int n=0; n<browserCount; n++) {
4241                            ResolveInfo browser = matchAllList.get(n);
4242                            if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4243                                result.add(browser);
4244                                defaultBrowserFound = true;
4245                                break;
4246                            }
4247                        }
4248                        if (!defaultBrowserFound) {
4249                            result.addAll(matchAllList);
4250                        }
4251                    } else {
4252                        result.addAll(matchAllList);
4253                    }
4254                }
4255
4256                // If there is nothing selected, add all candidates and remove the ones that the User
4257                // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4258                if (result.size() == 0) {
4259                    result.addAll(candidates);
4260                    result.removeAll(neverList);
4261                }
4262            }
4263        }
4264        if (DEBUG_PREFERRED) {
4265            Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " +
4266                    result.size());
4267        }
4268        return result;
4269    }
4270
4271    private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4272        int status = ps.getDomainVerificationStatusForUser(userId);
4273        // if none available, get the master status
4274        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4275            if (ps.getIntentFilterVerificationInfo() != null) {
4276                status = ps.getIntentFilterVerificationInfo().getStatus();
4277            }
4278        }
4279        return status;
4280    }
4281
4282    private ResolveInfo querySkipCurrentProfileIntents(
4283            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4284            int flags, int sourceUserId) {
4285        if (matchingFilters != null) {
4286            int size = matchingFilters.size();
4287            for (int i = 0; i < size; i ++) {
4288                CrossProfileIntentFilter filter = matchingFilters.get(i);
4289                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4290                    // Checking if there are activities in the target user that can handle the
4291                    // intent.
4292                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4293                            flags, sourceUserId);
4294                    if (resolveInfo != null) {
4295                        return resolveInfo;
4296                    }
4297                }
4298            }
4299        }
4300        return null;
4301    }
4302
4303    // Return matching ResolveInfo if any for skip current profile intent filters.
4304    private ResolveInfo queryCrossProfileIntents(
4305            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4306            int flags, int sourceUserId) {
4307        if (matchingFilters != null) {
4308            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4309            // match the same intent. For performance reasons, it is better not to
4310            // run queryIntent twice for the same userId
4311            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4312            int size = matchingFilters.size();
4313            for (int i = 0; i < size; i++) {
4314                CrossProfileIntentFilter filter = matchingFilters.get(i);
4315                int targetUserId = filter.getTargetUserId();
4316                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4317                        && !alreadyTriedUserIds.get(targetUserId)) {
4318                    // Checking if there are activities in the target user that can handle the
4319                    // intent.
4320                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4321                            flags, sourceUserId);
4322                    if (resolveInfo != null) return resolveInfo;
4323                    alreadyTriedUserIds.put(targetUserId, true);
4324                }
4325            }
4326        }
4327        return null;
4328    }
4329
4330    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4331            String resolvedType, int flags, int sourceUserId) {
4332        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4333                resolvedType, flags, filter.getTargetUserId());
4334        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4335            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4336        }
4337        return null;
4338    }
4339
4340    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4341            int sourceUserId, int targetUserId) {
4342        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4343        String className;
4344        if (targetUserId == UserHandle.USER_OWNER) {
4345            className = FORWARD_INTENT_TO_USER_OWNER;
4346        } else {
4347            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4348        }
4349        ComponentName forwardingActivityComponentName = new ComponentName(
4350                mAndroidApplication.packageName, className);
4351        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4352                sourceUserId);
4353        if (targetUserId == UserHandle.USER_OWNER) {
4354            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4355            forwardingResolveInfo.noResourceId = true;
4356        }
4357        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4358        forwardingResolveInfo.priority = 0;
4359        forwardingResolveInfo.preferredOrder = 0;
4360        forwardingResolveInfo.match = 0;
4361        forwardingResolveInfo.isDefault = true;
4362        forwardingResolveInfo.filter = filter;
4363        forwardingResolveInfo.targetUserId = targetUserId;
4364        return forwardingResolveInfo;
4365    }
4366
4367    @Override
4368    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4369            Intent[] specifics, String[] specificTypes, Intent intent,
4370            String resolvedType, int flags, int userId) {
4371        if (!sUserManager.exists(userId)) return Collections.emptyList();
4372        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4373                false, "query intent activity options");
4374        final String resultsAction = intent.getAction();
4375
4376        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4377                | PackageManager.GET_RESOLVED_FILTER, userId);
4378
4379        if (DEBUG_INTENT_MATCHING) {
4380            Log.v(TAG, "Query " + intent + ": " + results);
4381        }
4382
4383        int specificsPos = 0;
4384        int N;
4385
4386        // todo: note that the algorithm used here is O(N^2).  This
4387        // isn't a problem in our current environment, but if we start running
4388        // into situations where we have more than 5 or 10 matches then this
4389        // should probably be changed to something smarter...
4390
4391        // First we go through and resolve each of the specific items
4392        // that were supplied, taking care of removing any corresponding
4393        // duplicate items in the generic resolve list.
4394        if (specifics != null) {
4395            for (int i=0; i<specifics.length; i++) {
4396                final Intent sintent = specifics[i];
4397                if (sintent == null) {
4398                    continue;
4399                }
4400
4401                if (DEBUG_INTENT_MATCHING) {
4402                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4403                }
4404
4405                String action = sintent.getAction();
4406                if (resultsAction != null && resultsAction.equals(action)) {
4407                    // If this action was explicitly requested, then don't
4408                    // remove things that have it.
4409                    action = null;
4410                }
4411
4412                ResolveInfo ri = null;
4413                ActivityInfo ai = null;
4414
4415                ComponentName comp = sintent.getComponent();
4416                if (comp == null) {
4417                    ri = resolveIntent(
4418                        sintent,
4419                        specificTypes != null ? specificTypes[i] : null,
4420                            flags, userId);
4421                    if (ri == null) {
4422                        continue;
4423                    }
4424                    if (ri == mResolveInfo) {
4425                        // ACK!  Must do something better with this.
4426                    }
4427                    ai = ri.activityInfo;
4428                    comp = new ComponentName(ai.applicationInfo.packageName,
4429                            ai.name);
4430                } else {
4431                    ai = getActivityInfo(comp, flags, userId);
4432                    if (ai == null) {
4433                        continue;
4434                    }
4435                }
4436
4437                // Look for any generic query activities that are duplicates
4438                // of this specific one, and remove them from the results.
4439                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4440                N = results.size();
4441                int j;
4442                for (j=specificsPos; j<N; j++) {
4443                    ResolveInfo sri = results.get(j);
4444                    if ((sri.activityInfo.name.equals(comp.getClassName())
4445                            && sri.activityInfo.applicationInfo.packageName.equals(
4446                                    comp.getPackageName()))
4447                        || (action != null && sri.filter.matchAction(action))) {
4448                        results.remove(j);
4449                        if (DEBUG_INTENT_MATCHING) Log.v(
4450                            TAG, "Removing duplicate item from " + j
4451                            + " due to specific " + specificsPos);
4452                        if (ri == null) {
4453                            ri = sri;
4454                        }
4455                        j--;
4456                        N--;
4457                    }
4458                }
4459
4460                // Add this specific item to its proper place.
4461                if (ri == null) {
4462                    ri = new ResolveInfo();
4463                    ri.activityInfo = ai;
4464                }
4465                results.add(specificsPos, ri);
4466                ri.specificIndex = i;
4467                specificsPos++;
4468            }
4469        }
4470
4471        // Now we go through the remaining generic results and remove any
4472        // duplicate actions that are found here.
4473        N = results.size();
4474        for (int i=specificsPos; i<N-1; i++) {
4475            final ResolveInfo rii = results.get(i);
4476            if (rii.filter == null) {
4477                continue;
4478            }
4479
4480            // Iterate over all of the actions of this result's intent
4481            // filter...  typically this should be just one.
4482            final Iterator<String> it = rii.filter.actionsIterator();
4483            if (it == null) {
4484                continue;
4485            }
4486            while (it.hasNext()) {
4487                final String action = it.next();
4488                if (resultsAction != null && resultsAction.equals(action)) {
4489                    // If this action was explicitly requested, then don't
4490                    // remove things that have it.
4491                    continue;
4492                }
4493                for (int j=i+1; j<N; j++) {
4494                    final ResolveInfo rij = results.get(j);
4495                    if (rij.filter != null && rij.filter.hasAction(action)) {
4496                        results.remove(j);
4497                        if (DEBUG_INTENT_MATCHING) Log.v(
4498                            TAG, "Removing duplicate item from " + j
4499                            + " due to action " + action + " at " + i);
4500                        j--;
4501                        N--;
4502                    }
4503                }
4504            }
4505
4506            // If the caller didn't request filter information, drop it now
4507            // so we don't have to marshall/unmarshall it.
4508            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4509                rii.filter = null;
4510            }
4511        }
4512
4513        // Filter out the caller activity if so requested.
4514        if (caller != null) {
4515            N = results.size();
4516            for (int i=0; i<N; i++) {
4517                ActivityInfo ainfo = results.get(i).activityInfo;
4518                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
4519                        && caller.getClassName().equals(ainfo.name)) {
4520                    results.remove(i);
4521                    break;
4522                }
4523            }
4524        }
4525
4526        // If the caller didn't request filter information,
4527        // drop them now so we don't have to
4528        // marshall/unmarshall it.
4529        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4530            N = results.size();
4531            for (int i=0; i<N; i++) {
4532                results.get(i).filter = null;
4533            }
4534        }
4535
4536        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
4537        return results;
4538    }
4539
4540    @Override
4541    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
4542            int userId) {
4543        if (!sUserManager.exists(userId)) return Collections.emptyList();
4544        ComponentName comp = intent.getComponent();
4545        if (comp == null) {
4546            if (intent.getSelector() != null) {
4547                intent = intent.getSelector();
4548                comp = intent.getComponent();
4549            }
4550        }
4551        if (comp != null) {
4552            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4553            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
4554            if (ai != null) {
4555                ResolveInfo ri = new ResolveInfo();
4556                ri.activityInfo = ai;
4557                list.add(ri);
4558            }
4559            return list;
4560        }
4561
4562        // reader
4563        synchronized (mPackages) {
4564            String pkgName = intent.getPackage();
4565            if (pkgName == null) {
4566                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
4567            }
4568            final PackageParser.Package pkg = mPackages.get(pkgName);
4569            if (pkg != null) {
4570                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
4571                        userId);
4572            }
4573            return null;
4574        }
4575    }
4576
4577    @Override
4578    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
4579        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
4580        if (!sUserManager.exists(userId)) return null;
4581        if (query != null) {
4582            if (query.size() >= 1) {
4583                // If there is more than one service with the same priority,
4584                // just arbitrarily pick the first one.
4585                return query.get(0);
4586            }
4587        }
4588        return null;
4589    }
4590
4591    @Override
4592    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
4593            int userId) {
4594        if (!sUserManager.exists(userId)) return Collections.emptyList();
4595        ComponentName comp = intent.getComponent();
4596        if (comp == null) {
4597            if (intent.getSelector() != null) {
4598                intent = intent.getSelector();
4599                comp = intent.getComponent();
4600            }
4601        }
4602        if (comp != null) {
4603            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4604            final ServiceInfo si = getServiceInfo(comp, flags, userId);
4605            if (si != null) {
4606                final ResolveInfo ri = new ResolveInfo();
4607                ri.serviceInfo = si;
4608                list.add(ri);
4609            }
4610            return list;
4611        }
4612
4613        // reader
4614        synchronized (mPackages) {
4615            String pkgName = intent.getPackage();
4616            if (pkgName == null) {
4617                return mServices.queryIntent(intent, resolvedType, flags, userId);
4618            }
4619            final PackageParser.Package pkg = mPackages.get(pkgName);
4620            if (pkg != null) {
4621                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
4622                        userId);
4623            }
4624            return null;
4625        }
4626    }
4627
4628    @Override
4629    public List<ResolveInfo> queryIntentContentProviders(
4630            Intent intent, String resolvedType, int flags, int userId) {
4631        if (!sUserManager.exists(userId)) return Collections.emptyList();
4632        ComponentName comp = intent.getComponent();
4633        if (comp == null) {
4634            if (intent.getSelector() != null) {
4635                intent = intent.getSelector();
4636                comp = intent.getComponent();
4637            }
4638        }
4639        if (comp != null) {
4640            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4641            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
4642            if (pi != null) {
4643                final ResolveInfo ri = new ResolveInfo();
4644                ri.providerInfo = pi;
4645                list.add(ri);
4646            }
4647            return list;
4648        }
4649
4650        // reader
4651        synchronized (mPackages) {
4652            String pkgName = intent.getPackage();
4653            if (pkgName == null) {
4654                return mProviders.queryIntent(intent, resolvedType, flags, userId);
4655            }
4656            final PackageParser.Package pkg = mPackages.get(pkgName);
4657            if (pkg != null) {
4658                return mProviders.queryIntentForPackage(
4659                        intent, resolvedType, flags, pkg.providers, userId);
4660            }
4661            return null;
4662        }
4663    }
4664
4665    @Override
4666    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
4667        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4668
4669        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
4670
4671        // writer
4672        synchronized (mPackages) {
4673            ArrayList<PackageInfo> list;
4674            if (listUninstalled) {
4675                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
4676                for (PackageSetting ps : mSettings.mPackages.values()) {
4677                    PackageInfo pi;
4678                    if (ps.pkg != null) {
4679                        pi = generatePackageInfo(ps.pkg, flags, userId);
4680                    } else {
4681                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4682                    }
4683                    if (pi != null) {
4684                        list.add(pi);
4685                    }
4686                }
4687            } else {
4688                list = new ArrayList<PackageInfo>(mPackages.size());
4689                for (PackageParser.Package p : mPackages.values()) {
4690                    PackageInfo pi = generatePackageInfo(p, flags, userId);
4691                    if (pi != null) {
4692                        list.add(pi);
4693                    }
4694                }
4695            }
4696
4697            return new ParceledListSlice<PackageInfo>(list);
4698        }
4699    }
4700
4701    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
4702            String[] permissions, boolean[] tmp, int flags, int userId) {
4703        int numMatch = 0;
4704        final PermissionsState permissionsState = ps.getPermissionsState();
4705        for (int i=0; i<permissions.length; i++) {
4706            final String permission = permissions[i];
4707            if (permissionsState.hasPermission(permission, userId)) {
4708                tmp[i] = true;
4709                numMatch++;
4710            } else {
4711                tmp[i] = false;
4712            }
4713        }
4714        if (numMatch == 0) {
4715            return;
4716        }
4717        PackageInfo pi;
4718        if (ps.pkg != null) {
4719            pi = generatePackageInfo(ps.pkg, flags, userId);
4720        } else {
4721            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4722        }
4723        // The above might return null in cases of uninstalled apps or install-state
4724        // skew across users/profiles.
4725        if (pi != null) {
4726            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
4727                if (numMatch == permissions.length) {
4728                    pi.requestedPermissions = permissions;
4729                } else {
4730                    pi.requestedPermissions = new String[numMatch];
4731                    numMatch = 0;
4732                    for (int i=0; i<permissions.length; i++) {
4733                        if (tmp[i]) {
4734                            pi.requestedPermissions[numMatch] = permissions[i];
4735                            numMatch++;
4736                        }
4737                    }
4738                }
4739            }
4740            list.add(pi);
4741        }
4742    }
4743
4744    @Override
4745    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
4746            String[] permissions, int flags, int userId) {
4747        if (!sUserManager.exists(userId)) return null;
4748        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4749
4750        // writer
4751        synchronized (mPackages) {
4752            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
4753            boolean[] tmpBools = new boolean[permissions.length];
4754            if (listUninstalled) {
4755                for (PackageSetting ps : mSettings.mPackages.values()) {
4756                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
4757                }
4758            } else {
4759                for (PackageParser.Package pkg : mPackages.values()) {
4760                    PackageSetting ps = (PackageSetting)pkg.mExtras;
4761                    if (ps != null) {
4762                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
4763                                userId);
4764                    }
4765                }
4766            }
4767
4768            return new ParceledListSlice<PackageInfo>(list);
4769        }
4770    }
4771
4772    @Override
4773    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
4774        if (!sUserManager.exists(userId)) return null;
4775        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4776
4777        // writer
4778        synchronized (mPackages) {
4779            ArrayList<ApplicationInfo> list;
4780            if (listUninstalled) {
4781                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
4782                for (PackageSetting ps : mSettings.mPackages.values()) {
4783                    ApplicationInfo ai;
4784                    if (ps.pkg != null) {
4785                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4786                                ps.readUserState(userId), userId);
4787                    } else {
4788                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
4789                    }
4790                    if (ai != null) {
4791                        list.add(ai);
4792                    }
4793                }
4794            } else {
4795                list = new ArrayList<ApplicationInfo>(mPackages.size());
4796                for (PackageParser.Package p : mPackages.values()) {
4797                    if (p.mExtras != null) {
4798                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4799                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
4800                        if (ai != null) {
4801                            list.add(ai);
4802                        }
4803                    }
4804                }
4805            }
4806
4807            return new ParceledListSlice<ApplicationInfo>(list);
4808        }
4809    }
4810
4811    public List<ApplicationInfo> getPersistentApplications(int flags) {
4812        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
4813
4814        // reader
4815        synchronized (mPackages) {
4816            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
4817            final int userId = UserHandle.getCallingUserId();
4818            while (i.hasNext()) {
4819                final PackageParser.Package p = i.next();
4820                if (p.applicationInfo != null
4821                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
4822                        && (!mSafeMode || isSystemApp(p))) {
4823                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
4824                    if (ps != null) {
4825                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4826                                ps.readUserState(userId), userId);
4827                        if (ai != null) {
4828                            finalList.add(ai);
4829                        }
4830                    }
4831                }
4832            }
4833        }
4834
4835        return finalList;
4836    }
4837
4838    @Override
4839    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
4840        if (!sUserManager.exists(userId)) return null;
4841        // reader
4842        synchronized (mPackages) {
4843            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
4844            PackageSetting ps = provider != null
4845                    ? mSettings.mPackages.get(provider.owner.packageName)
4846                    : null;
4847            return ps != null
4848                    && mSettings.isEnabledLPr(provider.info, flags, userId)
4849                    && (!mSafeMode || (provider.info.applicationInfo.flags
4850                            &ApplicationInfo.FLAG_SYSTEM) != 0)
4851                    ? PackageParser.generateProviderInfo(provider, flags,
4852                            ps.readUserState(userId), userId)
4853                    : null;
4854        }
4855    }
4856
4857    /**
4858     * @deprecated
4859     */
4860    @Deprecated
4861    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
4862        // reader
4863        synchronized (mPackages) {
4864            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
4865                    .entrySet().iterator();
4866            final int userId = UserHandle.getCallingUserId();
4867            while (i.hasNext()) {
4868                Map.Entry<String, PackageParser.Provider> entry = i.next();
4869                PackageParser.Provider p = entry.getValue();
4870                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4871
4872                if (ps != null && p.syncable
4873                        && (!mSafeMode || (p.info.applicationInfo.flags
4874                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
4875                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
4876                            ps.readUserState(userId), userId);
4877                    if (info != null) {
4878                        outNames.add(entry.getKey());
4879                        outInfo.add(info);
4880                    }
4881                }
4882            }
4883        }
4884    }
4885
4886    @Override
4887    public List<ProviderInfo> queryContentProviders(String processName,
4888            int uid, int flags) {
4889        ArrayList<ProviderInfo> finalList = null;
4890        // reader
4891        synchronized (mPackages) {
4892            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
4893            final int userId = processName != null ?
4894                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
4895            while (i.hasNext()) {
4896                final PackageParser.Provider p = i.next();
4897                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4898                if (ps != null && p.info.authority != null
4899                        && (processName == null
4900                                || (p.info.processName.equals(processName)
4901                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
4902                        && mSettings.isEnabledLPr(p.info, flags, userId)
4903                        && (!mSafeMode
4904                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
4905                    if (finalList == null) {
4906                        finalList = new ArrayList<ProviderInfo>(3);
4907                    }
4908                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
4909                            ps.readUserState(userId), userId);
4910                    if (info != null) {
4911                        finalList.add(info);
4912                    }
4913                }
4914            }
4915        }
4916
4917        if (finalList != null) {
4918            Collections.sort(finalList, mProviderInitOrderSorter);
4919        }
4920
4921        return finalList;
4922    }
4923
4924    @Override
4925    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
4926            int flags) {
4927        // reader
4928        synchronized (mPackages) {
4929            final PackageParser.Instrumentation i = mInstrumentation.get(name);
4930            return PackageParser.generateInstrumentationInfo(i, flags);
4931        }
4932    }
4933
4934    @Override
4935    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4936            int flags) {
4937        ArrayList<InstrumentationInfo> finalList =
4938            new ArrayList<InstrumentationInfo>();
4939
4940        // reader
4941        synchronized (mPackages) {
4942            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4943            while (i.hasNext()) {
4944                final PackageParser.Instrumentation p = i.next();
4945                if (targetPackage == null
4946                        || targetPackage.equals(p.info.targetPackage)) {
4947                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4948                            flags);
4949                    if (ii != null) {
4950                        finalList.add(ii);
4951                    }
4952                }
4953            }
4954        }
4955
4956        return finalList;
4957    }
4958
4959    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4960        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4961        if (overlays == null) {
4962            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4963            return;
4964        }
4965        for (PackageParser.Package opkg : overlays.values()) {
4966            // Not much to do if idmap fails: we already logged the error
4967            // and we certainly don't want to abort installation of pkg simply
4968            // because an overlay didn't fit properly. For these reasons,
4969            // ignore the return value of createIdmapForPackagePairLI.
4970            createIdmapForPackagePairLI(pkg, opkg);
4971        }
4972    }
4973
4974    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4975            PackageParser.Package opkg) {
4976        if (!opkg.mTrustedOverlay) {
4977            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
4978                    opkg.baseCodePath + ": overlay not trusted");
4979            return false;
4980        }
4981        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4982        if (overlaySet == null) {
4983            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
4984                    opkg.baseCodePath + " but target package has no known overlays");
4985            return false;
4986        }
4987        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4988        // TODO: generate idmap for split APKs
4989        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
4990            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
4991                    + opkg.baseCodePath);
4992            return false;
4993        }
4994        PackageParser.Package[] overlayArray =
4995            overlaySet.values().toArray(new PackageParser.Package[0]);
4996        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4997            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4998                return p1.mOverlayPriority - p2.mOverlayPriority;
4999            }
5000        };
5001        Arrays.sort(overlayArray, cmp);
5002
5003        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5004        int i = 0;
5005        for (PackageParser.Package p : overlayArray) {
5006            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5007        }
5008        return true;
5009    }
5010
5011    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5012        final File[] files = dir.listFiles();
5013        if (ArrayUtils.isEmpty(files)) {
5014            Log.d(TAG, "No files in app dir " + dir);
5015            return;
5016        }
5017
5018        if (DEBUG_PACKAGE_SCANNING) {
5019            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5020                    + " flags=0x" + Integer.toHexString(parseFlags));
5021        }
5022
5023        for (File file : files) {
5024            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5025                    && !PackageInstallerService.isStageName(file.getName());
5026            if (!isPackage) {
5027                // Ignore entries which are not packages
5028                continue;
5029            }
5030            try {
5031                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5032                        scanFlags, currentTime, null);
5033            } catch (PackageManagerException e) {
5034                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5035
5036                // Delete invalid userdata apps
5037                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5038                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5039                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5040                    if (file.isDirectory()) {
5041                        mInstaller.rmPackageDir(file.getAbsolutePath());
5042                    } else {
5043                        file.delete();
5044                    }
5045                }
5046            }
5047        }
5048    }
5049
5050    private static File getSettingsProblemFile() {
5051        File dataDir = Environment.getDataDirectory();
5052        File systemDir = new File(dataDir, "system");
5053        File fname = new File(systemDir, "uiderrors.txt");
5054        return fname;
5055    }
5056
5057    static void reportSettingsProblem(int priority, String msg) {
5058        logCriticalInfo(priority, msg);
5059    }
5060
5061    static void logCriticalInfo(int priority, String msg) {
5062        Slog.println(priority, TAG, msg);
5063        EventLogTags.writePmCriticalInfo(msg);
5064        try {
5065            File fname = getSettingsProblemFile();
5066            FileOutputStream out = new FileOutputStream(fname, true);
5067            PrintWriter pw = new FastPrintWriter(out);
5068            SimpleDateFormat formatter = new SimpleDateFormat();
5069            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5070            pw.println(dateString + ": " + msg);
5071            pw.close();
5072            FileUtils.setPermissions(
5073                    fname.toString(),
5074                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5075                    -1, -1);
5076        } catch (java.io.IOException e) {
5077        }
5078    }
5079
5080    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5081            PackageParser.Package pkg, File srcFile, int parseFlags)
5082            throws PackageManagerException {
5083        if (ps != null
5084                && ps.codePath.equals(srcFile)
5085                && ps.timeStamp == srcFile.lastModified()
5086                && !isCompatSignatureUpdateNeeded(pkg)
5087                && !isRecoverSignatureUpdateNeeded(pkg)) {
5088            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5089            if (ps.signatures.mSignatures != null
5090                    && ps.signatures.mSignatures.length != 0
5091                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
5092                // Optimization: reuse the existing cached certificates
5093                // if the package appears to be unchanged.
5094                pkg.mSignatures = ps.signatures.mSignatures;
5095                KeySetManagerService ksms = mSettings.mKeySetManagerService;
5096                synchronized (mPackages) {
5097                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5098                }
5099                return;
5100            }
5101
5102            Slog.w(TAG, "PackageSetting for " + ps.name
5103                    + " is missing signatures.  Collecting certs again to recover them.");
5104        } else {
5105            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5106        }
5107
5108        try {
5109            pp.collectCertificates(pkg, parseFlags);
5110            pp.collectManifestDigest(pkg);
5111        } catch (PackageParserException e) {
5112            throw PackageManagerException.from(e);
5113        }
5114    }
5115
5116    /*
5117     *  Scan a package and return the newly parsed package.
5118     *  Returns null in case of errors and the error code is stored in mLastScanError
5119     */
5120    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5121            long currentTime, UserHandle user) throws PackageManagerException {
5122        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5123        parseFlags |= mDefParseFlags;
5124        PackageParser pp = new PackageParser();
5125        pp.setSeparateProcesses(mSeparateProcesses);
5126        pp.setOnlyCoreApps(mOnlyCore);
5127        pp.setDisplayMetrics(mMetrics);
5128
5129        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5130            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5131        }
5132
5133        final PackageParser.Package pkg;
5134        try {
5135            pkg = pp.parsePackage(scanFile, parseFlags);
5136        } catch (PackageParserException e) {
5137            throw PackageManagerException.from(e);
5138        }
5139
5140        PackageSetting ps = null;
5141        PackageSetting updatedPkg;
5142        // reader
5143        synchronized (mPackages) {
5144            // Look to see if we already know about this package.
5145            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5146            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5147                // This package has been renamed to its original name.  Let's
5148                // use that.
5149                ps = mSettings.peekPackageLPr(oldName);
5150            }
5151            // If there was no original package, see one for the real package name.
5152            if (ps == null) {
5153                ps = mSettings.peekPackageLPr(pkg.packageName);
5154            }
5155            // Check to see if this package could be hiding/updating a system
5156            // package.  Must look for it either under the original or real
5157            // package name depending on our state.
5158            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5159            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5160        }
5161        boolean updatedPkgBetter = false;
5162        // First check if this is a system package that may involve an update
5163        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5164            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5165            // it needs to drop FLAG_PRIVILEGED.
5166            if (locationIsPrivileged(scanFile)) {
5167                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5168            } else {
5169                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5170            }
5171
5172            if (ps != null && !ps.codePath.equals(scanFile)) {
5173                // The path has changed from what was last scanned...  check the
5174                // version of the new path against what we have stored to determine
5175                // what to do.
5176                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5177                if (pkg.mVersionCode <= ps.versionCode) {
5178                    // The system package has been updated and the code path does not match
5179                    // Ignore entry. Skip it.
5180                    Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5181                            + " ignored: updated version " + ps.versionCode
5182                            + " better than this " + pkg.mVersionCode);
5183                    if (!updatedPkg.codePath.equals(scanFile)) {
5184                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5185                                + ps.name + " changing from " + updatedPkg.codePathString
5186                                + " to " + scanFile);
5187                        updatedPkg.codePath = scanFile;
5188                        updatedPkg.codePathString = scanFile.toString();
5189                        updatedPkg.resourcePath = scanFile;
5190                        updatedPkg.resourcePathString = scanFile.toString();
5191                    }
5192                    updatedPkg.pkg = pkg;
5193                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
5194                } else {
5195                    // The current app on the system partition is better than
5196                    // what we have updated to on the data partition; switch
5197                    // back to the system partition version.
5198                    // At this point, its safely assumed that package installation for
5199                    // apps in system partition will go through. If not there won't be a working
5200                    // version of the app
5201                    // writer
5202                    synchronized (mPackages) {
5203                        // Just remove the loaded entries from package lists.
5204                        mPackages.remove(ps.name);
5205                    }
5206
5207                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5208                            + " reverting from " + ps.codePathString
5209                            + ": new version " + pkg.mVersionCode
5210                            + " better than installed " + ps.versionCode);
5211
5212                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5213                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5214                    synchronized (mInstallLock) {
5215                        args.cleanUpResourcesLI();
5216                    }
5217                    synchronized (mPackages) {
5218                        mSettings.enableSystemPackageLPw(ps.name);
5219                    }
5220                    updatedPkgBetter = true;
5221                }
5222            }
5223        }
5224
5225        if (updatedPkg != null) {
5226            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5227            // initially
5228            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5229
5230            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5231            // flag set initially
5232            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5233                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5234            }
5235        }
5236
5237        // Verify certificates against what was last scanned
5238        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5239
5240        /*
5241         * A new system app appeared, but we already had a non-system one of the
5242         * same name installed earlier.
5243         */
5244        boolean shouldHideSystemApp = false;
5245        if (updatedPkg == null && ps != null
5246                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5247            /*
5248             * Check to make sure the signatures match first. If they don't,
5249             * wipe the installed application and its data.
5250             */
5251            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5252                    != PackageManager.SIGNATURE_MATCH) {
5253                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5254                        + " signatures don't match existing userdata copy; removing");
5255                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5256                ps = null;
5257            } else {
5258                /*
5259                 * If the newly-added system app is an older version than the
5260                 * already installed version, hide it. It will be scanned later
5261                 * and re-added like an update.
5262                 */
5263                if (pkg.mVersionCode <= ps.versionCode) {
5264                    shouldHideSystemApp = true;
5265                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5266                            + " but new version " + pkg.mVersionCode + " better than installed "
5267                            + ps.versionCode + "; hiding system");
5268                } else {
5269                    /*
5270                     * The newly found system app is a newer version that the
5271                     * one previously installed. Simply remove the
5272                     * already-installed application and replace it with our own
5273                     * while keeping the application data.
5274                     */
5275                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5276                            + " reverting from " + ps.codePathString + ": new version "
5277                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5278                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5279                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5280                    synchronized (mInstallLock) {
5281                        args.cleanUpResourcesLI();
5282                    }
5283                }
5284            }
5285        }
5286
5287        // The apk is forward locked (not public) if its code and resources
5288        // are kept in different files. (except for app in either system or
5289        // vendor path).
5290        // TODO grab this value from PackageSettings
5291        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5292            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5293                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5294            }
5295        }
5296
5297        // TODO: extend to support forward-locked splits
5298        String resourcePath = null;
5299        String baseResourcePath = null;
5300        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5301            if (ps != null && ps.resourcePathString != null) {
5302                resourcePath = ps.resourcePathString;
5303                baseResourcePath = ps.resourcePathString;
5304            } else {
5305                // Should not happen at all. Just log an error.
5306                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5307            }
5308        } else {
5309            resourcePath = pkg.codePath;
5310            baseResourcePath = pkg.baseCodePath;
5311        }
5312
5313        // Set application objects path explicitly.
5314        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5315        pkg.applicationInfo.setCodePath(pkg.codePath);
5316        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5317        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5318        pkg.applicationInfo.setResourcePath(resourcePath);
5319        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5320        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5321
5322        // Note that we invoke the following method only if we are about to unpack an application
5323        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5324                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5325
5326        /*
5327         * If the system app should be overridden by a previously installed
5328         * data, hide the system app now and let the /data/app scan pick it up
5329         * again.
5330         */
5331        if (shouldHideSystemApp) {
5332            synchronized (mPackages) {
5333                /*
5334                 * We have to grant systems permissions before we hide, because
5335                 * grantPermissions will assume the package update is trying to
5336                 * expand its permissions.
5337                 */
5338                grantPermissionsLPw(pkg, true, pkg.packageName);
5339                mSettings.disableSystemPackageLPw(pkg.packageName);
5340            }
5341        }
5342
5343        return scannedPkg;
5344    }
5345
5346    private static String fixProcessName(String defProcessName,
5347            String processName, int uid) {
5348        if (processName == null) {
5349            return defProcessName;
5350        }
5351        return processName;
5352    }
5353
5354    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5355            throws PackageManagerException {
5356        if (pkgSetting.signatures.mSignatures != null) {
5357            // Already existing package. Make sure signatures match
5358            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5359                    == PackageManager.SIGNATURE_MATCH;
5360            if (!match) {
5361                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5362                        == PackageManager.SIGNATURE_MATCH;
5363            }
5364            if (!match) {
5365                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5366                        == PackageManager.SIGNATURE_MATCH;
5367            }
5368            if (!match) {
5369                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5370                        + pkg.packageName + " signatures do not match the "
5371                        + "previously installed version; ignoring!");
5372            }
5373        }
5374
5375        // Check for shared user signatures
5376        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5377            // Already existing package. Make sure signatures match
5378            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5379                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5380            if (!match) {
5381                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5382                        == PackageManager.SIGNATURE_MATCH;
5383            }
5384            if (!match) {
5385                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5386                        == PackageManager.SIGNATURE_MATCH;
5387            }
5388            if (!match) {
5389                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5390                        "Package " + pkg.packageName
5391                        + " has no signatures that match those in shared user "
5392                        + pkgSetting.sharedUser.name + "; ignoring!");
5393            }
5394        }
5395    }
5396
5397    /**
5398     * Enforces that only the system UID or root's UID can call a method exposed
5399     * via Binder.
5400     *
5401     * @param message used as message if SecurityException is thrown
5402     * @throws SecurityException if the caller is not system or root
5403     */
5404    private static final void enforceSystemOrRoot(String message) {
5405        final int uid = Binder.getCallingUid();
5406        if (uid != Process.SYSTEM_UID && uid != 0) {
5407            throw new SecurityException(message);
5408        }
5409    }
5410
5411    @Override
5412    public void performBootDexOpt() {
5413        enforceSystemOrRoot("Only the system can request dexopt be performed");
5414
5415        // Before everything else, see whether we need to fstrim.
5416        try {
5417            IMountService ms = PackageHelper.getMountService();
5418            if (ms != null) {
5419                final boolean isUpgrade = isUpgrade();
5420                boolean doTrim = isUpgrade;
5421                if (doTrim) {
5422                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5423                } else {
5424                    final long interval = android.provider.Settings.Global.getLong(
5425                            mContext.getContentResolver(),
5426                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5427                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5428                    if (interval > 0) {
5429                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5430                        if (timeSinceLast > interval) {
5431                            doTrim = true;
5432                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5433                                    + "; running immediately");
5434                        }
5435                    }
5436                }
5437                if (doTrim) {
5438                    if (!isFirstBoot()) {
5439                        try {
5440                            ActivityManagerNative.getDefault().showBootMessage(
5441                                    mContext.getResources().getString(
5442                                            R.string.android_upgrading_fstrim), true);
5443                        } catch (RemoteException e) {
5444                        }
5445                    }
5446                    ms.runMaintenance();
5447                }
5448            } else {
5449                Slog.e(TAG, "Mount service unavailable!");
5450            }
5451        } catch (RemoteException e) {
5452            // Can't happen; MountService is local
5453        }
5454
5455        final ArraySet<PackageParser.Package> pkgs;
5456        synchronized (mPackages) {
5457            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5458        }
5459
5460        if (pkgs != null) {
5461            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5462            // in case the device runs out of space.
5463            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5464            // Give priority to core apps.
5465            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5466                PackageParser.Package pkg = it.next();
5467                if (pkg.coreApp) {
5468                    if (DEBUG_DEXOPT) {
5469                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5470                    }
5471                    sortedPkgs.add(pkg);
5472                    it.remove();
5473                }
5474            }
5475            // Give priority to system apps that listen for pre boot complete.
5476            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5477            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
5478            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5479                PackageParser.Package pkg = it.next();
5480                if (pkgNames.contains(pkg.packageName)) {
5481                    if (DEBUG_DEXOPT) {
5482                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
5483                    }
5484                    sortedPkgs.add(pkg);
5485                    it.remove();
5486                }
5487            }
5488            // Give priority to system apps.
5489            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5490                PackageParser.Package pkg = it.next();
5491                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
5492                    if (DEBUG_DEXOPT) {
5493                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
5494                    }
5495                    sortedPkgs.add(pkg);
5496                    it.remove();
5497                }
5498            }
5499            // Give priority to updated system apps.
5500            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5501                PackageParser.Package pkg = it.next();
5502                if (pkg.isUpdatedSystemApp()) {
5503                    if (DEBUG_DEXOPT) {
5504                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
5505                    }
5506                    sortedPkgs.add(pkg);
5507                    it.remove();
5508                }
5509            }
5510            // Give priority to apps that listen for boot complete.
5511            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
5512            pkgNames = getPackageNamesForIntent(intent);
5513            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5514                PackageParser.Package pkg = it.next();
5515                if (pkgNames.contains(pkg.packageName)) {
5516                    if (DEBUG_DEXOPT) {
5517                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
5518                    }
5519                    sortedPkgs.add(pkg);
5520                    it.remove();
5521                }
5522            }
5523            // Filter out packages that aren't recently used.
5524            filterRecentlyUsedApps(pkgs);
5525            // Add all remaining apps.
5526            for (PackageParser.Package pkg : pkgs) {
5527                if (DEBUG_DEXOPT) {
5528                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
5529                }
5530                sortedPkgs.add(pkg);
5531            }
5532
5533            // If we want to be lazy, filter everything that wasn't recently used.
5534            if (mLazyDexOpt) {
5535                filterRecentlyUsedApps(sortedPkgs);
5536            }
5537
5538            int i = 0;
5539            int total = sortedPkgs.size();
5540            File dataDir = Environment.getDataDirectory();
5541            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
5542            if (lowThreshold == 0) {
5543                throw new IllegalStateException("Invalid low memory threshold");
5544            }
5545            for (PackageParser.Package pkg : sortedPkgs) {
5546                long usableSpace = dataDir.getUsableSpace();
5547                if (usableSpace < lowThreshold) {
5548                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
5549                    break;
5550                }
5551                performBootDexOpt(pkg, ++i, total);
5552            }
5553        }
5554    }
5555
5556    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
5557        // Filter out packages that aren't recently used.
5558        //
5559        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
5560        // should do a full dexopt.
5561        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
5562            int total = pkgs.size();
5563            int skipped = 0;
5564            long now = System.currentTimeMillis();
5565            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
5566                PackageParser.Package pkg = i.next();
5567                long then = pkg.mLastPackageUsageTimeInMills;
5568                if (then + mDexOptLRUThresholdInMills < now) {
5569                    if (DEBUG_DEXOPT) {
5570                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
5571                              ((then == 0) ? "never" : new Date(then)));
5572                    }
5573                    i.remove();
5574                    skipped++;
5575                }
5576            }
5577            if (DEBUG_DEXOPT) {
5578                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
5579            }
5580        }
5581    }
5582
5583    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
5584        List<ResolveInfo> ris = null;
5585        try {
5586            ris = AppGlobals.getPackageManager().queryIntentReceivers(
5587                    intent, null, 0, UserHandle.USER_OWNER);
5588        } catch (RemoteException e) {
5589        }
5590        ArraySet<String> pkgNames = new ArraySet<String>();
5591        if (ris != null) {
5592            for (ResolveInfo ri : ris) {
5593                pkgNames.add(ri.activityInfo.packageName);
5594            }
5595        }
5596        return pkgNames;
5597    }
5598
5599    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
5600        if (DEBUG_DEXOPT) {
5601            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
5602        }
5603        if (!isFirstBoot()) {
5604            try {
5605                ActivityManagerNative.getDefault().showBootMessage(
5606                        mContext.getResources().getString(R.string.android_upgrading_apk,
5607                                curr, total), true);
5608            } catch (RemoteException e) {
5609            }
5610        }
5611        PackageParser.Package p = pkg;
5612        synchronized (mInstallLock) {
5613            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
5614                    false /* force dex */, false /* defer */, true /* include dependencies */);
5615        }
5616    }
5617
5618    @Override
5619    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
5620        return performDexOpt(packageName, instructionSet, false);
5621    }
5622
5623    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
5624        boolean dexopt = mLazyDexOpt || backgroundDexopt;
5625        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
5626        if (!dexopt && !updateUsage) {
5627            // We aren't going to dexopt or update usage, so bail early.
5628            return false;
5629        }
5630        PackageParser.Package p;
5631        final String targetInstructionSet;
5632        synchronized (mPackages) {
5633            p = mPackages.get(packageName);
5634            if (p == null) {
5635                return false;
5636            }
5637            if (updateUsage) {
5638                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
5639            }
5640            mPackageUsage.write(false);
5641            if (!dexopt) {
5642                // We aren't going to dexopt, so bail early.
5643                return false;
5644            }
5645
5646            targetInstructionSet = instructionSet != null ? instructionSet :
5647                    getPrimaryInstructionSet(p.applicationInfo);
5648            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
5649                return false;
5650            }
5651        }
5652
5653        synchronized (mInstallLock) {
5654            final String[] instructionSets = new String[] { targetInstructionSet };
5655            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
5656                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
5657            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
5658        }
5659    }
5660
5661    public ArraySet<String> getPackagesThatNeedDexOpt() {
5662        ArraySet<String> pkgs = null;
5663        synchronized (mPackages) {
5664            for (PackageParser.Package p : mPackages.values()) {
5665                if (DEBUG_DEXOPT) {
5666                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
5667                }
5668                if (!p.mDexOptPerformed.isEmpty()) {
5669                    continue;
5670                }
5671                if (pkgs == null) {
5672                    pkgs = new ArraySet<String>();
5673                }
5674                pkgs.add(p.packageName);
5675            }
5676        }
5677        return pkgs;
5678    }
5679
5680    public void shutdown() {
5681        mPackageUsage.write(true);
5682    }
5683
5684    @Override
5685    public void forceDexOpt(String packageName) {
5686        enforceSystemOrRoot("forceDexOpt");
5687
5688        PackageParser.Package pkg;
5689        synchronized (mPackages) {
5690            pkg = mPackages.get(packageName);
5691            if (pkg == null) {
5692                throw new IllegalArgumentException("Missing package: " + packageName);
5693            }
5694        }
5695
5696        synchronized (mInstallLock) {
5697            final String[] instructionSets = new String[] {
5698                    getPrimaryInstructionSet(pkg.applicationInfo) };
5699            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
5700                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
5701            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
5702                throw new IllegalStateException("Failed to dexopt: " + res);
5703            }
5704        }
5705    }
5706
5707    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
5708        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
5709            Slog.w(TAG, "Unable to update from " + oldPkg.name
5710                    + " to " + newPkg.packageName
5711                    + ": old package not in system partition");
5712            return false;
5713        } else if (mPackages.get(oldPkg.name) != null) {
5714            Slog.w(TAG, "Unable to update from " + oldPkg.name
5715                    + " to " + newPkg.packageName
5716                    + ": old package still exists");
5717            return false;
5718        }
5719        return true;
5720    }
5721
5722    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
5723        int[] users = sUserManager.getUserIds();
5724        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
5725        if (res < 0) {
5726            return res;
5727        }
5728        for (int user : users) {
5729            if (user != 0) {
5730                res = mInstaller.createUserData(volumeUuid, packageName,
5731                        UserHandle.getUid(user, uid), user, seinfo);
5732                if (res < 0) {
5733                    return res;
5734                }
5735            }
5736        }
5737        return res;
5738    }
5739
5740    private int removeDataDirsLI(String volumeUuid, String packageName) {
5741        int[] users = sUserManager.getUserIds();
5742        int res = 0;
5743        for (int user : users) {
5744            int resInner = mInstaller.remove(volumeUuid, packageName, user);
5745            if (resInner < 0) {
5746                res = resInner;
5747            }
5748        }
5749
5750        return res;
5751    }
5752
5753    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
5754        int[] users = sUserManager.getUserIds();
5755        int res = 0;
5756        for (int user : users) {
5757            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
5758            if (resInner < 0) {
5759                res = resInner;
5760            }
5761        }
5762        return res;
5763    }
5764
5765    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
5766            PackageParser.Package changingLib) {
5767        if (file.path != null) {
5768            usesLibraryFiles.add(file.path);
5769            return;
5770        }
5771        PackageParser.Package p = mPackages.get(file.apk);
5772        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
5773            // If we are doing this while in the middle of updating a library apk,
5774            // then we need to make sure to use that new apk for determining the
5775            // dependencies here.  (We haven't yet finished committing the new apk
5776            // to the package manager state.)
5777            if (p == null || p.packageName.equals(changingLib.packageName)) {
5778                p = changingLib;
5779            }
5780        }
5781        if (p != null) {
5782            usesLibraryFiles.addAll(p.getAllCodePaths());
5783        }
5784    }
5785
5786    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
5787            PackageParser.Package changingLib) throws PackageManagerException {
5788        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
5789            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
5790            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
5791            for (int i=0; i<N; i++) {
5792                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
5793                if (file == null) {
5794                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
5795                            "Package " + pkg.packageName + " requires unavailable shared library "
5796                            + pkg.usesLibraries.get(i) + "; failing!");
5797                }
5798                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5799            }
5800            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
5801            for (int i=0; i<N; i++) {
5802                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
5803                if (file == null) {
5804                    Slog.w(TAG, "Package " + pkg.packageName
5805                            + " desires unavailable shared library "
5806                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
5807                } else {
5808                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5809                }
5810            }
5811            N = usesLibraryFiles.size();
5812            if (N > 0) {
5813                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
5814            } else {
5815                pkg.usesLibraryFiles = null;
5816            }
5817        }
5818    }
5819
5820    private static boolean hasString(List<String> list, List<String> which) {
5821        if (list == null) {
5822            return false;
5823        }
5824        for (int i=list.size()-1; i>=0; i--) {
5825            for (int j=which.size()-1; j>=0; j--) {
5826                if (which.get(j).equals(list.get(i))) {
5827                    return true;
5828                }
5829            }
5830        }
5831        return false;
5832    }
5833
5834    private void updateAllSharedLibrariesLPw() {
5835        for (PackageParser.Package pkg : mPackages.values()) {
5836            try {
5837                updateSharedLibrariesLPw(pkg, null);
5838            } catch (PackageManagerException e) {
5839                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5840            }
5841        }
5842    }
5843
5844    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
5845            PackageParser.Package changingPkg) {
5846        ArrayList<PackageParser.Package> res = null;
5847        for (PackageParser.Package pkg : mPackages.values()) {
5848            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
5849                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
5850                if (res == null) {
5851                    res = new ArrayList<PackageParser.Package>();
5852                }
5853                res.add(pkg);
5854                try {
5855                    updateSharedLibrariesLPw(pkg, changingPkg);
5856                } catch (PackageManagerException e) {
5857                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5858                }
5859            }
5860        }
5861        return res;
5862    }
5863
5864    /**
5865     * Derive the value of the {@code cpuAbiOverride} based on the provided
5866     * value and an optional stored value from the package settings.
5867     */
5868    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
5869        String cpuAbiOverride = null;
5870
5871        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
5872            cpuAbiOverride = null;
5873        } else if (abiOverride != null) {
5874            cpuAbiOverride = abiOverride;
5875        } else if (settings != null) {
5876            cpuAbiOverride = settings.cpuAbiOverrideString;
5877        }
5878
5879        return cpuAbiOverride;
5880    }
5881
5882    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
5883            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5884        boolean success = false;
5885        try {
5886            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
5887                    currentTime, user);
5888            success = true;
5889            return res;
5890        } finally {
5891            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5892                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
5893            }
5894        }
5895    }
5896
5897    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
5898            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5899        final File scanFile = new File(pkg.codePath);
5900        if (pkg.applicationInfo.getCodePath() == null ||
5901                pkg.applicationInfo.getResourcePath() == null) {
5902            // Bail out. The resource and code paths haven't been set.
5903            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
5904                    "Code and resource paths haven't been set correctly");
5905        }
5906
5907        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5908            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
5909        } else {
5910            // Only allow system apps to be flagged as core apps.
5911            pkg.coreApp = false;
5912        }
5913
5914        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5915            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5916        }
5917
5918        if (mCustomResolverComponentName != null &&
5919                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5920            setUpCustomResolverActivity(pkg);
5921        }
5922
5923        if (pkg.packageName.equals("android")) {
5924            synchronized (mPackages) {
5925                if (mAndroidApplication != null) {
5926                    Slog.w(TAG, "*************************************************");
5927                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5928                    Slog.w(TAG, " file=" + scanFile);
5929                    Slog.w(TAG, "*************************************************");
5930                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5931                            "Core android package being redefined.  Skipping.");
5932                }
5933
5934                // Set up information for our fall-back user intent resolution activity.
5935                mPlatformPackage = pkg;
5936                pkg.mVersionCode = mSdkVersion;
5937                mAndroidApplication = pkg.applicationInfo;
5938
5939                if (!mResolverReplaced) {
5940                    mResolveActivity.applicationInfo = mAndroidApplication;
5941                    mResolveActivity.name = ResolverActivity.class.getName();
5942                    mResolveActivity.packageName = mAndroidApplication.packageName;
5943                    mResolveActivity.processName = "system:ui";
5944                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5945                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5946                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5947                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5948                    mResolveActivity.exported = true;
5949                    mResolveActivity.enabled = true;
5950                    mResolveInfo.activityInfo = mResolveActivity;
5951                    mResolveInfo.priority = 0;
5952                    mResolveInfo.preferredOrder = 0;
5953                    mResolveInfo.match = 0;
5954                    mResolveComponentName = new ComponentName(
5955                            mAndroidApplication.packageName, mResolveActivity.name);
5956                }
5957            }
5958        }
5959
5960        if (DEBUG_PACKAGE_SCANNING) {
5961            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5962                Log.d(TAG, "Scanning package " + pkg.packageName);
5963        }
5964
5965        if (mPackages.containsKey(pkg.packageName)
5966                || mSharedLibraries.containsKey(pkg.packageName)) {
5967            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5968                    "Application package " + pkg.packageName
5969                    + " already installed.  Skipping duplicate.");
5970        }
5971
5972        // If we're only installing presumed-existing packages, require that the
5973        // scanned APK is both already known and at the path previously established
5974        // for it.  Previously unknown packages we pick up normally, but if we have an
5975        // a priori expectation about this package's install presence, enforce it.
5976        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
5977            PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
5978            if (known != null) {
5979                if (DEBUG_PACKAGE_SCANNING) {
5980                    Log.d(TAG, "Examining " + pkg.codePath
5981                            + " and requiring known paths " + known.codePathString
5982                            + " & " + known.resourcePathString);
5983                }
5984                if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
5985                        || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
5986                    throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
5987                            "Application package " + pkg.packageName
5988                            + " found at " + pkg.applicationInfo.getCodePath()
5989                            + " but expected at " + known.codePathString + "; ignoring.");
5990                }
5991            }
5992        }
5993
5994        // Initialize package source and resource directories
5995        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5996        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5997
5998        SharedUserSetting suid = null;
5999        PackageSetting pkgSetting = null;
6000
6001        if (!isSystemApp(pkg)) {
6002            // Only system apps can use these features.
6003            pkg.mOriginalPackages = null;
6004            pkg.mRealPackage = null;
6005            pkg.mAdoptPermissions = null;
6006        }
6007
6008        // writer
6009        synchronized (mPackages) {
6010            if (pkg.mSharedUserId != null) {
6011                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6012                if (suid == null) {
6013                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6014                            "Creating application package " + pkg.packageName
6015                            + " for shared user failed");
6016                }
6017                if (DEBUG_PACKAGE_SCANNING) {
6018                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6019                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6020                                + "): packages=" + suid.packages);
6021                }
6022            }
6023
6024            // Check if we are renaming from an original package name.
6025            PackageSetting origPackage = null;
6026            String realName = null;
6027            if (pkg.mOriginalPackages != null) {
6028                // This package may need to be renamed to a previously
6029                // installed name.  Let's check on that...
6030                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6031                if (pkg.mOriginalPackages.contains(renamed)) {
6032                    // This package had originally been installed as the
6033                    // original name, and we have already taken care of
6034                    // transitioning to the new one.  Just update the new
6035                    // one to continue using the old name.
6036                    realName = pkg.mRealPackage;
6037                    if (!pkg.packageName.equals(renamed)) {
6038                        // Callers into this function may have already taken
6039                        // care of renaming the package; only do it here if
6040                        // it is not already done.
6041                        pkg.setPackageName(renamed);
6042                    }
6043
6044                } else {
6045                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6046                        if ((origPackage = mSettings.peekPackageLPr(
6047                                pkg.mOriginalPackages.get(i))) != null) {
6048                            // We do have the package already installed under its
6049                            // original name...  should we use it?
6050                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6051                                // New package is not compatible with original.
6052                                origPackage = null;
6053                                continue;
6054                            } else if (origPackage.sharedUser != null) {
6055                                // Make sure uid is compatible between packages.
6056                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6057                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6058                                            + " to " + pkg.packageName + ": old uid "
6059                                            + origPackage.sharedUser.name
6060                                            + " differs from " + pkg.mSharedUserId);
6061                                    origPackage = null;
6062                                    continue;
6063                                }
6064                            } else {
6065                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6066                                        + pkg.packageName + " to old name " + origPackage.name);
6067                            }
6068                            break;
6069                        }
6070                    }
6071                }
6072            }
6073
6074            if (mTransferedPackages.contains(pkg.packageName)) {
6075                Slog.w(TAG, "Package " + pkg.packageName
6076                        + " was transferred to another, but its .apk remains");
6077            }
6078
6079            // Just create the setting, don't add it yet. For already existing packages
6080            // the PkgSetting exists already and doesn't have to be created.
6081            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6082                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6083                    pkg.applicationInfo.primaryCpuAbi,
6084                    pkg.applicationInfo.secondaryCpuAbi,
6085                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6086                    user, false);
6087            if (pkgSetting == null) {
6088                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6089                        "Creating application package " + pkg.packageName + " failed");
6090            }
6091
6092            if (pkgSetting.origPackage != null) {
6093                // If we are first transitioning from an original package,
6094                // fix up the new package's name now.  We need to do this after
6095                // looking up the package under its new name, so getPackageLP
6096                // can take care of fiddling things correctly.
6097                pkg.setPackageName(origPackage.name);
6098
6099                // File a report about this.
6100                String msg = "New package " + pkgSetting.realName
6101                        + " renamed to replace old package " + pkgSetting.name;
6102                reportSettingsProblem(Log.WARN, msg);
6103
6104                // Make a note of it.
6105                mTransferedPackages.add(origPackage.name);
6106
6107                // No longer need to retain this.
6108                pkgSetting.origPackage = null;
6109            }
6110
6111            if (realName != null) {
6112                // Make a note of it.
6113                mTransferedPackages.add(pkg.packageName);
6114            }
6115
6116            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6117                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6118            }
6119
6120            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6121                // Check all shared libraries and map to their actual file path.
6122                // We only do this here for apps not on a system dir, because those
6123                // are the only ones that can fail an install due to this.  We
6124                // will take care of the system apps by updating all of their
6125                // library paths after the scan is done.
6126                updateSharedLibrariesLPw(pkg, null);
6127            }
6128
6129            if (mFoundPolicyFile) {
6130                SELinuxMMAC.assignSeinfoValue(pkg);
6131            }
6132
6133            pkg.applicationInfo.uid = pkgSetting.appId;
6134            pkg.mExtras = pkgSetting;
6135            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
6136                try {
6137                    verifySignaturesLP(pkgSetting, pkg);
6138                    // We just determined the app is signed correctly, so bring
6139                    // over the latest parsed certs.
6140                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6141                } catch (PackageManagerException e) {
6142                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6143                        throw e;
6144                    }
6145                    // The signature has changed, but this package is in the system
6146                    // image...  let's recover!
6147                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6148                    // However...  if this package is part of a shared user, but it
6149                    // doesn't match the signature of the shared user, let's fail.
6150                    // What this means is that you can't change the signatures
6151                    // associated with an overall shared user, which doesn't seem all
6152                    // that unreasonable.
6153                    if (pkgSetting.sharedUser != null) {
6154                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6155                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6156                            throw new PackageManagerException(
6157                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6158                                            "Signature mismatch for shared user : "
6159                                            + pkgSetting.sharedUser);
6160                        }
6161                    }
6162                    // File a report about this.
6163                    String msg = "System package " + pkg.packageName
6164                        + " signature changed; retaining data.";
6165                    reportSettingsProblem(Log.WARN, msg);
6166                }
6167            } else {
6168                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
6169                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6170                            + pkg.packageName + " upgrade keys do not match the "
6171                            + "previously installed version");
6172                } else {
6173                    // We just determined the app is signed correctly, so bring
6174                    // over the latest parsed certs.
6175                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6176                }
6177            }
6178            // Verify that this new package doesn't have any content providers
6179            // that conflict with existing packages.  Only do this if the
6180            // package isn't already installed, since we don't want to break
6181            // things that are installed.
6182            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6183                final int N = pkg.providers.size();
6184                int i;
6185                for (i=0; i<N; i++) {
6186                    PackageParser.Provider p = pkg.providers.get(i);
6187                    if (p.info.authority != null) {
6188                        String names[] = p.info.authority.split(";");
6189                        for (int j = 0; j < names.length; j++) {
6190                            if (mProvidersByAuthority.containsKey(names[j])) {
6191                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6192                                final String otherPackageName =
6193                                        ((other != null && other.getComponentName() != null) ?
6194                                                other.getComponentName().getPackageName() : "?");
6195                                throw new PackageManagerException(
6196                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6197                                                "Can't install because provider name " + names[j]
6198                                                + " (in package " + pkg.applicationInfo.packageName
6199                                                + ") is already used by " + otherPackageName);
6200                            }
6201                        }
6202                    }
6203                }
6204            }
6205
6206            if (pkg.mAdoptPermissions != null) {
6207                // This package wants to adopt ownership of permissions from
6208                // another package.
6209                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6210                    final String origName = pkg.mAdoptPermissions.get(i);
6211                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6212                    if (orig != null) {
6213                        if (verifyPackageUpdateLPr(orig, pkg)) {
6214                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6215                                    + pkg.packageName);
6216                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6217                        }
6218                    }
6219                }
6220            }
6221        }
6222
6223        final String pkgName = pkg.packageName;
6224
6225        final long scanFileTime = scanFile.lastModified();
6226        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6227        pkg.applicationInfo.processName = fixProcessName(
6228                pkg.applicationInfo.packageName,
6229                pkg.applicationInfo.processName,
6230                pkg.applicationInfo.uid);
6231
6232        File dataPath;
6233        if (mPlatformPackage == pkg) {
6234            // The system package is special.
6235            dataPath = new File(Environment.getDataDirectory(), "system");
6236
6237            pkg.applicationInfo.dataDir = dataPath.getPath();
6238
6239        } else {
6240            // This is a normal package, need to make its data directory.
6241            dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName,
6242                    UserHandle.USER_OWNER);
6243
6244            boolean uidError = false;
6245            if (dataPath.exists()) {
6246                int currentUid = 0;
6247                try {
6248                    StructStat stat = Os.stat(dataPath.getPath());
6249                    currentUid = stat.st_uid;
6250                } catch (ErrnoException e) {
6251                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6252                }
6253
6254                // If we have mismatched owners for the data path, we have a problem.
6255                if (currentUid != pkg.applicationInfo.uid) {
6256                    boolean recovered = false;
6257                    if (currentUid == 0) {
6258                        // The directory somehow became owned by root.  Wow.
6259                        // This is probably because the system was stopped while
6260                        // installd was in the middle of messing with its libs
6261                        // directory.  Ask installd to fix that.
6262                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6263                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6264                        if (ret >= 0) {
6265                            recovered = true;
6266                            String msg = "Package " + pkg.packageName
6267                                    + " unexpectedly changed to uid 0; recovered to " +
6268                                    + pkg.applicationInfo.uid;
6269                            reportSettingsProblem(Log.WARN, msg);
6270                        }
6271                    }
6272                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6273                            || (scanFlags&SCAN_BOOTING) != 0)) {
6274                        // If this is a system app, we can at least delete its
6275                        // current data so the application will still work.
6276                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6277                        if (ret >= 0) {
6278                            // TODO: Kill the processes first
6279                            // Old data gone!
6280                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6281                                    ? "System package " : "Third party package ";
6282                            String msg = prefix + pkg.packageName
6283                                    + " has changed from uid: "
6284                                    + currentUid + " to "
6285                                    + pkg.applicationInfo.uid + "; old data erased";
6286                            reportSettingsProblem(Log.WARN, msg);
6287                            recovered = true;
6288
6289                            // And now re-install the app.
6290                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6291                                    pkg.applicationInfo.seinfo);
6292                            if (ret == -1) {
6293                                // Ack should not happen!
6294                                msg = prefix + pkg.packageName
6295                                        + " could not have data directory re-created after delete.";
6296                                reportSettingsProblem(Log.WARN, msg);
6297                                throw new PackageManagerException(
6298                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6299                            }
6300                        }
6301                        if (!recovered) {
6302                            mHasSystemUidErrors = true;
6303                        }
6304                    } else if (!recovered) {
6305                        // If we allow this install to proceed, we will be broken.
6306                        // Abort, abort!
6307                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6308                                "scanPackageLI");
6309                    }
6310                    if (!recovered) {
6311                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6312                            + pkg.applicationInfo.uid + "/fs_"
6313                            + currentUid;
6314                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6315                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6316                        String msg = "Package " + pkg.packageName
6317                                + " has mismatched uid: "
6318                                + currentUid + " on disk, "
6319                                + pkg.applicationInfo.uid + " in settings";
6320                        // writer
6321                        synchronized (mPackages) {
6322                            mSettings.mReadMessages.append(msg);
6323                            mSettings.mReadMessages.append('\n');
6324                            uidError = true;
6325                            if (!pkgSetting.uidError) {
6326                                reportSettingsProblem(Log.ERROR, msg);
6327                            }
6328                        }
6329                    }
6330                }
6331                pkg.applicationInfo.dataDir = dataPath.getPath();
6332                if (mShouldRestoreconData) {
6333                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6334                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6335                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6336                }
6337            } else {
6338                if (DEBUG_PACKAGE_SCANNING) {
6339                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6340                        Log.v(TAG, "Want this data dir: " + dataPath);
6341                }
6342                //invoke installer to do the actual installation
6343                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6344                        pkg.applicationInfo.seinfo);
6345                if (ret < 0) {
6346                    // Error from installer
6347                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6348                            "Unable to create data dirs [errorCode=" + ret + "]");
6349                }
6350
6351                if (dataPath.exists()) {
6352                    pkg.applicationInfo.dataDir = dataPath.getPath();
6353                } else {
6354                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6355                    pkg.applicationInfo.dataDir = null;
6356                }
6357            }
6358
6359            pkgSetting.uidError = uidError;
6360        }
6361
6362        final String path = scanFile.getPath();
6363        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6364
6365        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6366            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6367        } else {
6368            if ((scanFlags & SCAN_MOVE) != 0) {
6369                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6370                // but we already have this packages package info in the PackageSetting. We just
6371                // use that and derive the native library path based on the new codepath.
6372                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6373                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6374            }
6375
6376            // Set native library paths again. For moves, the path will be updated based on the
6377            // ABIs we've determined above. For non-moves, the path will be updated based on the
6378            // ABIs we determined during compilation, but the path will depend on the final
6379            // package path (after the rename away from the stage path).
6380            setNativeLibraryPaths(pkg);
6381        }
6382
6383        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6384        final int[] userIds = sUserManager.getUserIds();
6385        synchronized (mInstallLock) {
6386            // Create a native library symlink only if we have native libraries
6387            // and if the native libraries are 32 bit libraries. We do not provide
6388            // this symlink for 64 bit libraries.
6389            if (pkg.applicationInfo.primaryCpuAbi != null &&
6390                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6391                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6392                for (int userId : userIds) {
6393                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6394                            nativeLibPath, userId) < 0) {
6395                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6396                                "Failed linking native library dir (user=" + userId + ")");
6397                    }
6398                }
6399            }
6400        }
6401
6402        // This is a special case for the "system" package, where the ABI is
6403        // dictated by the zygote configuration (and init.rc). We should keep track
6404        // of this ABI so that we can deal with "normal" applications that run under
6405        // the same UID correctly.
6406        if (mPlatformPackage == pkg) {
6407            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6408                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6409        }
6410
6411        // If there's a mismatch between the abi-override in the package setting
6412        // and the abiOverride specified for the install. Warn about this because we
6413        // would've already compiled the app without taking the package setting into
6414        // account.
6415        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
6416            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
6417                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
6418                        " for package: " + pkg.packageName);
6419            }
6420        }
6421
6422        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6423        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6424        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6425
6426        // Copy the derived override back to the parsed package, so that we can
6427        // update the package settings accordingly.
6428        pkg.cpuAbiOverride = cpuAbiOverride;
6429
6430        if (DEBUG_ABI_SELECTION) {
6431            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6432                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6433                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6434        }
6435
6436        // Push the derived path down into PackageSettings so we know what to
6437        // clean up at uninstall time.
6438        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6439
6440        if (DEBUG_ABI_SELECTION) {
6441            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6442                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6443                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6444        }
6445
6446        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6447            // We don't do this here during boot because we can do it all
6448            // at once after scanning all existing packages.
6449            //
6450            // We also do this *before* we perform dexopt on this package, so that
6451            // we can avoid redundant dexopts, and also to make sure we've got the
6452            // code and package path correct.
6453            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
6454                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
6455        }
6456
6457        if ((scanFlags & SCAN_NO_DEX) == 0) {
6458            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
6459                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
6460            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6461                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
6462            }
6463        }
6464        if (mFactoryTest && pkg.requestedPermissions.contains(
6465                android.Manifest.permission.FACTORY_TEST)) {
6466            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
6467        }
6468
6469        ArrayList<PackageParser.Package> clientLibPkgs = null;
6470
6471        // writer
6472        synchronized (mPackages) {
6473            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6474                // Only system apps can add new shared libraries.
6475                if (pkg.libraryNames != null) {
6476                    for (int i=0; i<pkg.libraryNames.size(); i++) {
6477                        String name = pkg.libraryNames.get(i);
6478                        boolean allowed = false;
6479                        if (pkg.isUpdatedSystemApp()) {
6480                            // New library entries can only be added through the
6481                            // system image.  This is important to get rid of a lot
6482                            // of nasty edge cases: for example if we allowed a non-
6483                            // system update of the app to add a library, then uninstalling
6484                            // the update would make the library go away, and assumptions
6485                            // we made such as through app install filtering would now
6486                            // have allowed apps on the device which aren't compatible
6487                            // with it.  Better to just have the restriction here, be
6488                            // conservative, and create many fewer cases that can negatively
6489                            // impact the user experience.
6490                            final PackageSetting sysPs = mSettings
6491                                    .getDisabledSystemPkgLPr(pkg.packageName);
6492                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
6493                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
6494                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
6495                                        allowed = true;
6496                                        allowed = true;
6497                                        break;
6498                                    }
6499                                }
6500                            }
6501                        } else {
6502                            allowed = true;
6503                        }
6504                        if (allowed) {
6505                            if (!mSharedLibraries.containsKey(name)) {
6506                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
6507                            } else if (!name.equals(pkg.packageName)) {
6508                                Slog.w(TAG, "Package " + pkg.packageName + " library "
6509                                        + name + " already exists; skipping");
6510                            }
6511                        } else {
6512                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
6513                                    + name + " that is not declared on system image; skipping");
6514                        }
6515                    }
6516                    if ((scanFlags&SCAN_BOOTING) == 0) {
6517                        // If we are not booting, we need to update any applications
6518                        // that are clients of our shared library.  If we are booting,
6519                        // this will all be done once the scan is complete.
6520                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
6521                    }
6522                }
6523            }
6524        }
6525
6526        // We also need to dexopt any apps that are dependent on this library.  Note that
6527        // if these fail, we should abort the install since installing the library will
6528        // result in some apps being broken.
6529        if (clientLibPkgs != null) {
6530            if ((scanFlags & SCAN_NO_DEX) == 0) {
6531                for (int i = 0; i < clientLibPkgs.size(); i++) {
6532                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
6533                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
6534                            null /* instruction sets */, forceDex,
6535                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
6536                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6537                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
6538                                "scanPackageLI failed to dexopt clientLibPkgs");
6539                    }
6540                }
6541            }
6542        }
6543
6544        // Also need to kill any apps that are dependent on the library.
6545        if (clientLibPkgs != null) {
6546            for (int i=0; i<clientLibPkgs.size(); i++) {
6547                PackageParser.Package clientPkg = clientLibPkgs.get(i);
6548                killApplication(clientPkg.applicationInfo.packageName,
6549                        clientPkg.applicationInfo.uid, "update lib");
6550            }
6551        }
6552
6553        // writer
6554        synchronized (mPackages) {
6555            // We don't expect installation to fail beyond this point
6556
6557            // Add the new setting to mSettings
6558            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
6559            // Add the new setting to mPackages
6560            mPackages.put(pkg.applicationInfo.packageName, pkg);
6561            // Make sure we don't accidentally delete its data.
6562            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
6563            while (iter.hasNext()) {
6564                PackageCleanItem item = iter.next();
6565                if (pkgName.equals(item.packageName)) {
6566                    iter.remove();
6567                }
6568            }
6569
6570            // Take care of first install / last update times.
6571            if (currentTime != 0) {
6572                if (pkgSetting.firstInstallTime == 0) {
6573                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
6574                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
6575                    pkgSetting.lastUpdateTime = currentTime;
6576                }
6577            } else if (pkgSetting.firstInstallTime == 0) {
6578                // We need *something*.  Take time time stamp of the file.
6579                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
6580            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
6581                if (scanFileTime != pkgSetting.timeStamp) {
6582                    // A package on the system image has changed; consider this
6583                    // to be an update.
6584                    pkgSetting.lastUpdateTime = scanFileTime;
6585                }
6586            }
6587
6588            // Add the package's KeySets to the global KeySetManagerService
6589            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6590            try {
6591                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
6592                if (pkg.mKeySetMapping != null) {
6593                    ksms.addDefinedKeySetsToPackageLPw(pkg.packageName, pkg.mKeySetMapping);
6594                    if (pkg.mUpgradeKeySets != null) {
6595                        ksms.addUpgradeKeySetsToPackageLPw(pkg.packageName, pkg.mUpgradeKeySets);
6596                    }
6597                }
6598            } catch (NullPointerException e) {
6599                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
6600            } catch (IllegalArgumentException e) {
6601                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
6602            }
6603
6604            int N = pkg.providers.size();
6605            StringBuilder r = null;
6606            int i;
6607            for (i=0; i<N; i++) {
6608                PackageParser.Provider p = pkg.providers.get(i);
6609                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
6610                        p.info.processName, pkg.applicationInfo.uid);
6611                mProviders.addProvider(p);
6612                p.syncable = p.info.isSyncable;
6613                if (p.info.authority != null) {
6614                    String names[] = p.info.authority.split(";");
6615                    p.info.authority = null;
6616                    for (int j = 0; j < names.length; j++) {
6617                        if (j == 1 && p.syncable) {
6618                            // We only want the first authority for a provider to possibly be
6619                            // syncable, so if we already added this provider using a different
6620                            // authority clear the syncable flag. We copy the provider before
6621                            // changing it because the mProviders object contains a reference
6622                            // to a provider that we don't want to change.
6623                            // Only do this for the second authority since the resulting provider
6624                            // object can be the same for all future authorities for this provider.
6625                            p = new PackageParser.Provider(p);
6626                            p.syncable = false;
6627                        }
6628                        if (!mProvidersByAuthority.containsKey(names[j])) {
6629                            mProvidersByAuthority.put(names[j], p);
6630                            if (p.info.authority == null) {
6631                                p.info.authority = names[j];
6632                            } else {
6633                                p.info.authority = p.info.authority + ";" + names[j];
6634                            }
6635                            if (DEBUG_PACKAGE_SCANNING) {
6636                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6637                                    Log.d(TAG, "Registered content provider: " + names[j]
6638                                            + ", className = " + p.info.name + ", isSyncable = "
6639                                            + p.info.isSyncable);
6640                            }
6641                        } else {
6642                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6643                            Slog.w(TAG, "Skipping provider name " + names[j] +
6644                                    " (in package " + pkg.applicationInfo.packageName +
6645                                    "): name already used by "
6646                                    + ((other != null && other.getComponentName() != null)
6647                                            ? other.getComponentName().getPackageName() : "?"));
6648                        }
6649                    }
6650                }
6651                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6652                    if (r == null) {
6653                        r = new StringBuilder(256);
6654                    } else {
6655                        r.append(' ');
6656                    }
6657                    r.append(p.info.name);
6658                }
6659            }
6660            if (r != null) {
6661                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
6662            }
6663
6664            N = pkg.services.size();
6665            r = null;
6666            for (i=0; i<N; i++) {
6667                PackageParser.Service s = pkg.services.get(i);
6668                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
6669                        s.info.processName, pkg.applicationInfo.uid);
6670                mServices.addService(s);
6671                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6672                    if (r == null) {
6673                        r = new StringBuilder(256);
6674                    } else {
6675                        r.append(' ');
6676                    }
6677                    r.append(s.info.name);
6678                }
6679            }
6680            if (r != null) {
6681                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
6682            }
6683
6684            N = pkg.receivers.size();
6685            r = null;
6686            for (i=0; i<N; i++) {
6687                PackageParser.Activity a = pkg.receivers.get(i);
6688                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6689                        a.info.processName, pkg.applicationInfo.uid);
6690                mReceivers.addActivity(a, "receiver");
6691                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6692                    if (r == null) {
6693                        r = new StringBuilder(256);
6694                    } else {
6695                        r.append(' ');
6696                    }
6697                    r.append(a.info.name);
6698                }
6699            }
6700            if (r != null) {
6701                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
6702            }
6703
6704            N = pkg.activities.size();
6705            r = null;
6706            for (i=0; i<N; i++) {
6707                PackageParser.Activity a = pkg.activities.get(i);
6708                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6709                        a.info.processName, pkg.applicationInfo.uid);
6710                mActivities.addActivity(a, "activity");
6711                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6712                    if (r == null) {
6713                        r = new StringBuilder(256);
6714                    } else {
6715                        r.append(' ');
6716                    }
6717                    r.append(a.info.name);
6718                }
6719            }
6720            if (r != null) {
6721                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
6722            }
6723
6724            N = pkg.permissionGroups.size();
6725            r = null;
6726            for (i=0; i<N; i++) {
6727                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
6728                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
6729                if (cur == null) {
6730                    mPermissionGroups.put(pg.info.name, pg);
6731                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6732                        if (r == null) {
6733                            r = new StringBuilder(256);
6734                        } else {
6735                            r.append(' ');
6736                        }
6737                        r.append(pg.info.name);
6738                    }
6739                } else {
6740                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
6741                            + pg.info.packageName + " ignored: original from "
6742                            + cur.info.packageName);
6743                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6744                        if (r == null) {
6745                            r = new StringBuilder(256);
6746                        } else {
6747                            r.append(' ');
6748                        }
6749                        r.append("DUP:");
6750                        r.append(pg.info.name);
6751                    }
6752                }
6753            }
6754            if (r != null) {
6755                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6756            }
6757
6758            N = pkg.permissions.size();
6759            r = null;
6760            for (i=0; i<N; i++) {
6761                PackageParser.Permission p = pkg.permissions.get(i);
6762
6763                // Now that permission groups have a special meaning, we ignore permission
6764                // groups for legacy apps to prevent unexpected behavior. In particular,
6765                // permissions for one app being granted to someone just becuase they happen
6766                // to be in a group defined by another app (before this had no implications).
6767                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
6768                    p.group = mPermissionGroups.get(p.info.group);
6769                    // Warn for a permission in an unknown group.
6770                    if (p.info.group != null && p.group == null) {
6771                        Slog.w(TAG, "Permission " + p.info.name + " from package "
6772                                + p.info.packageName + " in an unknown group " + p.info.group);
6773                    }
6774                }
6775
6776                ArrayMap<String, BasePermission> permissionMap =
6777                        p.tree ? mSettings.mPermissionTrees
6778                                : mSettings.mPermissions;
6779                BasePermission bp = permissionMap.get(p.info.name);
6780
6781                // Allow system apps to redefine non-system permissions
6782                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
6783                    final boolean currentOwnerIsSystem = (bp.perm != null
6784                            && isSystemApp(bp.perm.owner));
6785                    if (isSystemApp(p.owner)) {
6786                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
6787                            // It's a built-in permission and no owner, take ownership now
6788                            bp.packageSetting = pkgSetting;
6789                            bp.perm = p;
6790                            bp.uid = pkg.applicationInfo.uid;
6791                            bp.sourcePackage = p.info.packageName;
6792                        } else if (!currentOwnerIsSystem) {
6793                            String msg = "New decl " + p.owner + " of permission  "
6794                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
6795                            reportSettingsProblem(Log.WARN, msg);
6796                            bp = null;
6797                        }
6798                    }
6799                }
6800
6801                if (bp == null) {
6802                    bp = new BasePermission(p.info.name, p.info.packageName,
6803                            BasePermission.TYPE_NORMAL);
6804                    permissionMap.put(p.info.name, bp);
6805                }
6806
6807                if (bp.perm == null) {
6808                    if (bp.sourcePackage == null
6809                            || bp.sourcePackage.equals(p.info.packageName)) {
6810                        BasePermission tree = findPermissionTreeLP(p.info.name);
6811                        if (tree == null
6812                                || tree.sourcePackage.equals(p.info.packageName)) {
6813                            bp.packageSetting = pkgSetting;
6814                            bp.perm = p;
6815                            bp.uid = pkg.applicationInfo.uid;
6816                            bp.sourcePackage = p.info.packageName;
6817                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6818                                if (r == null) {
6819                                    r = new StringBuilder(256);
6820                                } else {
6821                                    r.append(' ');
6822                                }
6823                                r.append(p.info.name);
6824                            }
6825                        } else {
6826                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6827                                    + p.info.packageName + " ignored: base tree "
6828                                    + tree.name + " is from package "
6829                                    + tree.sourcePackage);
6830                        }
6831                    } else {
6832                        Slog.w(TAG, "Permission " + p.info.name + " from package "
6833                                + p.info.packageName + " ignored: original from "
6834                                + bp.sourcePackage);
6835                    }
6836                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6837                    if (r == null) {
6838                        r = new StringBuilder(256);
6839                    } else {
6840                        r.append(' ');
6841                    }
6842                    r.append("DUP:");
6843                    r.append(p.info.name);
6844                }
6845                if (bp.perm == p) {
6846                    bp.protectionLevel = p.info.protectionLevel;
6847                }
6848            }
6849
6850            if (r != null) {
6851                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6852            }
6853
6854            N = pkg.instrumentation.size();
6855            r = null;
6856            for (i=0; i<N; i++) {
6857                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6858                a.info.packageName = pkg.applicationInfo.packageName;
6859                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6860                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6861                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6862                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6863                a.info.dataDir = pkg.applicationInfo.dataDir;
6864
6865                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6866                // need other information about the application, like the ABI and what not ?
6867                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6868                mInstrumentation.put(a.getComponentName(), a);
6869                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6870                    if (r == null) {
6871                        r = new StringBuilder(256);
6872                    } else {
6873                        r.append(' ');
6874                    }
6875                    r.append(a.info.name);
6876                }
6877            }
6878            if (r != null) {
6879                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6880            }
6881
6882            if (pkg.protectedBroadcasts != null) {
6883                N = pkg.protectedBroadcasts.size();
6884                for (i=0; i<N; i++) {
6885                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6886                }
6887            }
6888
6889            pkgSetting.setTimeStamp(scanFileTime);
6890
6891            // Create idmap files for pairs of (packages, overlay packages).
6892            // Note: "android", ie framework-res.apk, is handled by native layers.
6893            if (pkg.mOverlayTarget != null) {
6894                // This is an overlay package.
6895                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6896                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6897                        mOverlays.put(pkg.mOverlayTarget,
6898                                new ArrayMap<String, PackageParser.Package>());
6899                    }
6900                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6901                    map.put(pkg.packageName, pkg);
6902                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6903                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6904                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6905                                "scanPackageLI failed to createIdmap");
6906                    }
6907                }
6908            } else if (mOverlays.containsKey(pkg.packageName) &&
6909                    !pkg.packageName.equals("android")) {
6910                // This is a regular package, with one or more known overlay packages.
6911                createIdmapsForPackageLI(pkg);
6912            }
6913        }
6914
6915        return pkg;
6916    }
6917
6918    /**
6919     * Derive the ABI of a non-system package located at {@code scanFile}. This information
6920     * is derived purely on the basis of the contents of {@code scanFile} and
6921     * {@code cpuAbiOverride}.
6922     *
6923     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
6924     */
6925    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
6926                                 String cpuAbiOverride, boolean extractLibs)
6927            throws PackageManagerException {
6928        // TODO: We can probably be smarter about this stuff. For installed apps,
6929        // we can calculate this information at install time once and for all. For
6930        // system apps, we can probably assume that this information doesn't change
6931        // after the first boot scan. As things stand, we do lots of unnecessary work.
6932
6933        // Give ourselves some initial paths; we'll come back for another
6934        // pass once we've determined ABI below.
6935        setNativeLibraryPaths(pkg);
6936
6937        // We would never need to extract libs for forward-locked and external packages,
6938        // since the container service will do it for us. We shouldn't attempt to
6939        // extract libs from system app when it was not updated.
6940        if (pkg.isForwardLocked() || isExternal(pkg) ||
6941            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
6942            extractLibs = false;
6943        }
6944
6945        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
6946        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
6947
6948        NativeLibraryHelper.Handle handle = null;
6949        try {
6950            handle = NativeLibraryHelper.Handle.create(scanFile);
6951            // TODO(multiArch): This can be null for apps that didn't go through the
6952            // usual installation process. We can calculate it again, like we
6953            // do during install time.
6954            //
6955            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
6956            // unnecessary.
6957            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
6958
6959            // Null out the abis so that they can be recalculated.
6960            pkg.applicationInfo.primaryCpuAbi = null;
6961            pkg.applicationInfo.secondaryCpuAbi = null;
6962            if (isMultiArch(pkg.applicationInfo)) {
6963                // Warn if we've set an abiOverride for multi-lib packages..
6964                // By definition, we need to copy both 32 and 64 bit libraries for
6965                // such packages.
6966                if (pkg.cpuAbiOverride != null
6967                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
6968                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
6969                }
6970
6971                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
6972                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
6973                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
6974                    if (extractLibs) {
6975                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
6976                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
6977                                useIsaSpecificSubdirs);
6978                    } else {
6979                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
6980                    }
6981                }
6982
6983                maybeThrowExceptionForMultiArchCopy(
6984                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
6985
6986                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
6987                    if (extractLibs) {
6988                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
6989                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
6990                                useIsaSpecificSubdirs);
6991                    } else {
6992                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
6993                    }
6994                }
6995
6996                maybeThrowExceptionForMultiArchCopy(
6997                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
6998
6999                if (abi64 >= 0) {
7000                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7001                }
7002
7003                if (abi32 >= 0) {
7004                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7005                    if (abi64 >= 0) {
7006                        pkg.applicationInfo.secondaryCpuAbi = abi;
7007                    } else {
7008                        pkg.applicationInfo.primaryCpuAbi = abi;
7009                    }
7010                }
7011            } else {
7012                String[] abiList = (cpuAbiOverride != null) ?
7013                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7014
7015                // Enable gross and lame hacks for apps that are built with old
7016                // SDK tools. We must scan their APKs for renderscript bitcode and
7017                // not launch them if it's present. Don't bother checking on devices
7018                // that don't have 64 bit support.
7019                boolean needsRenderScriptOverride = false;
7020                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7021                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7022                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7023                    needsRenderScriptOverride = true;
7024                }
7025
7026                final int copyRet;
7027                if (extractLibs) {
7028                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7029                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7030                } else {
7031                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7032                }
7033
7034                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7035                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7036                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7037                }
7038
7039                if (copyRet >= 0) {
7040                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7041                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7042                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7043                } else if (needsRenderScriptOverride) {
7044                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7045                }
7046            }
7047        } catch (IOException ioe) {
7048            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7049        } finally {
7050            IoUtils.closeQuietly(handle);
7051        }
7052
7053        // Now that we've calculated the ABIs and determined if it's an internal app,
7054        // we will go ahead and populate the nativeLibraryPath.
7055        setNativeLibraryPaths(pkg);
7056    }
7057
7058    /**
7059     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7060     * i.e, so that all packages can be run inside a single process if required.
7061     *
7062     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7063     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7064     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7065     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7066     * updating a package that belongs to a shared user.
7067     *
7068     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7069     * adds unnecessary complexity.
7070     */
7071    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7072            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7073        String requiredInstructionSet = null;
7074        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7075            requiredInstructionSet = VMRuntime.getInstructionSet(
7076                     scannedPackage.applicationInfo.primaryCpuAbi);
7077        }
7078
7079        PackageSetting requirer = null;
7080        for (PackageSetting ps : packagesForUser) {
7081            // If packagesForUser contains scannedPackage, we skip it. This will happen
7082            // when scannedPackage is an update of an existing package. Without this check,
7083            // we will never be able to change the ABI of any package belonging to a shared
7084            // user, even if it's compatible with other packages.
7085            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7086                if (ps.primaryCpuAbiString == null) {
7087                    continue;
7088                }
7089
7090                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7091                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7092                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7093                    // this but there's not much we can do.
7094                    String errorMessage = "Instruction set mismatch, "
7095                            + ((requirer == null) ? "[caller]" : requirer)
7096                            + " requires " + requiredInstructionSet + " whereas " + ps
7097                            + " requires " + instructionSet;
7098                    Slog.w(TAG, errorMessage);
7099                }
7100
7101                if (requiredInstructionSet == null) {
7102                    requiredInstructionSet = instructionSet;
7103                    requirer = ps;
7104                }
7105            }
7106        }
7107
7108        if (requiredInstructionSet != null) {
7109            String adjustedAbi;
7110            if (requirer != null) {
7111                // requirer != null implies that either scannedPackage was null or that scannedPackage
7112                // did not require an ABI, in which case we have to adjust scannedPackage to match
7113                // the ABI of the set (which is the same as requirer's ABI)
7114                adjustedAbi = requirer.primaryCpuAbiString;
7115                if (scannedPackage != null) {
7116                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7117                }
7118            } else {
7119                // requirer == null implies that we're updating all ABIs in the set to
7120                // match scannedPackage.
7121                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7122            }
7123
7124            for (PackageSetting ps : packagesForUser) {
7125                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7126                    if (ps.primaryCpuAbiString != null) {
7127                        continue;
7128                    }
7129
7130                    ps.primaryCpuAbiString = adjustedAbi;
7131                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7132                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7133                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7134
7135                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7136                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7137                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7138                            ps.primaryCpuAbiString = null;
7139                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7140                            return;
7141                        } else {
7142                            mInstaller.rmdex(ps.codePathString,
7143                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7144                        }
7145                    }
7146                }
7147            }
7148        }
7149    }
7150
7151    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7152        synchronized (mPackages) {
7153            mResolverReplaced = true;
7154            // Set up information for custom user intent resolution activity.
7155            mResolveActivity.applicationInfo = pkg.applicationInfo;
7156            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7157            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7158            mResolveActivity.processName = pkg.applicationInfo.packageName;
7159            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7160            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7161                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7162            mResolveActivity.theme = 0;
7163            mResolveActivity.exported = true;
7164            mResolveActivity.enabled = true;
7165            mResolveInfo.activityInfo = mResolveActivity;
7166            mResolveInfo.priority = 0;
7167            mResolveInfo.preferredOrder = 0;
7168            mResolveInfo.match = 0;
7169            mResolveComponentName = mCustomResolverComponentName;
7170            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7171                    mResolveComponentName);
7172        }
7173    }
7174
7175    private static String calculateBundledApkRoot(final String codePathString) {
7176        final File codePath = new File(codePathString);
7177        final File codeRoot;
7178        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7179            codeRoot = Environment.getRootDirectory();
7180        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7181            codeRoot = Environment.getOemDirectory();
7182        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7183            codeRoot = Environment.getVendorDirectory();
7184        } else {
7185            // Unrecognized code path; take its top real segment as the apk root:
7186            // e.g. /something/app/blah.apk => /something
7187            try {
7188                File f = codePath.getCanonicalFile();
7189                File parent = f.getParentFile();    // non-null because codePath is a file
7190                File tmp;
7191                while ((tmp = parent.getParentFile()) != null) {
7192                    f = parent;
7193                    parent = tmp;
7194                }
7195                codeRoot = f;
7196                Slog.w(TAG, "Unrecognized code path "
7197                        + codePath + " - using " + codeRoot);
7198            } catch (IOException e) {
7199                // Can't canonicalize the code path -- shenanigans?
7200                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7201                return Environment.getRootDirectory().getPath();
7202            }
7203        }
7204        return codeRoot.getPath();
7205    }
7206
7207    /**
7208     * Derive and set the location of native libraries for the given package,
7209     * which varies depending on where and how the package was installed.
7210     */
7211    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7212        final ApplicationInfo info = pkg.applicationInfo;
7213        final String codePath = pkg.codePath;
7214        final File codeFile = new File(codePath);
7215        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7216        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7217
7218        info.nativeLibraryRootDir = null;
7219        info.nativeLibraryRootRequiresIsa = false;
7220        info.nativeLibraryDir = null;
7221        info.secondaryNativeLibraryDir = null;
7222
7223        if (isApkFile(codeFile)) {
7224            // Monolithic install
7225            if (bundledApp) {
7226                // If "/system/lib64/apkname" exists, assume that is the per-package
7227                // native library directory to use; otherwise use "/system/lib/apkname".
7228                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7229                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7230                        getPrimaryInstructionSet(info));
7231
7232                // This is a bundled system app so choose the path based on the ABI.
7233                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7234                // is just the default path.
7235                final String apkName = deriveCodePathName(codePath);
7236                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7237                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7238                        apkName).getAbsolutePath();
7239
7240                if (info.secondaryCpuAbi != null) {
7241                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7242                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7243                            secondaryLibDir, apkName).getAbsolutePath();
7244                }
7245            } else if (asecApp) {
7246                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7247                        .getAbsolutePath();
7248            } else {
7249                final String apkName = deriveCodePathName(codePath);
7250                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7251                        .getAbsolutePath();
7252            }
7253
7254            info.nativeLibraryRootRequiresIsa = false;
7255            info.nativeLibraryDir = info.nativeLibraryRootDir;
7256        } else {
7257            // Cluster install
7258            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7259            info.nativeLibraryRootRequiresIsa = true;
7260
7261            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7262                    getPrimaryInstructionSet(info)).getAbsolutePath();
7263
7264            if (info.secondaryCpuAbi != null) {
7265                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7266                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7267            }
7268        }
7269    }
7270
7271    /**
7272     * Deduces the ABI of a bundled app and sets the relevant fields on the
7273     * parsed pkg object.
7274     *
7275     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7276     *        under which system libraries are installed.
7277     * @param apkName the name of the installed package.
7278     */
7279    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7280        final File codeFile = new File(pkg.codePath);
7281
7282        final boolean has64BitLibs;
7283        final boolean has32BitLibs;
7284        if (isApkFile(codeFile)) {
7285            // Monolithic install
7286            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7287            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7288        } else {
7289            // Cluster install
7290            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7291            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7292                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7293                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7294                has64BitLibs = (new File(rootDir, isa)).exists();
7295            } else {
7296                has64BitLibs = false;
7297            }
7298            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7299                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7300                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7301                has32BitLibs = (new File(rootDir, isa)).exists();
7302            } else {
7303                has32BitLibs = false;
7304            }
7305        }
7306
7307        if (has64BitLibs && !has32BitLibs) {
7308            // The package has 64 bit libs, but not 32 bit libs. Its primary
7309            // ABI should be 64 bit. We can safely assume here that the bundled
7310            // native libraries correspond to the most preferred ABI in the list.
7311
7312            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7313            pkg.applicationInfo.secondaryCpuAbi = null;
7314        } else if (has32BitLibs && !has64BitLibs) {
7315            // The package has 32 bit libs but not 64 bit libs. Its primary
7316            // ABI should be 32 bit.
7317
7318            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7319            pkg.applicationInfo.secondaryCpuAbi = null;
7320        } else if (has32BitLibs && has64BitLibs) {
7321            // The application has both 64 and 32 bit bundled libraries. We check
7322            // here that the app declares multiArch support, and warn if it doesn't.
7323            //
7324            // We will be lenient here and record both ABIs. The primary will be the
7325            // ABI that's higher on the list, i.e, a device that's configured to prefer
7326            // 64 bit apps will see a 64 bit primary ABI,
7327
7328            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7329                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7330            }
7331
7332            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7333                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7334                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7335            } else {
7336                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7337                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7338            }
7339        } else {
7340            pkg.applicationInfo.primaryCpuAbi = null;
7341            pkg.applicationInfo.secondaryCpuAbi = null;
7342        }
7343    }
7344
7345    private void killApplication(String pkgName, int appId, String reason) {
7346        // Request the ActivityManager to kill the process(only for existing packages)
7347        // so that we do not end up in a confused state while the user is still using the older
7348        // version of the application while the new one gets installed.
7349        IActivityManager am = ActivityManagerNative.getDefault();
7350        if (am != null) {
7351            try {
7352                am.killApplicationWithAppId(pkgName, appId, reason);
7353            } catch (RemoteException e) {
7354            }
7355        }
7356    }
7357
7358    void removePackageLI(PackageSetting ps, boolean chatty) {
7359        if (DEBUG_INSTALL) {
7360            if (chatty)
7361                Log.d(TAG, "Removing package " + ps.name);
7362        }
7363
7364        // writer
7365        synchronized (mPackages) {
7366            mPackages.remove(ps.name);
7367            final PackageParser.Package pkg = ps.pkg;
7368            if (pkg != null) {
7369                cleanPackageDataStructuresLILPw(pkg, chatty);
7370            }
7371        }
7372    }
7373
7374    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7375        if (DEBUG_INSTALL) {
7376            if (chatty)
7377                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7378        }
7379
7380        // writer
7381        synchronized (mPackages) {
7382            mPackages.remove(pkg.applicationInfo.packageName);
7383            cleanPackageDataStructuresLILPw(pkg, chatty);
7384        }
7385    }
7386
7387    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7388        int N = pkg.providers.size();
7389        StringBuilder r = null;
7390        int i;
7391        for (i=0; i<N; i++) {
7392            PackageParser.Provider p = pkg.providers.get(i);
7393            mProviders.removeProvider(p);
7394            if (p.info.authority == null) {
7395
7396                /* There was another ContentProvider with this authority when
7397                 * this app was installed so this authority is null,
7398                 * Ignore it as we don't have to unregister the provider.
7399                 */
7400                continue;
7401            }
7402            String names[] = p.info.authority.split(";");
7403            for (int j = 0; j < names.length; j++) {
7404                if (mProvidersByAuthority.get(names[j]) == p) {
7405                    mProvidersByAuthority.remove(names[j]);
7406                    if (DEBUG_REMOVE) {
7407                        if (chatty)
7408                            Log.d(TAG, "Unregistered content provider: " + names[j]
7409                                    + ", className = " + p.info.name + ", isSyncable = "
7410                                    + p.info.isSyncable);
7411                    }
7412                }
7413            }
7414            if (DEBUG_REMOVE && chatty) {
7415                if (r == null) {
7416                    r = new StringBuilder(256);
7417                } else {
7418                    r.append(' ');
7419                }
7420                r.append(p.info.name);
7421            }
7422        }
7423        if (r != null) {
7424            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7425        }
7426
7427        N = pkg.services.size();
7428        r = null;
7429        for (i=0; i<N; i++) {
7430            PackageParser.Service s = pkg.services.get(i);
7431            mServices.removeService(s);
7432            if (chatty) {
7433                if (r == null) {
7434                    r = new StringBuilder(256);
7435                } else {
7436                    r.append(' ');
7437                }
7438                r.append(s.info.name);
7439            }
7440        }
7441        if (r != null) {
7442            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
7443        }
7444
7445        N = pkg.receivers.size();
7446        r = null;
7447        for (i=0; i<N; i++) {
7448            PackageParser.Activity a = pkg.receivers.get(i);
7449            mReceivers.removeActivity(a, "receiver");
7450            if (DEBUG_REMOVE && chatty) {
7451                if (r == null) {
7452                    r = new StringBuilder(256);
7453                } else {
7454                    r.append(' ');
7455                }
7456                r.append(a.info.name);
7457            }
7458        }
7459        if (r != null) {
7460            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
7461        }
7462
7463        N = pkg.activities.size();
7464        r = null;
7465        for (i=0; i<N; i++) {
7466            PackageParser.Activity a = pkg.activities.get(i);
7467            mActivities.removeActivity(a, "activity");
7468            if (DEBUG_REMOVE && chatty) {
7469                if (r == null) {
7470                    r = new StringBuilder(256);
7471                } else {
7472                    r.append(' ');
7473                }
7474                r.append(a.info.name);
7475            }
7476        }
7477        if (r != null) {
7478            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
7479        }
7480
7481        N = pkg.permissions.size();
7482        r = null;
7483        for (i=0; i<N; i++) {
7484            PackageParser.Permission p = pkg.permissions.get(i);
7485            BasePermission bp = mSettings.mPermissions.get(p.info.name);
7486            if (bp == null) {
7487                bp = mSettings.mPermissionTrees.get(p.info.name);
7488            }
7489            if (bp != null && bp.perm == p) {
7490                bp.perm = null;
7491                if (DEBUG_REMOVE && chatty) {
7492                    if (r == null) {
7493                        r = new StringBuilder(256);
7494                    } else {
7495                        r.append(' ');
7496                    }
7497                    r.append(p.info.name);
7498                }
7499            }
7500            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7501                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
7502                if (appOpPerms != null) {
7503                    appOpPerms.remove(pkg.packageName);
7504                }
7505            }
7506        }
7507        if (r != null) {
7508            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7509        }
7510
7511        N = pkg.requestedPermissions.size();
7512        r = null;
7513        for (i=0; i<N; i++) {
7514            String perm = pkg.requestedPermissions.get(i);
7515            BasePermission bp = mSettings.mPermissions.get(perm);
7516            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7517                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
7518                if (appOpPerms != null) {
7519                    appOpPerms.remove(pkg.packageName);
7520                    if (appOpPerms.isEmpty()) {
7521                        mAppOpPermissionPackages.remove(perm);
7522                    }
7523                }
7524            }
7525        }
7526        if (r != null) {
7527            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7528        }
7529
7530        N = pkg.instrumentation.size();
7531        r = null;
7532        for (i=0; i<N; i++) {
7533            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7534            mInstrumentation.remove(a.getComponentName());
7535            if (DEBUG_REMOVE && chatty) {
7536                if (r == null) {
7537                    r = new StringBuilder(256);
7538                } else {
7539                    r.append(' ');
7540                }
7541                r.append(a.info.name);
7542            }
7543        }
7544        if (r != null) {
7545            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
7546        }
7547
7548        r = null;
7549        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7550            // Only system apps can hold shared libraries.
7551            if (pkg.libraryNames != null) {
7552                for (i=0; i<pkg.libraryNames.size(); i++) {
7553                    String name = pkg.libraryNames.get(i);
7554                    SharedLibraryEntry cur = mSharedLibraries.get(name);
7555                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
7556                        mSharedLibraries.remove(name);
7557                        if (DEBUG_REMOVE && chatty) {
7558                            if (r == null) {
7559                                r = new StringBuilder(256);
7560                            } else {
7561                                r.append(' ');
7562                            }
7563                            r.append(name);
7564                        }
7565                    }
7566                }
7567            }
7568        }
7569        if (r != null) {
7570            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
7571        }
7572    }
7573
7574    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
7575        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
7576            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
7577                return true;
7578            }
7579        }
7580        return false;
7581    }
7582
7583    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
7584    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
7585    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
7586
7587    private void updatePermissionsLPw(String changingPkg,
7588            PackageParser.Package pkgInfo, int flags) {
7589        // Make sure there are no dangling permission trees.
7590        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
7591        while (it.hasNext()) {
7592            final BasePermission bp = it.next();
7593            if (bp.packageSetting == null) {
7594                // We may not yet have parsed the package, so just see if
7595                // we still know about its settings.
7596                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7597            }
7598            if (bp.packageSetting == null) {
7599                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
7600                        + " from package " + bp.sourcePackage);
7601                it.remove();
7602            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7603                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7604                    Slog.i(TAG, "Removing old permission tree: " + bp.name
7605                            + " from package " + bp.sourcePackage);
7606                    flags |= UPDATE_PERMISSIONS_ALL;
7607                    it.remove();
7608                }
7609            }
7610        }
7611
7612        // Make sure all dynamic permissions have been assigned to a package,
7613        // and make sure there are no dangling permissions.
7614        it = mSettings.mPermissions.values().iterator();
7615        while (it.hasNext()) {
7616            final BasePermission bp = it.next();
7617            if (bp.type == BasePermission.TYPE_DYNAMIC) {
7618                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
7619                        + bp.name + " pkg=" + bp.sourcePackage
7620                        + " info=" + bp.pendingInfo);
7621                if (bp.packageSetting == null && bp.pendingInfo != null) {
7622                    final BasePermission tree = findPermissionTreeLP(bp.name);
7623                    if (tree != null && tree.perm != null) {
7624                        bp.packageSetting = tree.packageSetting;
7625                        bp.perm = new PackageParser.Permission(tree.perm.owner,
7626                                new PermissionInfo(bp.pendingInfo));
7627                        bp.perm.info.packageName = tree.perm.info.packageName;
7628                        bp.perm.info.name = bp.name;
7629                        bp.uid = tree.uid;
7630                    }
7631                }
7632            }
7633            if (bp.packageSetting == null) {
7634                // We may not yet have parsed the package, so just see if
7635                // we still know about its settings.
7636                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7637            }
7638            if (bp.packageSetting == null) {
7639                Slog.w(TAG, "Removing dangling permission: " + bp.name
7640                        + " from package " + bp.sourcePackage);
7641                it.remove();
7642            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7643                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7644                    Slog.i(TAG, "Removing old permission: " + bp.name
7645                            + " from package " + bp.sourcePackage);
7646                    flags |= UPDATE_PERMISSIONS_ALL;
7647                    it.remove();
7648                }
7649            }
7650        }
7651
7652        // Now update the permissions for all packages, in particular
7653        // replace the granted permissions of the system packages.
7654        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
7655            for (PackageParser.Package pkg : mPackages.values()) {
7656                if (pkg != pkgInfo) {
7657                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
7658                            changingPkg);
7659                }
7660            }
7661        }
7662
7663        if (pkgInfo != null) {
7664            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
7665        }
7666    }
7667
7668    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
7669            String packageOfInterest) {
7670        // IMPORTANT: There are two types of permissions: install and runtime.
7671        // Install time permissions are granted when the app is installed to
7672        // all device users and users added in the future. Runtime permissions
7673        // are granted at runtime explicitly to specific users. Normal and signature
7674        // protected permissions are install time permissions. Dangerous permissions
7675        // are install permissions if the app's target SDK is Lollipop MR1 or older,
7676        // otherwise they are runtime permissions. This function does not manage
7677        // runtime permissions except for the case an app targeting Lollipop MR1
7678        // being upgraded to target a newer SDK, in which case dangerous permissions
7679        // are transformed from install time to runtime ones.
7680
7681        final PackageSetting ps = (PackageSetting) pkg.mExtras;
7682        if (ps == null) {
7683            return;
7684        }
7685
7686        PermissionsState permissionsState = ps.getPermissionsState();
7687        PermissionsState origPermissions = permissionsState;
7688
7689        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
7690
7691        int[] upgradeUserIds = EMPTY_INT_ARRAY;
7692        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
7693
7694        boolean changedInstallPermission = false;
7695
7696        if (replace) {
7697            ps.installPermissionsFixed = false;
7698            if (!ps.isSharedUser()) {
7699                origPermissions = new PermissionsState(permissionsState);
7700                permissionsState.reset();
7701            }
7702        }
7703
7704        permissionsState.setGlobalGids(mGlobalGids);
7705
7706        final int N = pkg.requestedPermissions.size();
7707        for (int i=0; i<N; i++) {
7708            final String name = pkg.requestedPermissions.get(i);
7709            final BasePermission bp = mSettings.mPermissions.get(name);
7710
7711            if (DEBUG_INSTALL) {
7712                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
7713            }
7714
7715            if (bp == null || bp.packageSetting == null) {
7716                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7717                    Slog.w(TAG, "Unknown permission " + name
7718                            + " in package " + pkg.packageName);
7719                }
7720                continue;
7721            }
7722
7723            final String perm = bp.name;
7724            boolean allowedSig = false;
7725            int grant = GRANT_DENIED;
7726
7727            // Keep track of app op permissions.
7728            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7729                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
7730                if (pkgs == null) {
7731                    pkgs = new ArraySet<>();
7732                    mAppOpPermissionPackages.put(bp.name, pkgs);
7733                }
7734                pkgs.add(pkg.packageName);
7735            }
7736
7737            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
7738            switch (level) {
7739                case PermissionInfo.PROTECTION_NORMAL: {
7740                    // For all apps normal permissions are install time ones.
7741                    grant = GRANT_INSTALL;
7742                } break;
7743
7744                case PermissionInfo.PROTECTION_DANGEROUS: {
7745                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
7746                        // For legacy apps dangerous permissions are install time ones.
7747                        grant = GRANT_INSTALL_LEGACY;
7748                    } else if (ps.isSystem()) {
7749                        final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds();
7750                        if (origPermissions.hasInstallPermission(bp.name)) {
7751                            // If a system app had an install permission, then the app was
7752                            // upgraded and we grant the permissions as runtime to all users.
7753                            grant = GRANT_UPGRADE;
7754                            upgradeUserIds = currentUserIds;
7755                        } else if (!Arrays.equals(updatedUserIds, currentUserIds)) {
7756                            // If users changed since the last permissions update for a
7757                            // system app, we grant the permission as runtime to the new users.
7758                            grant = GRANT_UPGRADE;
7759                            upgradeUserIds = currentUserIds;
7760                            for (int userId : updatedUserIds) {
7761                                upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId);
7762                            }
7763                        } else {
7764                            // Otherwise, we grant the permission as runtime if the app
7765                            // already had it, i.e. we preserve runtime permissions.
7766                            grant = GRANT_RUNTIME;
7767                        }
7768                    } else if (origPermissions.hasInstallPermission(bp.name)) {
7769                        // For legacy apps that became modern, install becomes runtime.
7770                        grant = GRANT_UPGRADE;
7771                        upgradeUserIds = currentUserIds;
7772                    } else if (replace) {
7773                        // For upgraded modern apps keep runtime permissions unchanged.
7774                        grant = GRANT_RUNTIME;
7775                    }
7776                } break;
7777
7778                case PermissionInfo.PROTECTION_SIGNATURE: {
7779                    // For all apps signature permissions are install time ones.
7780                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
7781                    if (allowedSig) {
7782                        grant = GRANT_INSTALL;
7783                    }
7784                } break;
7785            }
7786
7787            if (DEBUG_INSTALL) {
7788                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
7789            }
7790
7791            if (grant != GRANT_DENIED) {
7792                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
7793                    // If this is an existing, non-system package, then
7794                    // we can't add any new permissions to it.
7795                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
7796                        // Except...  if this is a permission that was added
7797                        // to the platform (note: need to only do this when
7798                        // updating the platform).
7799                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
7800                            grant = GRANT_DENIED;
7801                        }
7802                    }
7803                }
7804
7805                switch (grant) {
7806                    case GRANT_INSTALL: {
7807                        // Revoke this as runtime permission to handle the case of
7808                        // a runtime permssion being downgraded to an install one.
7809                        for (int userId : UserManagerService.getInstance().getUserIds()) {
7810                            if (origPermissions.getRuntimePermissionState(
7811                                    bp.name, userId) != null) {
7812                                // Revoke the runtime permission and clear the flags.
7813                                origPermissions.revokeRuntimePermission(bp, userId);
7814                                origPermissions.updatePermissionFlags(bp, userId,
7815                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
7816                                // If we revoked a permission permission, we have to write.
7817                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7818                                        changedRuntimePermissionUserIds, userId);
7819                            }
7820                        }
7821                        // Grant an install permission.
7822                        if (permissionsState.grantInstallPermission(bp) !=
7823                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
7824                            changedInstallPermission = true;
7825                        }
7826                    } break;
7827
7828                    case GRANT_INSTALL_LEGACY: {
7829                        // Grant an install permission.
7830                        if (permissionsState.grantInstallPermission(bp) !=
7831                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
7832                            changedInstallPermission = true;
7833                        }
7834                    } break;
7835
7836                    case GRANT_RUNTIME: {
7837                        // Grant previously granted runtime permissions.
7838                        for (int userId : UserManagerService.getInstance().getUserIds()) {
7839                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
7840                                PermissionState permissionState = origPermissions
7841                                        .getRuntimePermissionState(bp.name, userId);
7842                                final int flags = permissionState.getFlags();
7843                                if (permissionsState.grantRuntimePermission(bp, userId) ==
7844                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7845                                    // If we cannot put the permission as it was, we have to write.
7846                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7847                                            changedRuntimePermissionUserIds, userId);
7848                                } else {
7849                                    // System components not only get the permissions but
7850                                    // they are also fixed, so nothing can change that.
7851                                    final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg)
7852                                            ? flags
7853                                            : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
7854                                    // Propagate the permission flags.
7855                                    permissionsState.updatePermissionFlags(bp, userId,
7856                                            newFlags, newFlags);
7857                                }
7858                            }
7859                        }
7860                    } break;
7861
7862                    case GRANT_UPGRADE: {
7863                        // Grant runtime permissions for a previously held install permission.
7864                        PermissionState permissionState = origPermissions
7865                                .getInstallPermissionState(bp.name);
7866                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
7867
7868                        origPermissions.revokeInstallPermission(bp);
7869                        // We will be transferring the permission flags, so clear them.
7870                        origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
7871                                PackageManager.MASK_PERMISSION_FLAGS, 0);
7872
7873                        // If the permission is not to be promoted to runtime we ignore it and
7874                        // also its other flags as they are not applicable to install permissions.
7875                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
7876                            for (int userId : upgradeUserIds) {
7877                                if (permissionsState.grantRuntimePermission(bp, userId) !=
7878                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7879                                    // System components not only get the permissions but
7880                                    // they are also fixed so nothing can change that.
7881                                    final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg)
7882                                            ? flags
7883                                            : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
7884                                    // Transfer the permission flags.
7885                                    permissionsState.updatePermissionFlags(bp, userId,
7886                                            newFlags, newFlags);
7887                                    // If we granted the permission, we have to write.
7888                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7889                                            changedRuntimePermissionUserIds, userId);
7890                                }
7891                            }
7892                        }
7893                    } break;
7894
7895                    default: {
7896                        if (packageOfInterest == null
7897                                || packageOfInterest.equals(pkg.packageName)) {
7898                            Slog.w(TAG, "Not granting permission " + perm
7899                                    + " to package " + pkg.packageName
7900                                    + " because it was previously installed without");
7901                        }
7902                    } break;
7903                }
7904            } else {
7905                if (permissionsState.revokeInstallPermission(bp) !=
7906                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7907                    // Also drop the permission flags.
7908                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
7909                            PackageManager.MASK_PERMISSION_FLAGS, 0);
7910                    changedInstallPermission = true;
7911                    Slog.i(TAG, "Un-granting permission " + perm
7912                            + " from package " + pkg.packageName
7913                            + " (protectionLevel=" + bp.protectionLevel
7914                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7915                            + ")");
7916                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
7917                    // Don't print warning for app op permissions, since it is fine for them
7918                    // not to be granted, there is a UI for the user to decide.
7919                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7920                        Slog.w(TAG, "Not granting permission " + perm
7921                                + " to package " + pkg.packageName
7922                                + " (protectionLevel=" + bp.protectionLevel
7923                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7924                                + ")");
7925                    }
7926                }
7927            }
7928        }
7929
7930        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
7931                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
7932            // This is the first that we have heard about this package, so the
7933            // permissions we have now selected are fixed until explicitly
7934            // changed.
7935            ps.installPermissionsFixed = true;
7936        }
7937
7938        ps.setPermissionsUpdatedForUserIds(currentUserIds);
7939
7940        // Persist the runtime permissions state for users with changes.
7941        for (int userId : changedRuntimePermissionUserIds) {
7942            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
7943        }
7944    }
7945
7946    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
7947        boolean allowed = false;
7948        final int NP = PackageParser.NEW_PERMISSIONS.length;
7949        for (int ip=0; ip<NP; ip++) {
7950            final PackageParser.NewPermissionInfo npi
7951                    = PackageParser.NEW_PERMISSIONS[ip];
7952            if (npi.name.equals(perm)
7953                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
7954                allowed = true;
7955                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
7956                        + pkg.packageName);
7957                break;
7958            }
7959        }
7960        return allowed;
7961    }
7962
7963    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
7964            BasePermission bp, PermissionsState origPermissions) {
7965        boolean allowed;
7966        allowed = (compareSignatures(
7967                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
7968                        == PackageManager.SIGNATURE_MATCH)
7969                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
7970                        == PackageManager.SIGNATURE_MATCH);
7971        if (!allowed && (bp.protectionLevel
7972                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
7973            if (isSystemApp(pkg)) {
7974                // For updated system applications, a system permission
7975                // is granted only if it had been defined by the original application.
7976                if (pkg.isUpdatedSystemApp()) {
7977                    final PackageSetting sysPs = mSettings
7978                            .getDisabledSystemPkgLPr(pkg.packageName);
7979                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
7980                        // If the original was granted this permission, we take
7981                        // that grant decision as read and propagate it to the
7982                        // update.
7983                        if (sysPs.isPrivileged()) {
7984                            allowed = true;
7985                        }
7986                    } else {
7987                        // The system apk may have been updated with an older
7988                        // version of the one on the data partition, but which
7989                        // granted a new system permission that it didn't have
7990                        // before.  In this case we do want to allow the app to
7991                        // now get the new permission if the ancestral apk is
7992                        // privileged to get it.
7993                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
7994                            for (int j=0;
7995                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
7996                                if (perm.equals(
7997                                        sysPs.pkg.requestedPermissions.get(j))) {
7998                                    allowed = true;
7999                                    break;
8000                                }
8001                            }
8002                        }
8003                    }
8004                } else {
8005                    allowed = isPrivilegedApp(pkg);
8006                }
8007            }
8008        }
8009        if (!allowed && (bp.protectionLevel
8010                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8011            // For development permissions, a development permission
8012            // is granted only if it was already granted.
8013            allowed = origPermissions.hasInstallPermission(perm);
8014        }
8015        return allowed;
8016    }
8017
8018    final class ActivityIntentResolver
8019            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8020        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8021                boolean defaultOnly, int userId) {
8022            if (!sUserManager.exists(userId)) return null;
8023            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8024            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8025        }
8026
8027        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8028                int userId) {
8029            if (!sUserManager.exists(userId)) return null;
8030            mFlags = flags;
8031            return super.queryIntent(intent, resolvedType,
8032                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8033        }
8034
8035        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8036                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8037            if (!sUserManager.exists(userId)) return null;
8038            if (packageActivities == null) {
8039                return null;
8040            }
8041            mFlags = flags;
8042            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8043            final int N = packageActivities.size();
8044            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8045                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8046
8047            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8048            for (int i = 0; i < N; ++i) {
8049                intentFilters = packageActivities.get(i).intents;
8050                if (intentFilters != null && intentFilters.size() > 0) {
8051                    PackageParser.ActivityIntentInfo[] array =
8052                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8053                    intentFilters.toArray(array);
8054                    listCut.add(array);
8055                }
8056            }
8057            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8058        }
8059
8060        public final void addActivity(PackageParser.Activity a, String type) {
8061            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8062            mActivities.put(a.getComponentName(), a);
8063            if (DEBUG_SHOW_INFO)
8064                Log.v(
8065                TAG, "  " + type + " " +
8066                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8067            if (DEBUG_SHOW_INFO)
8068                Log.v(TAG, "    Class=" + a.info.name);
8069            final int NI = a.intents.size();
8070            for (int j=0; j<NI; j++) {
8071                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8072                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8073                    intent.setPriority(0);
8074                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8075                            + a.className + " with priority > 0, forcing to 0");
8076                }
8077                if (DEBUG_SHOW_INFO) {
8078                    Log.v(TAG, "    IntentFilter:");
8079                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8080                }
8081                if (!intent.debugCheck()) {
8082                    Log.w(TAG, "==> For Activity " + a.info.name);
8083                }
8084                addFilter(intent);
8085            }
8086        }
8087
8088        public final void removeActivity(PackageParser.Activity a, String type) {
8089            mActivities.remove(a.getComponentName());
8090            if (DEBUG_SHOW_INFO) {
8091                Log.v(TAG, "  " + type + " "
8092                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8093                                : a.info.name) + ":");
8094                Log.v(TAG, "    Class=" + a.info.name);
8095            }
8096            final int NI = a.intents.size();
8097            for (int j=0; j<NI; j++) {
8098                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8099                if (DEBUG_SHOW_INFO) {
8100                    Log.v(TAG, "    IntentFilter:");
8101                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8102                }
8103                removeFilter(intent);
8104            }
8105        }
8106
8107        @Override
8108        protected boolean allowFilterResult(
8109                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8110            ActivityInfo filterAi = filter.activity.info;
8111            for (int i=dest.size()-1; i>=0; i--) {
8112                ActivityInfo destAi = dest.get(i).activityInfo;
8113                if (destAi.name == filterAi.name
8114                        && destAi.packageName == filterAi.packageName) {
8115                    return false;
8116                }
8117            }
8118            return true;
8119        }
8120
8121        @Override
8122        protected ActivityIntentInfo[] newArray(int size) {
8123            return new ActivityIntentInfo[size];
8124        }
8125
8126        @Override
8127        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8128            if (!sUserManager.exists(userId)) return true;
8129            PackageParser.Package p = filter.activity.owner;
8130            if (p != null) {
8131                PackageSetting ps = (PackageSetting)p.mExtras;
8132                if (ps != null) {
8133                    // System apps are never considered stopped for purposes of
8134                    // filtering, because there may be no way for the user to
8135                    // actually re-launch them.
8136                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8137                            && ps.getStopped(userId);
8138                }
8139            }
8140            return false;
8141        }
8142
8143        @Override
8144        protected boolean isPackageForFilter(String packageName,
8145                PackageParser.ActivityIntentInfo info) {
8146            return packageName.equals(info.activity.owner.packageName);
8147        }
8148
8149        @Override
8150        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8151                int match, int userId) {
8152            if (!sUserManager.exists(userId)) return null;
8153            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8154                return null;
8155            }
8156            final PackageParser.Activity activity = info.activity;
8157            if (mSafeMode && (activity.info.applicationInfo.flags
8158                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8159                return null;
8160            }
8161            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8162            if (ps == null) {
8163                return null;
8164            }
8165            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8166                    ps.readUserState(userId), userId);
8167            if (ai == null) {
8168                return null;
8169            }
8170            final ResolveInfo res = new ResolveInfo();
8171            res.activityInfo = ai;
8172            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8173                res.filter = info;
8174            }
8175            if (info != null) {
8176                res.handleAllWebDataURI = info.handleAllWebDataURI();
8177            }
8178            res.priority = info.getPriority();
8179            res.preferredOrder = activity.owner.mPreferredOrder;
8180            //System.out.println("Result: " + res.activityInfo.className +
8181            //                   " = " + res.priority);
8182            res.match = match;
8183            res.isDefault = info.hasDefault;
8184            res.labelRes = info.labelRes;
8185            res.nonLocalizedLabel = info.nonLocalizedLabel;
8186            if (userNeedsBadging(userId)) {
8187                res.noResourceId = true;
8188            } else {
8189                res.icon = info.icon;
8190            }
8191            res.system = res.activityInfo.applicationInfo.isSystemApp();
8192            return res;
8193        }
8194
8195        @Override
8196        protected void sortResults(List<ResolveInfo> results) {
8197            Collections.sort(results, mResolvePrioritySorter);
8198        }
8199
8200        @Override
8201        protected void dumpFilter(PrintWriter out, String prefix,
8202                PackageParser.ActivityIntentInfo filter) {
8203            out.print(prefix); out.print(
8204                    Integer.toHexString(System.identityHashCode(filter.activity)));
8205                    out.print(' ');
8206                    filter.activity.printComponentShortName(out);
8207                    out.print(" filter ");
8208                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8209        }
8210
8211        @Override
8212        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8213            return filter.activity;
8214        }
8215
8216        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8217            PackageParser.Activity activity = (PackageParser.Activity)label;
8218            out.print(prefix); out.print(
8219                    Integer.toHexString(System.identityHashCode(activity)));
8220                    out.print(' ');
8221                    activity.printComponentShortName(out);
8222            if (count > 1) {
8223                out.print(" ("); out.print(count); out.print(" filters)");
8224            }
8225            out.println();
8226        }
8227
8228//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8229//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8230//            final List<ResolveInfo> retList = Lists.newArrayList();
8231//            while (i.hasNext()) {
8232//                final ResolveInfo resolveInfo = i.next();
8233//                if (isEnabledLP(resolveInfo.activityInfo)) {
8234//                    retList.add(resolveInfo);
8235//                }
8236//            }
8237//            return retList;
8238//        }
8239
8240        // Keys are String (activity class name), values are Activity.
8241        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8242                = new ArrayMap<ComponentName, PackageParser.Activity>();
8243        private int mFlags;
8244    }
8245
8246    private final class ServiceIntentResolver
8247            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8248        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8249                boolean defaultOnly, int userId) {
8250            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8251            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8252        }
8253
8254        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8255                int userId) {
8256            if (!sUserManager.exists(userId)) return null;
8257            mFlags = flags;
8258            return super.queryIntent(intent, resolvedType,
8259                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8260        }
8261
8262        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8263                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8264            if (!sUserManager.exists(userId)) return null;
8265            if (packageServices == null) {
8266                return null;
8267            }
8268            mFlags = flags;
8269            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8270            final int N = packageServices.size();
8271            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8272                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8273
8274            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8275            for (int i = 0; i < N; ++i) {
8276                intentFilters = packageServices.get(i).intents;
8277                if (intentFilters != null && intentFilters.size() > 0) {
8278                    PackageParser.ServiceIntentInfo[] array =
8279                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8280                    intentFilters.toArray(array);
8281                    listCut.add(array);
8282                }
8283            }
8284            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8285        }
8286
8287        public final void addService(PackageParser.Service s) {
8288            mServices.put(s.getComponentName(), s);
8289            if (DEBUG_SHOW_INFO) {
8290                Log.v(TAG, "  "
8291                        + (s.info.nonLocalizedLabel != null
8292                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8293                Log.v(TAG, "    Class=" + s.info.name);
8294            }
8295            final int NI = s.intents.size();
8296            int j;
8297            for (j=0; j<NI; j++) {
8298                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8299                if (DEBUG_SHOW_INFO) {
8300                    Log.v(TAG, "    IntentFilter:");
8301                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8302                }
8303                if (!intent.debugCheck()) {
8304                    Log.w(TAG, "==> For Service " + s.info.name);
8305                }
8306                addFilter(intent);
8307            }
8308        }
8309
8310        public final void removeService(PackageParser.Service s) {
8311            mServices.remove(s.getComponentName());
8312            if (DEBUG_SHOW_INFO) {
8313                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8314                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8315                Log.v(TAG, "    Class=" + s.info.name);
8316            }
8317            final int NI = s.intents.size();
8318            int j;
8319            for (j=0; j<NI; j++) {
8320                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8321                if (DEBUG_SHOW_INFO) {
8322                    Log.v(TAG, "    IntentFilter:");
8323                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8324                }
8325                removeFilter(intent);
8326            }
8327        }
8328
8329        @Override
8330        protected boolean allowFilterResult(
8331                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8332            ServiceInfo filterSi = filter.service.info;
8333            for (int i=dest.size()-1; i>=0; i--) {
8334                ServiceInfo destAi = dest.get(i).serviceInfo;
8335                if (destAi.name == filterSi.name
8336                        && destAi.packageName == filterSi.packageName) {
8337                    return false;
8338                }
8339            }
8340            return true;
8341        }
8342
8343        @Override
8344        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8345            return new PackageParser.ServiceIntentInfo[size];
8346        }
8347
8348        @Override
8349        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8350            if (!sUserManager.exists(userId)) return true;
8351            PackageParser.Package p = filter.service.owner;
8352            if (p != null) {
8353                PackageSetting ps = (PackageSetting)p.mExtras;
8354                if (ps != null) {
8355                    // System apps are never considered stopped for purposes of
8356                    // filtering, because there may be no way for the user to
8357                    // actually re-launch them.
8358                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8359                            && ps.getStopped(userId);
8360                }
8361            }
8362            return false;
8363        }
8364
8365        @Override
8366        protected boolean isPackageForFilter(String packageName,
8367                PackageParser.ServiceIntentInfo info) {
8368            return packageName.equals(info.service.owner.packageName);
8369        }
8370
8371        @Override
8372        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8373                int match, int userId) {
8374            if (!sUserManager.exists(userId)) return null;
8375            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8376            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8377                return null;
8378            }
8379            final PackageParser.Service service = info.service;
8380            if (mSafeMode && (service.info.applicationInfo.flags
8381                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8382                return null;
8383            }
8384            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8385            if (ps == null) {
8386                return null;
8387            }
8388            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8389                    ps.readUserState(userId), userId);
8390            if (si == null) {
8391                return null;
8392            }
8393            final ResolveInfo res = new ResolveInfo();
8394            res.serviceInfo = si;
8395            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8396                res.filter = filter;
8397            }
8398            res.priority = info.getPriority();
8399            res.preferredOrder = service.owner.mPreferredOrder;
8400            res.match = match;
8401            res.isDefault = info.hasDefault;
8402            res.labelRes = info.labelRes;
8403            res.nonLocalizedLabel = info.nonLocalizedLabel;
8404            res.icon = info.icon;
8405            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8406            return res;
8407        }
8408
8409        @Override
8410        protected void sortResults(List<ResolveInfo> results) {
8411            Collections.sort(results, mResolvePrioritySorter);
8412        }
8413
8414        @Override
8415        protected void dumpFilter(PrintWriter out, String prefix,
8416                PackageParser.ServiceIntentInfo filter) {
8417            out.print(prefix); out.print(
8418                    Integer.toHexString(System.identityHashCode(filter.service)));
8419                    out.print(' ');
8420                    filter.service.printComponentShortName(out);
8421                    out.print(" filter ");
8422                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8423        }
8424
8425        @Override
8426        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8427            return filter.service;
8428        }
8429
8430        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8431            PackageParser.Service service = (PackageParser.Service)label;
8432            out.print(prefix); out.print(
8433                    Integer.toHexString(System.identityHashCode(service)));
8434                    out.print(' ');
8435                    service.printComponentShortName(out);
8436            if (count > 1) {
8437                out.print(" ("); out.print(count); out.print(" filters)");
8438            }
8439            out.println();
8440        }
8441
8442//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8443//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8444//            final List<ResolveInfo> retList = Lists.newArrayList();
8445//            while (i.hasNext()) {
8446//                final ResolveInfo resolveInfo = (ResolveInfo) i;
8447//                if (isEnabledLP(resolveInfo.serviceInfo)) {
8448//                    retList.add(resolveInfo);
8449//                }
8450//            }
8451//            return retList;
8452//        }
8453
8454        // Keys are String (activity class name), values are Activity.
8455        private final ArrayMap<ComponentName, PackageParser.Service> mServices
8456                = new ArrayMap<ComponentName, PackageParser.Service>();
8457        private int mFlags;
8458    };
8459
8460    private final class ProviderIntentResolver
8461            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
8462        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8463                boolean defaultOnly, int userId) {
8464            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8465            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8466        }
8467
8468        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8469                int userId) {
8470            if (!sUserManager.exists(userId))
8471                return null;
8472            mFlags = flags;
8473            return super.queryIntent(intent, resolvedType,
8474                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8475        }
8476
8477        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8478                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
8479            if (!sUserManager.exists(userId))
8480                return null;
8481            if (packageProviders == null) {
8482                return null;
8483            }
8484            mFlags = flags;
8485            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
8486            final int N = packageProviders.size();
8487            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
8488                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
8489
8490            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
8491            for (int i = 0; i < N; ++i) {
8492                intentFilters = packageProviders.get(i).intents;
8493                if (intentFilters != null && intentFilters.size() > 0) {
8494                    PackageParser.ProviderIntentInfo[] array =
8495                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
8496                    intentFilters.toArray(array);
8497                    listCut.add(array);
8498                }
8499            }
8500            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8501        }
8502
8503        public final void addProvider(PackageParser.Provider p) {
8504            if (mProviders.containsKey(p.getComponentName())) {
8505                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
8506                return;
8507            }
8508
8509            mProviders.put(p.getComponentName(), p);
8510            if (DEBUG_SHOW_INFO) {
8511                Log.v(TAG, "  "
8512                        + (p.info.nonLocalizedLabel != null
8513                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
8514                Log.v(TAG, "    Class=" + p.info.name);
8515            }
8516            final int NI = p.intents.size();
8517            int j;
8518            for (j = 0; j < NI; j++) {
8519                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8520                if (DEBUG_SHOW_INFO) {
8521                    Log.v(TAG, "    IntentFilter:");
8522                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8523                }
8524                if (!intent.debugCheck()) {
8525                    Log.w(TAG, "==> For Provider " + p.info.name);
8526                }
8527                addFilter(intent);
8528            }
8529        }
8530
8531        public final void removeProvider(PackageParser.Provider p) {
8532            mProviders.remove(p.getComponentName());
8533            if (DEBUG_SHOW_INFO) {
8534                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
8535                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
8536                Log.v(TAG, "    Class=" + p.info.name);
8537            }
8538            final int NI = p.intents.size();
8539            int j;
8540            for (j = 0; j < NI; j++) {
8541                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8542                if (DEBUG_SHOW_INFO) {
8543                    Log.v(TAG, "    IntentFilter:");
8544                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8545                }
8546                removeFilter(intent);
8547            }
8548        }
8549
8550        @Override
8551        protected boolean allowFilterResult(
8552                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
8553            ProviderInfo filterPi = filter.provider.info;
8554            for (int i = dest.size() - 1; i >= 0; i--) {
8555                ProviderInfo destPi = dest.get(i).providerInfo;
8556                if (destPi.name == filterPi.name
8557                        && destPi.packageName == filterPi.packageName) {
8558                    return false;
8559                }
8560            }
8561            return true;
8562        }
8563
8564        @Override
8565        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
8566            return new PackageParser.ProviderIntentInfo[size];
8567        }
8568
8569        @Override
8570        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
8571            if (!sUserManager.exists(userId))
8572                return true;
8573            PackageParser.Package p = filter.provider.owner;
8574            if (p != null) {
8575                PackageSetting ps = (PackageSetting) p.mExtras;
8576                if (ps != null) {
8577                    // System apps are never considered stopped for purposes of
8578                    // filtering, because there may be no way for the user to
8579                    // actually re-launch them.
8580                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8581                            && ps.getStopped(userId);
8582                }
8583            }
8584            return false;
8585        }
8586
8587        @Override
8588        protected boolean isPackageForFilter(String packageName,
8589                PackageParser.ProviderIntentInfo info) {
8590            return packageName.equals(info.provider.owner.packageName);
8591        }
8592
8593        @Override
8594        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
8595                int match, int userId) {
8596            if (!sUserManager.exists(userId))
8597                return null;
8598            final PackageParser.ProviderIntentInfo info = filter;
8599            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
8600                return null;
8601            }
8602            final PackageParser.Provider provider = info.provider;
8603            if (mSafeMode && (provider.info.applicationInfo.flags
8604                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
8605                return null;
8606            }
8607            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
8608            if (ps == null) {
8609                return null;
8610            }
8611            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
8612                    ps.readUserState(userId), userId);
8613            if (pi == null) {
8614                return null;
8615            }
8616            final ResolveInfo res = new ResolveInfo();
8617            res.providerInfo = pi;
8618            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
8619                res.filter = filter;
8620            }
8621            res.priority = info.getPriority();
8622            res.preferredOrder = provider.owner.mPreferredOrder;
8623            res.match = match;
8624            res.isDefault = info.hasDefault;
8625            res.labelRes = info.labelRes;
8626            res.nonLocalizedLabel = info.nonLocalizedLabel;
8627            res.icon = info.icon;
8628            res.system = res.providerInfo.applicationInfo.isSystemApp();
8629            return res;
8630        }
8631
8632        @Override
8633        protected void sortResults(List<ResolveInfo> results) {
8634            Collections.sort(results, mResolvePrioritySorter);
8635        }
8636
8637        @Override
8638        protected void dumpFilter(PrintWriter out, String prefix,
8639                PackageParser.ProviderIntentInfo filter) {
8640            out.print(prefix);
8641            out.print(
8642                    Integer.toHexString(System.identityHashCode(filter.provider)));
8643            out.print(' ');
8644            filter.provider.printComponentShortName(out);
8645            out.print(" filter ");
8646            out.println(Integer.toHexString(System.identityHashCode(filter)));
8647        }
8648
8649        @Override
8650        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
8651            return filter.provider;
8652        }
8653
8654        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8655            PackageParser.Provider provider = (PackageParser.Provider)label;
8656            out.print(prefix); out.print(
8657                    Integer.toHexString(System.identityHashCode(provider)));
8658                    out.print(' ');
8659                    provider.printComponentShortName(out);
8660            if (count > 1) {
8661                out.print(" ("); out.print(count); out.print(" filters)");
8662            }
8663            out.println();
8664        }
8665
8666        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
8667                = new ArrayMap<ComponentName, PackageParser.Provider>();
8668        private int mFlags;
8669    };
8670
8671    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
8672            new Comparator<ResolveInfo>() {
8673        public int compare(ResolveInfo r1, ResolveInfo r2) {
8674            int v1 = r1.priority;
8675            int v2 = r2.priority;
8676            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
8677            if (v1 != v2) {
8678                return (v1 > v2) ? -1 : 1;
8679            }
8680            v1 = r1.preferredOrder;
8681            v2 = r2.preferredOrder;
8682            if (v1 != v2) {
8683                return (v1 > v2) ? -1 : 1;
8684            }
8685            if (r1.isDefault != r2.isDefault) {
8686                return r1.isDefault ? -1 : 1;
8687            }
8688            v1 = r1.match;
8689            v2 = r2.match;
8690            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
8691            if (v1 != v2) {
8692                return (v1 > v2) ? -1 : 1;
8693            }
8694            if (r1.system != r2.system) {
8695                return r1.system ? -1 : 1;
8696            }
8697            return 0;
8698        }
8699    };
8700
8701    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
8702            new Comparator<ProviderInfo>() {
8703        public int compare(ProviderInfo p1, ProviderInfo p2) {
8704            final int v1 = p1.initOrder;
8705            final int v2 = p2.initOrder;
8706            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
8707        }
8708    };
8709
8710    final void sendPackageBroadcast(final String action, final String pkg,
8711            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
8712            final int[] userIds) {
8713        mHandler.post(new Runnable() {
8714            @Override
8715            public void run() {
8716                try {
8717                    final IActivityManager am = ActivityManagerNative.getDefault();
8718                    if (am == null) return;
8719                    final int[] resolvedUserIds;
8720                    if (userIds == null) {
8721                        resolvedUserIds = am.getRunningUserIds();
8722                    } else {
8723                        resolvedUserIds = userIds;
8724                    }
8725                    for (int id : resolvedUserIds) {
8726                        final Intent intent = new Intent(action,
8727                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
8728                        if (extras != null) {
8729                            intent.putExtras(extras);
8730                        }
8731                        if (targetPkg != null) {
8732                            intent.setPackage(targetPkg);
8733                        }
8734                        // Modify the UID when posting to other users
8735                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
8736                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
8737                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
8738                            intent.putExtra(Intent.EXTRA_UID, uid);
8739                        }
8740                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
8741                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
8742                        if (DEBUG_BROADCASTS) {
8743                            RuntimeException here = new RuntimeException("here");
8744                            here.fillInStackTrace();
8745                            Slog.d(TAG, "Sending to user " + id + ": "
8746                                    + intent.toShortString(false, true, false, false)
8747                                    + " " + intent.getExtras(), here);
8748                        }
8749                        am.broadcastIntent(null, intent, null, finishedReceiver,
8750                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
8751                                finishedReceiver != null, false, id);
8752                    }
8753                } catch (RemoteException ex) {
8754                }
8755            }
8756        });
8757    }
8758
8759    /**
8760     * Check if the external storage media is available. This is true if there
8761     * is a mounted external storage medium or if the external storage is
8762     * emulated.
8763     */
8764    private boolean isExternalMediaAvailable() {
8765        return mMediaMounted || Environment.isExternalStorageEmulated();
8766    }
8767
8768    @Override
8769    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
8770        // writer
8771        synchronized (mPackages) {
8772            if (!isExternalMediaAvailable()) {
8773                // If the external storage is no longer mounted at this point,
8774                // the caller may not have been able to delete all of this
8775                // packages files and can not delete any more.  Bail.
8776                return null;
8777            }
8778            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
8779            if (lastPackage != null) {
8780                pkgs.remove(lastPackage);
8781            }
8782            if (pkgs.size() > 0) {
8783                return pkgs.get(0);
8784            }
8785        }
8786        return null;
8787    }
8788
8789    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
8790        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
8791                userId, andCode ? 1 : 0, packageName);
8792        if (mSystemReady) {
8793            msg.sendToTarget();
8794        } else {
8795            if (mPostSystemReadyMessages == null) {
8796                mPostSystemReadyMessages = new ArrayList<>();
8797            }
8798            mPostSystemReadyMessages.add(msg);
8799        }
8800    }
8801
8802    void startCleaningPackages() {
8803        // reader
8804        synchronized (mPackages) {
8805            if (!isExternalMediaAvailable()) {
8806                return;
8807            }
8808            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
8809                return;
8810            }
8811        }
8812        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
8813        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
8814        IActivityManager am = ActivityManagerNative.getDefault();
8815        if (am != null) {
8816            try {
8817                am.startService(null, intent, null, UserHandle.USER_OWNER);
8818            } catch (RemoteException e) {
8819            }
8820        }
8821    }
8822
8823    @Override
8824    public void installPackage(String originPath, IPackageInstallObserver2 observer,
8825            int installFlags, String installerPackageName, VerificationParams verificationParams,
8826            String packageAbiOverride) {
8827        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
8828                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
8829    }
8830
8831    @Override
8832    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
8833            int installFlags, String installerPackageName, VerificationParams verificationParams,
8834            String packageAbiOverride, int userId) {
8835        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
8836
8837        final int callingUid = Binder.getCallingUid();
8838        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
8839
8840        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8841            try {
8842                if (observer != null) {
8843                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
8844                }
8845            } catch (RemoteException re) {
8846            }
8847            return;
8848        }
8849
8850        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
8851            installFlags |= PackageManager.INSTALL_FROM_ADB;
8852
8853        } else {
8854            // Caller holds INSTALL_PACKAGES permission, so we're less strict
8855            // about installerPackageName.
8856
8857            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
8858            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
8859        }
8860
8861        UserHandle user;
8862        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
8863            user = UserHandle.ALL;
8864        } else {
8865            user = new UserHandle(userId);
8866        }
8867
8868        // Only system components can circumvent runtime permissions when installing.
8869        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
8870                && mContext.checkCallingOrSelfPermission(Manifest.permission
8871                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
8872            throw new SecurityException("You need the "
8873                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
8874                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
8875        }
8876
8877        verificationParams.setInstallerUid(callingUid);
8878
8879        final File originFile = new File(originPath);
8880        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
8881
8882        final Message msg = mHandler.obtainMessage(INIT_COPY);
8883        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
8884                null, verificationParams, user, packageAbiOverride);
8885        mHandler.sendMessage(msg);
8886    }
8887
8888    void installStage(String packageName, File stagedDir, String stagedCid,
8889            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
8890            String installerPackageName, int installerUid, UserHandle user) {
8891        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
8892                params.referrerUri, installerUid, null);
8893
8894        final OriginInfo origin;
8895        if (stagedDir != null) {
8896            origin = OriginInfo.fromStagedFile(stagedDir);
8897        } else {
8898            origin = OriginInfo.fromStagedContainer(stagedCid);
8899        }
8900
8901        final Message msg = mHandler.obtainMessage(INIT_COPY);
8902        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
8903                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
8904        mHandler.sendMessage(msg);
8905    }
8906
8907    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
8908        Bundle extras = new Bundle(1);
8909        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
8910
8911        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
8912                packageName, extras, null, null, new int[] {userId});
8913        try {
8914            IActivityManager am = ActivityManagerNative.getDefault();
8915            final boolean isSystem =
8916                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
8917            if (isSystem && am.isUserRunning(userId, false)) {
8918                // The just-installed/enabled app is bundled on the system, so presumed
8919                // to be able to run automatically without needing an explicit launch.
8920                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
8921                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
8922                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
8923                        .setPackage(packageName);
8924                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
8925                        android.app.AppOpsManager.OP_NONE, false, false, userId);
8926            }
8927        } catch (RemoteException e) {
8928            // shouldn't happen
8929            Slog.w(TAG, "Unable to bootstrap installed package", e);
8930        }
8931    }
8932
8933    @Override
8934    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
8935            int userId) {
8936        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8937        PackageSetting pkgSetting;
8938        final int uid = Binder.getCallingUid();
8939        enforceCrossUserPermission(uid, userId, true, true,
8940                "setApplicationHiddenSetting for user " + userId);
8941
8942        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
8943            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
8944            return false;
8945        }
8946
8947        long callingId = Binder.clearCallingIdentity();
8948        try {
8949            boolean sendAdded = false;
8950            boolean sendRemoved = false;
8951            // writer
8952            synchronized (mPackages) {
8953                pkgSetting = mSettings.mPackages.get(packageName);
8954                if (pkgSetting == null) {
8955                    return false;
8956                }
8957                if (pkgSetting.getHidden(userId) != hidden) {
8958                    pkgSetting.setHidden(hidden, userId);
8959                    mSettings.writePackageRestrictionsLPr(userId);
8960                    if (hidden) {
8961                        sendRemoved = true;
8962                    } else {
8963                        sendAdded = true;
8964                    }
8965                }
8966            }
8967            if (sendAdded) {
8968                sendPackageAddedForUser(packageName, pkgSetting, userId);
8969                return true;
8970            }
8971            if (sendRemoved) {
8972                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
8973                        "hiding pkg");
8974                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
8975            }
8976        } finally {
8977            Binder.restoreCallingIdentity(callingId);
8978        }
8979        return false;
8980    }
8981
8982    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
8983            int userId) {
8984        final PackageRemovedInfo info = new PackageRemovedInfo();
8985        info.removedPackage = packageName;
8986        info.removedUsers = new int[] {userId};
8987        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
8988        info.sendBroadcast(false, false, false);
8989    }
8990
8991    /**
8992     * Returns true if application is not found or there was an error. Otherwise it returns
8993     * the hidden state of the package for the given user.
8994     */
8995    @Override
8996    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
8997        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8998        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
8999                false, "getApplicationHidden for user " + userId);
9000        PackageSetting pkgSetting;
9001        long callingId = Binder.clearCallingIdentity();
9002        try {
9003            // writer
9004            synchronized (mPackages) {
9005                pkgSetting = mSettings.mPackages.get(packageName);
9006                if (pkgSetting == null) {
9007                    return true;
9008                }
9009                return pkgSetting.getHidden(userId);
9010            }
9011        } finally {
9012            Binder.restoreCallingIdentity(callingId);
9013        }
9014    }
9015
9016    /**
9017     * @hide
9018     */
9019    @Override
9020    public int installExistingPackageAsUser(String packageName, int userId) {
9021        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9022                null);
9023        PackageSetting pkgSetting;
9024        final int uid = Binder.getCallingUid();
9025        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9026                + userId);
9027        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9028            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9029        }
9030
9031        long callingId = Binder.clearCallingIdentity();
9032        try {
9033            boolean sendAdded = false;
9034
9035            // writer
9036            synchronized (mPackages) {
9037                pkgSetting = mSettings.mPackages.get(packageName);
9038                if (pkgSetting == null) {
9039                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9040                }
9041                if (!pkgSetting.getInstalled(userId)) {
9042                    pkgSetting.setInstalled(true, userId);
9043                    pkgSetting.setHidden(false, userId);
9044                    mSettings.writePackageRestrictionsLPr(userId);
9045                    sendAdded = true;
9046                }
9047            }
9048
9049            if (sendAdded) {
9050                sendPackageAddedForUser(packageName, pkgSetting, userId);
9051            }
9052        } finally {
9053            Binder.restoreCallingIdentity(callingId);
9054        }
9055
9056        return PackageManager.INSTALL_SUCCEEDED;
9057    }
9058
9059    boolean isUserRestricted(int userId, String restrictionKey) {
9060        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9061        if (restrictions.getBoolean(restrictionKey, false)) {
9062            Log.w(TAG, "User is restricted: " + restrictionKey);
9063            return true;
9064        }
9065        return false;
9066    }
9067
9068    @Override
9069    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9070        mContext.enforceCallingOrSelfPermission(
9071                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9072                "Only package verification agents can verify applications");
9073
9074        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9075        final PackageVerificationResponse response = new PackageVerificationResponse(
9076                verificationCode, Binder.getCallingUid());
9077        msg.arg1 = id;
9078        msg.obj = response;
9079        mHandler.sendMessage(msg);
9080    }
9081
9082    @Override
9083    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9084            long millisecondsToDelay) {
9085        mContext.enforceCallingOrSelfPermission(
9086                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9087                "Only package verification agents can extend verification timeouts");
9088
9089        final PackageVerificationState state = mPendingVerification.get(id);
9090        final PackageVerificationResponse response = new PackageVerificationResponse(
9091                verificationCodeAtTimeout, Binder.getCallingUid());
9092
9093        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9094            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9095        }
9096        if (millisecondsToDelay < 0) {
9097            millisecondsToDelay = 0;
9098        }
9099        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9100                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9101            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9102        }
9103
9104        if ((state != null) && !state.timeoutExtended()) {
9105            state.extendTimeout();
9106
9107            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9108            msg.arg1 = id;
9109            msg.obj = response;
9110            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9111        }
9112    }
9113
9114    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9115            int verificationCode, UserHandle user) {
9116        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9117        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9118        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9119        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9120        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9121
9122        mContext.sendBroadcastAsUser(intent, user,
9123                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9124    }
9125
9126    private ComponentName matchComponentForVerifier(String packageName,
9127            List<ResolveInfo> receivers) {
9128        ActivityInfo targetReceiver = null;
9129
9130        final int NR = receivers.size();
9131        for (int i = 0; i < NR; i++) {
9132            final ResolveInfo info = receivers.get(i);
9133            if (info.activityInfo == null) {
9134                continue;
9135            }
9136
9137            if (packageName.equals(info.activityInfo.packageName)) {
9138                targetReceiver = info.activityInfo;
9139                break;
9140            }
9141        }
9142
9143        if (targetReceiver == null) {
9144            return null;
9145        }
9146
9147        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9148    }
9149
9150    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9151            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9152        if (pkgInfo.verifiers.length == 0) {
9153            return null;
9154        }
9155
9156        final int N = pkgInfo.verifiers.length;
9157        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9158        for (int i = 0; i < N; i++) {
9159            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9160
9161            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9162                    receivers);
9163            if (comp == null) {
9164                continue;
9165            }
9166
9167            final int verifierUid = getUidForVerifier(verifierInfo);
9168            if (verifierUid == -1) {
9169                continue;
9170            }
9171
9172            if (DEBUG_VERIFY) {
9173                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9174                        + " with the correct signature");
9175            }
9176            sufficientVerifiers.add(comp);
9177            verificationState.addSufficientVerifier(verifierUid);
9178        }
9179
9180        return sufficientVerifiers;
9181    }
9182
9183    private int getUidForVerifier(VerifierInfo verifierInfo) {
9184        synchronized (mPackages) {
9185            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9186            if (pkg == null) {
9187                return -1;
9188            } else if (pkg.mSignatures.length != 1) {
9189                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9190                        + " has more than one signature; ignoring");
9191                return -1;
9192            }
9193
9194            /*
9195             * If the public key of the package's signature does not match
9196             * our expected public key, then this is a different package and
9197             * we should skip.
9198             */
9199
9200            final byte[] expectedPublicKey;
9201            try {
9202                final Signature verifierSig = pkg.mSignatures[0];
9203                final PublicKey publicKey = verifierSig.getPublicKey();
9204                expectedPublicKey = publicKey.getEncoded();
9205            } catch (CertificateException e) {
9206                return -1;
9207            }
9208
9209            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9210
9211            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9212                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9213                        + " does not have the expected public key; ignoring");
9214                return -1;
9215            }
9216
9217            return pkg.applicationInfo.uid;
9218        }
9219    }
9220
9221    @Override
9222    public void finishPackageInstall(int token) {
9223        enforceSystemOrRoot("Only the system is allowed to finish installs");
9224
9225        if (DEBUG_INSTALL) {
9226            Slog.v(TAG, "BM finishing package install for " + token);
9227        }
9228
9229        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9230        mHandler.sendMessage(msg);
9231    }
9232
9233    /**
9234     * Get the verification agent timeout.
9235     *
9236     * @return verification timeout in milliseconds
9237     */
9238    private long getVerificationTimeout() {
9239        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9240                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9241                DEFAULT_VERIFICATION_TIMEOUT);
9242    }
9243
9244    /**
9245     * Get the default verification agent response code.
9246     *
9247     * @return default verification response code
9248     */
9249    private int getDefaultVerificationResponse() {
9250        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9251                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9252                DEFAULT_VERIFICATION_RESPONSE);
9253    }
9254
9255    /**
9256     * Check whether or not package verification has been enabled.
9257     *
9258     * @return true if verification should be performed
9259     */
9260    private boolean isVerificationEnabled(int userId, int installFlags) {
9261        if (!DEFAULT_VERIFY_ENABLE) {
9262            return false;
9263        }
9264
9265        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9266
9267        // Check if installing from ADB
9268        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9269            // Do not run verification in a test harness environment
9270            if (ActivityManager.isRunningInTestHarness()) {
9271                return false;
9272            }
9273            if (ensureVerifyAppsEnabled) {
9274                return true;
9275            }
9276            // Check if the developer does not want package verification for ADB installs
9277            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9278                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9279                return false;
9280            }
9281        }
9282
9283        if (ensureVerifyAppsEnabled) {
9284            return true;
9285        }
9286
9287        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9288                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9289    }
9290
9291    @Override
9292    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9293            throws RemoteException {
9294        mContext.enforceCallingOrSelfPermission(
9295                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9296                "Only intentfilter verification agents can verify applications");
9297
9298        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9299        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9300                Binder.getCallingUid(), verificationCode, failedDomains);
9301        msg.arg1 = id;
9302        msg.obj = response;
9303        mHandler.sendMessage(msg);
9304    }
9305
9306    @Override
9307    public int getIntentVerificationStatus(String packageName, int userId) {
9308        synchronized (mPackages) {
9309            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9310        }
9311    }
9312
9313    @Override
9314    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9315        boolean result = false;
9316        synchronized (mPackages) {
9317            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9318        }
9319        if (result) {
9320            scheduleWritePackageRestrictionsLocked(userId);
9321        }
9322        return result;
9323    }
9324
9325    @Override
9326    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9327        synchronized (mPackages) {
9328            return mSettings.getIntentFilterVerificationsLPr(packageName);
9329        }
9330    }
9331
9332    @Override
9333    public List<IntentFilter> getAllIntentFilters(String packageName) {
9334        if (TextUtils.isEmpty(packageName)) {
9335            return Collections.<IntentFilter>emptyList();
9336        }
9337        synchronized (mPackages) {
9338            PackageParser.Package pkg = mPackages.get(packageName);
9339            if (pkg == null || pkg.activities == null) {
9340                return Collections.<IntentFilter>emptyList();
9341            }
9342            final int count = pkg.activities.size();
9343            ArrayList<IntentFilter> result = new ArrayList<>();
9344            for (int n=0; n<count; n++) {
9345                PackageParser.Activity activity = pkg.activities.get(n);
9346                if (activity.intents != null || activity.intents.size() > 0) {
9347                    result.addAll(activity.intents);
9348                }
9349            }
9350            return result;
9351        }
9352    }
9353
9354    @Override
9355    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9356        synchronized (mPackages) {
9357            boolean result = mSettings.setDefaultBrowserPackageNameLPr(packageName, userId);
9358            if (packageName != null) {
9359                result |= updateIntentVerificationStatus(packageName,
9360                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9361                        UserHandle.myUserId());
9362            }
9363            return result;
9364        }
9365    }
9366
9367    @Override
9368    public String getDefaultBrowserPackageName(int userId) {
9369        synchronized (mPackages) {
9370            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9371        }
9372    }
9373
9374    /**
9375     * Get the "allow unknown sources" setting.
9376     *
9377     * @return the current "allow unknown sources" setting
9378     */
9379    private int getUnknownSourcesSettings() {
9380        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9381                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9382                -1);
9383    }
9384
9385    @Override
9386    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9387        final int uid = Binder.getCallingUid();
9388        // writer
9389        synchronized (mPackages) {
9390            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9391            if (targetPackageSetting == null) {
9392                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9393            }
9394
9395            PackageSetting installerPackageSetting;
9396            if (installerPackageName != null) {
9397                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9398                if (installerPackageSetting == null) {
9399                    throw new IllegalArgumentException("Unknown installer package: "
9400                            + installerPackageName);
9401                }
9402            } else {
9403                installerPackageSetting = null;
9404            }
9405
9406            Signature[] callerSignature;
9407            Object obj = mSettings.getUserIdLPr(uid);
9408            if (obj != null) {
9409                if (obj instanceof SharedUserSetting) {
9410                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9411                } else if (obj instanceof PackageSetting) {
9412                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9413                } else {
9414                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9415                }
9416            } else {
9417                throw new SecurityException("Unknown calling uid " + uid);
9418            }
9419
9420            // Verify: can't set installerPackageName to a package that is
9421            // not signed with the same cert as the caller.
9422            if (installerPackageSetting != null) {
9423                if (compareSignatures(callerSignature,
9424                        installerPackageSetting.signatures.mSignatures)
9425                        != PackageManager.SIGNATURE_MATCH) {
9426                    throw new SecurityException(
9427                            "Caller does not have same cert as new installer package "
9428                            + installerPackageName);
9429                }
9430            }
9431
9432            // Verify: if target already has an installer package, it must
9433            // be signed with the same cert as the caller.
9434            if (targetPackageSetting.installerPackageName != null) {
9435                PackageSetting setting = mSettings.mPackages.get(
9436                        targetPackageSetting.installerPackageName);
9437                // If the currently set package isn't valid, then it's always
9438                // okay to change it.
9439                if (setting != null) {
9440                    if (compareSignatures(callerSignature,
9441                            setting.signatures.mSignatures)
9442                            != PackageManager.SIGNATURE_MATCH) {
9443                        throw new SecurityException(
9444                                "Caller does not have same cert as old installer package "
9445                                + targetPackageSetting.installerPackageName);
9446                    }
9447                }
9448            }
9449
9450            // Okay!
9451            targetPackageSetting.installerPackageName = installerPackageName;
9452            scheduleWriteSettingsLocked();
9453        }
9454    }
9455
9456    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
9457        // Queue up an async operation since the package installation may take a little while.
9458        mHandler.post(new Runnable() {
9459            public void run() {
9460                mHandler.removeCallbacks(this);
9461                 // Result object to be returned
9462                PackageInstalledInfo res = new PackageInstalledInfo();
9463                res.returnCode = currentStatus;
9464                res.uid = -1;
9465                res.pkg = null;
9466                res.removedInfo = new PackageRemovedInfo();
9467                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9468                    args.doPreInstall(res.returnCode);
9469                    synchronized (mInstallLock) {
9470                        installPackageLI(args, res);
9471                    }
9472                    args.doPostInstall(res.returnCode, res.uid);
9473                }
9474
9475                // A restore should be performed at this point if (a) the install
9476                // succeeded, (b) the operation is not an update, and (c) the new
9477                // package has not opted out of backup participation.
9478                final boolean update = res.removedInfo.removedPackage != null;
9479                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
9480                boolean doRestore = !update
9481                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
9482
9483                // Set up the post-install work request bookkeeping.  This will be used
9484                // and cleaned up by the post-install event handling regardless of whether
9485                // there's a restore pass performed.  Token values are >= 1.
9486                int token;
9487                if (mNextInstallToken < 0) mNextInstallToken = 1;
9488                token = mNextInstallToken++;
9489
9490                PostInstallData data = new PostInstallData(args, res);
9491                mRunningInstalls.put(token, data);
9492                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
9493
9494                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
9495                    // Pass responsibility to the Backup Manager.  It will perform a
9496                    // restore if appropriate, then pass responsibility back to the
9497                    // Package Manager to run the post-install observer callbacks
9498                    // and broadcasts.
9499                    IBackupManager bm = IBackupManager.Stub.asInterface(
9500                            ServiceManager.getService(Context.BACKUP_SERVICE));
9501                    if (bm != null) {
9502                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
9503                                + " to BM for possible restore");
9504                        try {
9505                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
9506                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
9507                            } else {
9508                                doRestore = false;
9509                            }
9510                        } catch (RemoteException e) {
9511                            // can't happen; the backup manager is local
9512                        } catch (Exception e) {
9513                            Slog.e(TAG, "Exception trying to enqueue restore", e);
9514                            doRestore = false;
9515                        }
9516                    } else {
9517                        Slog.e(TAG, "Backup Manager not found!");
9518                        doRestore = false;
9519                    }
9520                }
9521
9522                if (!doRestore) {
9523                    // No restore possible, or the Backup Manager was mysteriously not
9524                    // available -- just fire the post-install work request directly.
9525                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
9526                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9527                    mHandler.sendMessage(msg);
9528                }
9529            }
9530        });
9531    }
9532
9533    private abstract class HandlerParams {
9534        private static final int MAX_RETRIES = 4;
9535
9536        /**
9537         * Number of times startCopy() has been attempted and had a non-fatal
9538         * error.
9539         */
9540        private int mRetries = 0;
9541
9542        /** User handle for the user requesting the information or installation. */
9543        private final UserHandle mUser;
9544
9545        HandlerParams(UserHandle user) {
9546            mUser = user;
9547        }
9548
9549        UserHandle getUser() {
9550            return mUser;
9551        }
9552
9553        final boolean startCopy() {
9554            boolean res;
9555            try {
9556                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
9557
9558                if (++mRetries > MAX_RETRIES) {
9559                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
9560                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
9561                    handleServiceError();
9562                    return false;
9563                } else {
9564                    handleStartCopy();
9565                    res = true;
9566                }
9567            } catch (RemoteException e) {
9568                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
9569                mHandler.sendEmptyMessage(MCS_RECONNECT);
9570                res = false;
9571            }
9572            handleReturnCode();
9573            return res;
9574        }
9575
9576        final void serviceError() {
9577            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
9578            handleServiceError();
9579            handleReturnCode();
9580        }
9581
9582        abstract void handleStartCopy() throws RemoteException;
9583        abstract void handleServiceError();
9584        abstract void handleReturnCode();
9585    }
9586
9587    class MeasureParams extends HandlerParams {
9588        private final PackageStats mStats;
9589        private boolean mSuccess;
9590
9591        private final IPackageStatsObserver mObserver;
9592
9593        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
9594            super(new UserHandle(stats.userHandle));
9595            mObserver = observer;
9596            mStats = stats;
9597        }
9598
9599        @Override
9600        public String toString() {
9601            return "MeasureParams{"
9602                + Integer.toHexString(System.identityHashCode(this))
9603                + " " + mStats.packageName + "}";
9604        }
9605
9606        @Override
9607        void handleStartCopy() throws RemoteException {
9608            synchronized (mInstallLock) {
9609                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
9610            }
9611
9612            if (mSuccess) {
9613                final boolean mounted;
9614                if (Environment.isExternalStorageEmulated()) {
9615                    mounted = true;
9616                } else {
9617                    final String status = Environment.getExternalStorageState();
9618                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
9619                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
9620                }
9621
9622                if (mounted) {
9623                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
9624
9625                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
9626                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
9627
9628                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
9629                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
9630
9631                    // Always subtract cache size, since it's a subdirectory
9632                    mStats.externalDataSize -= mStats.externalCacheSize;
9633
9634                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
9635                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
9636
9637                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
9638                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
9639                }
9640            }
9641        }
9642
9643        @Override
9644        void handleReturnCode() {
9645            if (mObserver != null) {
9646                try {
9647                    mObserver.onGetStatsCompleted(mStats, mSuccess);
9648                } catch (RemoteException e) {
9649                    Slog.i(TAG, "Observer no longer exists.");
9650                }
9651            }
9652        }
9653
9654        @Override
9655        void handleServiceError() {
9656            Slog.e(TAG, "Could not measure application " + mStats.packageName
9657                            + " external storage");
9658        }
9659    }
9660
9661    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
9662            throws RemoteException {
9663        long result = 0;
9664        for (File path : paths) {
9665            result += mcs.calculateDirectorySize(path.getAbsolutePath());
9666        }
9667        return result;
9668    }
9669
9670    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
9671        for (File path : paths) {
9672            try {
9673                mcs.clearDirectory(path.getAbsolutePath());
9674            } catch (RemoteException e) {
9675            }
9676        }
9677    }
9678
9679    static class OriginInfo {
9680        /**
9681         * Location where install is coming from, before it has been
9682         * copied/renamed into place. This could be a single monolithic APK
9683         * file, or a cluster directory. This location may be untrusted.
9684         */
9685        final File file;
9686        final String cid;
9687
9688        /**
9689         * Flag indicating that {@link #file} or {@link #cid} has already been
9690         * staged, meaning downstream users don't need to defensively copy the
9691         * contents.
9692         */
9693        final boolean staged;
9694
9695        /**
9696         * Flag indicating that {@link #file} or {@link #cid} is an already
9697         * installed app that is being moved.
9698         */
9699        final boolean existing;
9700
9701        final String resolvedPath;
9702        final File resolvedFile;
9703
9704        static OriginInfo fromNothing() {
9705            return new OriginInfo(null, null, false, false);
9706        }
9707
9708        static OriginInfo fromUntrustedFile(File file) {
9709            return new OriginInfo(file, null, false, false);
9710        }
9711
9712        static OriginInfo fromExistingFile(File file) {
9713            return new OriginInfo(file, null, false, true);
9714        }
9715
9716        static OriginInfo fromStagedFile(File file) {
9717            return new OriginInfo(file, null, true, false);
9718        }
9719
9720        static OriginInfo fromStagedContainer(String cid) {
9721            return new OriginInfo(null, cid, true, false);
9722        }
9723
9724        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
9725            this.file = file;
9726            this.cid = cid;
9727            this.staged = staged;
9728            this.existing = existing;
9729
9730            if (cid != null) {
9731                resolvedPath = PackageHelper.getSdDir(cid);
9732                resolvedFile = new File(resolvedPath);
9733            } else if (file != null) {
9734                resolvedPath = file.getAbsolutePath();
9735                resolvedFile = file;
9736            } else {
9737                resolvedPath = null;
9738                resolvedFile = null;
9739            }
9740        }
9741    }
9742
9743    class MoveInfo {
9744        final int moveId;
9745        final String fromUuid;
9746        final String toUuid;
9747        final String packageName;
9748        final String dataAppName;
9749        final int appId;
9750        final String seinfo;
9751
9752        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
9753                String dataAppName, int appId, String seinfo) {
9754            this.moveId = moveId;
9755            this.fromUuid = fromUuid;
9756            this.toUuid = toUuid;
9757            this.packageName = packageName;
9758            this.dataAppName = dataAppName;
9759            this.appId = appId;
9760            this.seinfo = seinfo;
9761        }
9762    }
9763
9764    class InstallParams extends HandlerParams {
9765        final OriginInfo origin;
9766        final MoveInfo move;
9767        final IPackageInstallObserver2 observer;
9768        int installFlags;
9769        final String installerPackageName;
9770        final String volumeUuid;
9771        final VerificationParams verificationParams;
9772        private InstallArgs mArgs;
9773        private int mRet;
9774        final String packageAbiOverride;
9775
9776        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
9777                int installFlags, String installerPackageName, String volumeUuid,
9778                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
9779            super(user);
9780            this.origin = origin;
9781            this.move = move;
9782            this.observer = observer;
9783            this.installFlags = installFlags;
9784            this.installerPackageName = installerPackageName;
9785            this.volumeUuid = volumeUuid;
9786            this.verificationParams = verificationParams;
9787            this.packageAbiOverride = packageAbiOverride;
9788        }
9789
9790        @Override
9791        public String toString() {
9792            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
9793                    + " file=" + origin.file + " cid=" + origin.cid + "}";
9794        }
9795
9796        public ManifestDigest getManifestDigest() {
9797            if (verificationParams == null) {
9798                return null;
9799            }
9800            return verificationParams.getManifestDigest();
9801        }
9802
9803        private int installLocationPolicy(PackageInfoLite pkgLite) {
9804            String packageName = pkgLite.packageName;
9805            int installLocation = pkgLite.installLocation;
9806            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9807            // reader
9808            synchronized (mPackages) {
9809                PackageParser.Package pkg = mPackages.get(packageName);
9810                if (pkg != null) {
9811                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
9812                        // Check for downgrading.
9813                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
9814                            try {
9815                                checkDowngrade(pkg, pkgLite);
9816                            } catch (PackageManagerException e) {
9817                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
9818                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
9819                            }
9820                        }
9821                        // Check for updated system application.
9822                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9823                            if (onSd) {
9824                                Slog.w(TAG, "Cannot install update to system app on sdcard");
9825                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
9826                            }
9827                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9828                        } else {
9829                            if (onSd) {
9830                                // Install flag overrides everything.
9831                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9832                            }
9833                            // If current upgrade specifies particular preference
9834                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
9835                                // Application explicitly specified internal.
9836                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9837                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
9838                                // App explictly prefers external. Let policy decide
9839                            } else {
9840                                // Prefer previous location
9841                                if (isExternal(pkg)) {
9842                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9843                                }
9844                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9845                            }
9846                        }
9847                    } else {
9848                        // Invalid install. Return error code
9849                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
9850                    }
9851                }
9852            }
9853            // All the special cases have been taken care of.
9854            // Return result based on recommended install location.
9855            if (onSd) {
9856                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9857            }
9858            return pkgLite.recommendedInstallLocation;
9859        }
9860
9861        /*
9862         * Invoke remote method to get package information and install
9863         * location values. Override install location based on default
9864         * policy if needed and then create install arguments based
9865         * on the install location.
9866         */
9867        public void handleStartCopy() throws RemoteException {
9868            int ret = PackageManager.INSTALL_SUCCEEDED;
9869
9870            // If we're already staged, we've firmly committed to an install location
9871            if (origin.staged) {
9872                if (origin.file != null) {
9873                    installFlags |= PackageManager.INSTALL_INTERNAL;
9874                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
9875                } else if (origin.cid != null) {
9876                    installFlags |= PackageManager.INSTALL_EXTERNAL;
9877                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
9878                } else {
9879                    throw new IllegalStateException("Invalid stage location");
9880                }
9881            }
9882
9883            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9884            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
9885
9886            PackageInfoLite pkgLite = null;
9887
9888            if (onInt && onSd) {
9889                // Check if both bits are set.
9890                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
9891                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9892            } else {
9893                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
9894                        packageAbiOverride);
9895
9896                /*
9897                 * If we have too little free space, try to free cache
9898                 * before giving up.
9899                 */
9900                if (!origin.staged && pkgLite.recommendedInstallLocation
9901                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9902                    // TODO: focus freeing disk space on the target device
9903                    final StorageManager storage = StorageManager.from(mContext);
9904                    final long lowThreshold = storage.getStorageLowBytes(
9905                            Environment.getDataDirectory());
9906
9907                    final long sizeBytes = mContainerService.calculateInstalledSize(
9908                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
9909
9910                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
9911                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
9912                                installFlags, packageAbiOverride);
9913                    }
9914
9915                    /*
9916                     * The cache free must have deleted the file we
9917                     * downloaded to install.
9918                     *
9919                     * TODO: fix the "freeCache" call to not delete
9920                     *       the file we care about.
9921                     */
9922                    if (pkgLite.recommendedInstallLocation
9923                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9924                        pkgLite.recommendedInstallLocation
9925                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
9926                    }
9927                }
9928            }
9929
9930            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9931                int loc = pkgLite.recommendedInstallLocation;
9932                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
9933                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9934                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
9935                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9936                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9937                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9938                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
9939                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
9940                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9941                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
9942                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
9943                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
9944                } else {
9945                    // Override with defaults if needed.
9946                    loc = installLocationPolicy(pkgLite);
9947                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
9948                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
9949                    } else if (!onSd && !onInt) {
9950                        // Override install location with flags
9951                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
9952                            // Set the flag to install on external media.
9953                            installFlags |= PackageManager.INSTALL_EXTERNAL;
9954                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
9955                        } else {
9956                            // Make sure the flag for installing on external
9957                            // media is unset
9958                            installFlags |= PackageManager.INSTALL_INTERNAL;
9959                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
9960                        }
9961                    }
9962                }
9963            }
9964
9965            final InstallArgs args = createInstallArgs(this);
9966            mArgs = args;
9967
9968            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9969                 /*
9970                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
9971                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
9972                 */
9973                int userIdentifier = getUser().getIdentifier();
9974                if (userIdentifier == UserHandle.USER_ALL
9975                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
9976                    userIdentifier = UserHandle.USER_OWNER;
9977                }
9978
9979                /*
9980                 * Determine if we have any installed package verifiers. If we
9981                 * do, then we'll defer to them to verify the packages.
9982                 */
9983                final int requiredUid = mRequiredVerifierPackage == null ? -1
9984                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
9985                if (!origin.existing && requiredUid != -1
9986                        && isVerificationEnabled(userIdentifier, installFlags)) {
9987                    final Intent verification = new Intent(
9988                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
9989                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
9990                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
9991                            PACKAGE_MIME_TYPE);
9992                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9993
9994                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
9995                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
9996                            0 /* TODO: Which userId? */);
9997
9998                    if (DEBUG_VERIFY) {
9999                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10000                                + verification.toString() + " with " + pkgLite.verifiers.length
10001                                + " optional verifiers");
10002                    }
10003
10004                    final int verificationId = mPendingVerificationToken++;
10005
10006                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10007
10008                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10009                            installerPackageName);
10010
10011                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10012                            installFlags);
10013
10014                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10015                            pkgLite.packageName);
10016
10017                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10018                            pkgLite.versionCode);
10019
10020                    if (verificationParams != null) {
10021                        if (verificationParams.getVerificationURI() != null) {
10022                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10023                                 verificationParams.getVerificationURI());
10024                        }
10025                        if (verificationParams.getOriginatingURI() != null) {
10026                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10027                                  verificationParams.getOriginatingURI());
10028                        }
10029                        if (verificationParams.getReferrer() != null) {
10030                            verification.putExtra(Intent.EXTRA_REFERRER,
10031                                  verificationParams.getReferrer());
10032                        }
10033                        if (verificationParams.getOriginatingUid() >= 0) {
10034                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10035                                  verificationParams.getOriginatingUid());
10036                        }
10037                        if (verificationParams.getInstallerUid() >= 0) {
10038                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10039                                  verificationParams.getInstallerUid());
10040                        }
10041                    }
10042
10043                    final PackageVerificationState verificationState = new PackageVerificationState(
10044                            requiredUid, args);
10045
10046                    mPendingVerification.append(verificationId, verificationState);
10047
10048                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10049                            receivers, verificationState);
10050
10051                    /*
10052                     * If any sufficient verifiers were listed in the package
10053                     * manifest, attempt to ask them.
10054                     */
10055                    if (sufficientVerifiers != null) {
10056                        final int N = sufficientVerifiers.size();
10057                        if (N == 0) {
10058                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10059                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10060                        } else {
10061                            for (int i = 0; i < N; i++) {
10062                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10063
10064                                final Intent sufficientIntent = new Intent(verification);
10065                                sufficientIntent.setComponent(verifierComponent);
10066
10067                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
10068                            }
10069                        }
10070                    }
10071
10072                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10073                            mRequiredVerifierPackage, receivers);
10074                    if (ret == PackageManager.INSTALL_SUCCEEDED
10075                            && mRequiredVerifierPackage != null) {
10076                        /*
10077                         * Send the intent to the required verification agent,
10078                         * but only start the verification timeout after the
10079                         * target BroadcastReceivers have run.
10080                         */
10081                        verification.setComponent(requiredVerifierComponent);
10082                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
10083                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10084                                new BroadcastReceiver() {
10085                                    @Override
10086                                    public void onReceive(Context context, Intent intent) {
10087                                        final Message msg = mHandler
10088                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10089                                        msg.arg1 = verificationId;
10090                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10091                                    }
10092                                }, null, 0, null, null);
10093
10094                        /*
10095                         * We don't want the copy to proceed until verification
10096                         * succeeds, so null out this field.
10097                         */
10098                        mArgs = null;
10099                    }
10100                } else {
10101                    /*
10102                     * No package verification is enabled, so immediately start
10103                     * the remote call to initiate copy using temporary file.
10104                     */
10105                    ret = args.copyApk(mContainerService, true);
10106                }
10107            }
10108
10109            mRet = ret;
10110        }
10111
10112        @Override
10113        void handleReturnCode() {
10114            // If mArgs is null, then MCS couldn't be reached. When it
10115            // reconnects, it will try again to install. At that point, this
10116            // will succeed.
10117            if (mArgs != null) {
10118                processPendingInstall(mArgs, mRet);
10119            }
10120        }
10121
10122        @Override
10123        void handleServiceError() {
10124            mArgs = createInstallArgs(this);
10125            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10126        }
10127
10128        public boolean isForwardLocked() {
10129            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10130        }
10131    }
10132
10133    /**
10134     * Used during creation of InstallArgs
10135     *
10136     * @param installFlags package installation flags
10137     * @return true if should be installed on external storage
10138     */
10139    private static boolean installOnExternalAsec(int installFlags) {
10140        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10141            return false;
10142        }
10143        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10144            return true;
10145        }
10146        return false;
10147    }
10148
10149    /**
10150     * Used during creation of InstallArgs
10151     *
10152     * @param installFlags package installation flags
10153     * @return true if should be installed as forward locked
10154     */
10155    private static boolean installForwardLocked(int installFlags) {
10156        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10157    }
10158
10159    private InstallArgs createInstallArgs(InstallParams params) {
10160        if (params.move != null) {
10161            return new MoveInstallArgs(params);
10162        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10163            return new AsecInstallArgs(params);
10164        } else {
10165            return new FileInstallArgs(params);
10166        }
10167    }
10168
10169    /**
10170     * Create args that describe an existing installed package. Typically used
10171     * when cleaning up old installs, or used as a move source.
10172     */
10173    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10174            String resourcePath, String[] instructionSets) {
10175        final boolean isInAsec;
10176        if (installOnExternalAsec(installFlags)) {
10177            /* Apps on SD card are always in ASEC containers. */
10178            isInAsec = true;
10179        } else if (installForwardLocked(installFlags)
10180                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10181            /*
10182             * Forward-locked apps are only in ASEC containers if they're the
10183             * new style
10184             */
10185            isInAsec = true;
10186        } else {
10187            isInAsec = false;
10188        }
10189
10190        if (isInAsec) {
10191            return new AsecInstallArgs(codePath, instructionSets,
10192                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10193        } else {
10194            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10195        }
10196    }
10197
10198    static abstract class InstallArgs {
10199        /** @see InstallParams#origin */
10200        final OriginInfo origin;
10201        /** @see InstallParams#move */
10202        final MoveInfo move;
10203
10204        final IPackageInstallObserver2 observer;
10205        // Always refers to PackageManager flags only
10206        final int installFlags;
10207        final String installerPackageName;
10208        final String volumeUuid;
10209        final ManifestDigest manifestDigest;
10210        final UserHandle user;
10211        final String abiOverride;
10212
10213        // The list of instruction sets supported by this app. This is currently
10214        // only used during the rmdex() phase to clean up resources. We can get rid of this
10215        // if we move dex files under the common app path.
10216        /* nullable */ String[] instructionSets;
10217
10218        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10219                int installFlags, String installerPackageName, String volumeUuid,
10220                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10221                String abiOverride) {
10222            this.origin = origin;
10223            this.move = move;
10224            this.installFlags = installFlags;
10225            this.observer = observer;
10226            this.installerPackageName = installerPackageName;
10227            this.volumeUuid = volumeUuid;
10228            this.manifestDigest = manifestDigest;
10229            this.user = user;
10230            this.instructionSets = instructionSets;
10231            this.abiOverride = abiOverride;
10232        }
10233
10234        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10235        abstract int doPreInstall(int status);
10236
10237        /**
10238         * Rename package into final resting place. All paths on the given
10239         * scanned package should be updated to reflect the rename.
10240         */
10241        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10242        abstract int doPostInstall(int status, int uid);
10243
10244        /** @see PackageSettingBase#codePathString */
10245        abstract String getCodePath();
10246        /** @see PackageSettingBase#resourcePathString */
10247        abstract String getResourcePath();
10248
10249        // Need installer lock especially for dex file removal.
10250        abstract void cleanUpResourcesLI();
10251        abstract boolean doPostDeleteLI(boolean delete);
10252
10253        /**
10254         * Called before the source arguments are copied. This is used mostly
10255         * for MoveParams when it needs to read the source file to put it in the
10256         * destination.
10257         */
10258        int doPreCopy() {
10259            return PackageManager.INSTALL_SUCCEEDED;
10260        }
10261
10262        /**
10263         * Called after the source arguments are copied. This is used mostly for
10264         * MoveParams when it needs to read the source file to put it in the
10265         * destination.
10266         *
10267         * @return
10268         */
10269        int doPostCopy(int uid) {
10270            return PackageManager.INSTALL_SUCCEEDED;
10271        }
10272
10273        protected boolean isFwdLocked() {
10274            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10275        }
10276
10277        protected boolean isExternalAsec() {
10278            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10279        }
10280
10281        UserHandle getUser() {
10282            return user;
10283        }
10284    }
10285
10286    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10287        if (!allCodePaths.isEmpty()) {
10288            if (instructionSets == null) {
10289                throw new IllegalStateException("instructionSet == null");
10290            }
10291            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10292            for (String codePath : allCodePaths) {
10293                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10294                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10295                    if (retCode < 0) {
10296                        Slog.w(TAG, "Couldn't remove dex file for package: "
10297                                + " at location " + codePath + ", retcode=" + retCode);
10298                        // we don't consider this to be a failure of the core package deletion
10299                    }
10300                }
10301            }
10302        }
10303    }
10304
10305    /**
10306     * Logic to handle installation of non-ASEC applications, including copying
10307     * and renaming logic.
10308     */
10309    class FileInstallArgs extends InstallArgs {
10310        private File codeFile;
10311        private File resourceFile;
10312
10313        // Example topology:
10314        // /data/app/com.example/base.apk
10315        // /data/app/com.example/split_foo.apk
10316        // /data/app/com.example/lib/arm/libfoo.so
10317        // /data/app/com.example/lib/arm64/libfoo.so
10318        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10319
10320        /** New install */
10321        FileInstallArgs(InstallParams params) {
10322            super(params.origin, params.move, params.observer, params.installFlags,
10323                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10324                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10325            if (isFwdLocked()) {
10326                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10327            }
10328        }
10329
10330        /** Existing install */
10331        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10332            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10333                    null);
10334            this.codeFile = (codePath != null) ? new File(codePath) : null;
10335            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10336        }
10337
10338        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10339            if (origin.staged) {
10340                Slog.d(TAG, origin.file + " already staged; skipping copy");
10341                codeFile = origin.file;
10342                resourceFile = origin.file;
10343                return PackageManager.INSTALL_SUCCEEDED;
10344            }
10345
10346            try {
10347                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10348                codeFile = tempDir;
10349                resourceFile = tempDir;
10350            } catch (IOException e) {
10351                Slog.w(TAG, "Failed to create copy file: " + e);
10352                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10353            }
10354
10355            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10356                @Override
10357                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10358                    if (!FileUtils.isValidExtFilename(name)) {
10359                        throw new IllegalArgumentException("Invalid filename: " + name);
10360                    }
10361                    try {
10362                        final File file = new File(codeFile, name);
10363                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10364                                O_RDWR | O_CREAT, 0644);
10365                        Os.chmod(file.getAbsolutePath(), 0644);
10366                        return new ParcelFileDescriptor(fd);
10367                    } catch (ErrnoException e) {
10368                        throw new RemoteException("Failed to open: " + e.getMessage());
10369                    }
10370                }
10371            };
10372
10373            int ret = PackageManager.INSTALL_SUCCEEDED;
10374            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10375            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10376                Slog.e(TAG, "Failed to copy package");
10377                return ret;
10378            }
10379
10380            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10381            NativeLibraryHelper.Handle handle = null;
10382            try {
10383                handle = NativeLibraryHelper.Handle.create(codeFile);
10384                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10385                        abiOverride);
10386            } catch (IOException e) {
10387                Slog.e(TAG, "Copying native libraries failed", e);
10388                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10389            } finally {
10390                IoUtils.closeQuietly(handle);
10391            }
10392
10393            return ret;
10394        }
10395
10396        int doPreInstall(int status) {
10397            if (status != PackageManager.INSTALL_SUCCEEDED) {
10398                cleanUp();
10399            }
10400            return status;
10401        }
10402
10403        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10404            if (status != PackageManager.INSTALL_SUCCEEDED) {
10405                cleanUp();
10406                return false;
10407            }
10408
10409            final File targetDir = codeFile.getParentFile();
10410            final File beforeCodeFile = codeFile;
10411            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10412
10413            Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10414            try {
10415                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10416            } catch (ErrnoException e) {
10417                Slog.d(TAG, "Failed to rename", e);
10418                return false;
10419            }
10420
10421            if (!SELinux.restoreconRecursive(afterCodeFile)) {
10422                Slog.d(TAG, "Failed to restorecon");
10423                return false;
10424            }
10425
10426            // Reflect the rename internally
10427            codeFile = afterCodeFile;
10428            resourceFile = afterCodeFile;
10429
10430            // Reflect the rename in scanned details
10431            pkg.codePath = afterCodeFile.getAbsolutePath();
10432            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10433                    pkg.baseCodePath);
10434            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10435                    pkg.splitCodePaths);
10436
10437            // Reflect the rename in app info
10438            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10439            pkg.applicationInfo.setCodePath(pkg.codePath);
10440            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10441            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10442            pkg.applicationInfo.setResourcePath(pkg.codePath);
10443            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10444            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10445
10446            return true;
10447        }
10448
10449        int doPostInstall(int status, int uid) {
10450            if (status != PackageManager.INSTALL_SUCCEEDED) {
10451                cleanUp();
10452            }
10453            return status;
10454        }
10455
10456        @Override
10457        String getCodePath() {
10458            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10459        }
10460
10461        @Override
10462        String getResourcePath() {
10463            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10464        }
10465
10466        private boolean cleanUp() {
10467            if (codeFile == null || !codeFile.exists()) {
10468                return false;
10469            }
10470
10471            if (codeFile.isDirectory()) {
10472                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10473            } else {
10474                codeFile.delete();
10475            }
10476
10477            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10478                resourceFile.delete();
10479            }
10480
10481            return true;
10482        }
10483
10484        void cleanUpResourcesLI() {
10485            // Try enumerating all code paths before deleting
10486            List<String> allCodePaths = Collections.EMPTY_LIST;
10487            if (codeFile != null && codeFile.exists()) {
10488                try {
10489                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10490                    allCodePaths = pkg.getAllCodePaths();
10491                } catch (PackageParserException e) {
10492                    // Ignored; we tried our best
10493                }
10494            }
10495
10496            cleanUp();
10497            removeDexFiles(allCodePaths, instructionSets);
10498        }
10499
10500        boolean doPostDeleteLI(boolean delete) {
10501            // XXX err, shouldn't we respect the delete flag?
10502            cleanUpResourcesLI();
10503            return true;
10504        }
10505    }
10506
10507    private boolean isAsecExternal(String cid) {
10508        final String asecPath = PackageHelper.getSdFilesystem(cid);
10509        return !asecPath.startsWith(mAsecInternalPath);
10510    }
10511
10512    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
10513            PackageManagerException {
10514        if (copyRet < 0) {
10515            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
10516                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
10517                throw new PackageManagerException(copyRet, message);
10518            }
10519        }
10520    }
10521
10522    /**
10523     * Extract the MountService "container ID" from the full code path of an
10524     * .apk.
10525     */
10526    static String cidFromCodePath(String fullCodePath) {
10527        int eidx = fullCodePath.lastIndexOf("/");
10528        String subStr1 = fullCodePath.substring(0, eidx);
10529        int sidx = subStr1.lastIndexOf("/");
10530        return subStr1.substring(sidx+1, eidx);
10531    }
10532
10533    /**
10534     * Logic to handle installation of ASEC applications, including copying and
10535     * renaming logic.
10536     */
10537    class AsecInstallArgs extends InstallArgs {
10538        static final String RES_FILE_NAME = "pkg.apk";
10539        static final String PUBLIC_RES_FILE_NAME = "res.zip";
10540
10541        String cid;
10542        String packagePath;
10543        String resourcePath;
10544
10545        /** New install */
10546        AsecInstallArgs(InstallParams params) {
10547            super(params.origin, params.move, params.observer, params.installFlags,
10548                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10549                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10550        }
10551
10552        /** Existing install */
10553        AsecInstallArgs(String fullCodePath, String[] instructionSets,
10554                        boolean isExternal, boolean isForwardLocked) {
10555            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
10556                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10557                    instructionSets, null);
10558            // Hackily pretend we're still looking at a full code path
10559            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
10560                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
10561            }
10562
10563            // Extract cid from fullCodePath
10564            int eidx = fullCodePath.lastIndexOf("/");
10565            String subStr1 = fullCodePath.substring(0, eidx);
10566            int sidx = subStr1.lastIndexOf("/");
10567            cid = subStr1.substring(sidx+1, eidx);
10568            setMountPath(subStr1);
10569        }
10570
10571        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
10572            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
10573                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10574                    instructionSets, null);
10575            this.cid = cid;
10576            setMountPath(PackageHelper.getSdDir(cid));
10577        }
10578
10579        void createCopyFile() {
10580            cid = mInstallerService.allocateExternalStageCidLegacy();
10581        }
10582
10583        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10584            if (origin.staged) {
10585                Slog.d(TAG, origin.cid + " already staged; skipping copy");
10586                cid = origin.cid;
10587                setMountPath(PackageHelper.getSdDir(cid));
10588                return PackageManager.INSTALL_SUCCEEDED;
10589            }
10590
10591            if (temp) {
10592                createCopyFile();
10593            } else {
10594                /*
10595                 * Pre-emptively destroy the container since it's destroyed if
10596                 * copying fails due to it existing anyway.
10597                 */
10598                PackageHelper.destroySdDir(cid);
10599            }
10600
10601            final String newMountPath = imcs.copyPackageToContainer(
10602                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
10603                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
10604
10605            if (newMountPath != null) {
10606                setMountPath(newMountPath);
10607                return PackageManager.INSTALL_SUCCEEDED;
10608            } else {
10609                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10610            }
10611        }
10612
10613        @Override
10614        String getCodePath() {
10615            return packagePath;
10616        }
10617
10618        @Override
10619        String getResourcePath() {
10620            return resourcePath;
10621        }
10622
10623        int doPreInstall(int status) {
10624            if (status != PackageManager.INSTALL_SUCCEEDED) {
10625                // Destroy container
10626                PackageHelper.destroySdDir(cid);
10627            } else {
10628                boolean mounted = PackageHelper.isContainerMounted(cid);
10629                if (!mounted) {
10630                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
10631                            Process.SYSTEM_UID);
10632                    if (newMountPath != null) {
10633                        setMountPath(newMountPath);
10634                    } else {
10635                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10636                    }
10637                }
10638            }
10639            return status;
10640        }
10641
10642        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10643            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
10644            String newMountPath = null;
10645            if (PackageHelper.isContainerMounted(cid)) {
10646                // Unmount the container
10647                if (!PackageHelper.unMountSdDir(cid)) {
10648                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
10649                    return false;
10650                }
10651            }
10652            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10653                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
10654                        " which might be stale. Will try to clean up.");
10655                // Clean up the stale container and proceed to recreate.
10656                if (!PackageHelper.destroySdDir(newCacheId)) {
10657                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
10658                    return false;
10659                }
10660                // Successfully cleaned up stale container. Try to rename again.
10661                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10662                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
10663                            + " inspite of cleaning it up.");
10664                    return false;
10665                }
10666            }
10667            if (!PackageHelper.isContainerMounted(newCacheId)) {
10668                Slog.w(TAG, "Mounting container " + newCacheId);
10669                newMountPath = PackageHelper.mountSdDir(newCacheId,
10670                        getEncryptKey(), Process.SYSTEM_UID);
10671            } else {
10672                newMountPath = PackageHelper.getSdDir(newCacheId);
10673            }
10674            if (newMountPath == null) {
10675                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
10676                return false;
10677            }
10678            Log.i(TAG, "Succesfully renamed " + cid +
10679                    " to " + newCacheId +
10680                    " at new path: " + newMountPath);
10681            cid = newCacheId;
10682
10683            final File beforeCodeFile = new File(packagePath);
10684            setMountPath(newMountPath);
10685            final File afterCodeFile = new File(packagePath);
10686
10687            // Reflect the rename in scanned details
10688            pkg.codePath = afterCodeFile.getAbsolutePath();
10689            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10690                    pkg.baseCodePath);
10691            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10692                    pkg.splitCodePaths);
10693
10694            // Reflect the rename in app info
10695            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10696            pkg.applicationInfo.setCodePath(pkg.codePath);
10697            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10698            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10699            pkg.applicationInfo.setResourcePath(pkg.codePath);
10700            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10701            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10702
10703            return true;
10704        }
10705
10706        private void setMountPath(String mountPath) {
10707            final File mountFile = new File(mountPath);
10708
10709            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
10710            if (monolithicFile.exists()) {
10711                packagePath = monolithicFile.getAbsolutePath();
10712                if (isFwdLocked()) {
10713                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
10714                } else {
10715                    resourcePath = packagePath;
10716                }
10717            } else {
10718                packagePath = mountFile.getAbsolutePath();
10719                resourcePath = packagePath;
10720            }
10721        }
10722
10723        int doPostInstall(int status, int uid) {
10724            if (status != PackageManager.INSTALL_SUCCEEDED) {
10725                cleanUp();
10726            } else {
10727                final int groupOwner;
10728                final String protectedFile;
10729                if (isFwdLocked()) {
10730                    groupOwner = UserHandle.getSharedAppGid(uid);
10731                    protectedFile = RES_FILE_NAME;
10732                } else {
10733                    groupOwner = -1;
10734                    protectedFile = null;
10735                }
10736
10737                if (uid < Process.FIRST_APPLICATION_UID
10738                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
10739                    Slog.e(TAG, "Failed to finalize " + cid);
10740                    PackageHelper.destroySdDir(cid);
10741                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10742                }
10743
10744                boolean mounted = PackageHelper.isContainerMounted(cid);
10745                if (!mounted) {
10746                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
10747                }
10748            }
10749            return status;
10750        }
10751
10752        private void cleanUp() {
10753            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
10754
10755            // Destroy secure container
10756            PackageHelper.destroySdDir(cid);
10757        }
10758
10759        private List<String> getAllCodePaths() {
10760            final File codeFile = new File(getCodePath());
10761            if (codeFile != null && codeFile.exists()) {
10762                try {
10763                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10764                    return pkg.getAllCodePaths();
10765                } catch (PackageParserException e) {
10766                    // Ignored; we tried our best
10767                }
10768            }
10769            return Collections.EMPTY_LIST;
10770        }
10771
10772        void cleanUpResourcesLI() {
10773            // Enumerate all code paths before deleting
10774            cleanUpResourcesLI(getAllCodePaths());
10775        }
10776
10777        private void cleanUpResourcesLI(List<String> allCodePaths) {
10778            cleanUp();
10779            removeDexFiles(allCodePaths, instructionSets);
10780        }
10781
10782        String getPackageName() {
10783            return getAsecPackageName(cid);
10784        }
10785
10786        boolean doPostDeleteLI(boolean delete) {
10787            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
10788            final List<String> allCodePaths = getAllCodePaths();
10789            boolean mounted = PackageHelper.isContainerMounted(cid);
10790            if (mounted) {
10791                // Unmount first
10792                if (PackageHelper.unMountSdDir(cid)) {
10793                    mounted = false;
10794                }
10795            }
10796            if (!mounted && delete) {
10797                cleanUpResourcesLI(allCodePaths);
10798            }
10799            return !mounted;
10800        }
10801
10802        @Override
10803        int doPreCopy() {
10804            if (isFwdLocked()) {
10805                if (!PackageHelper.fixSdPermissions(cid,
10806                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
10807                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10808                }
10809            }
10810
10811            return PackageManager.INSTALL_SUCCEEDED;
10812        }
10813
10814        @Override
10815        int doPostCopy(int uid) {
10816            if (isFwdLocked()) {
10817                if (uid < Process.FIRST_APPLICATION_UID
10818                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
10819                                RES_FILE_NAME)) {
10820                    Slog.e(TAG, "Failed to finalize " + cid);
10821                    PackageHelper.destroySdDir(cid);
10822                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10823                }
10824            }
10825
10826            return PackageManager.INSTALL_SUCCEEDED;
10827        }
10828    }
10829
10830    /**
10831     * Logic to handle movement of existing installed applications.
10832     */
10833    class MoveInstallArgs extends InstallArgs {
10834        private File codeFile;
10835        private File resourceFile;
10836
10837        /** New install */
10838        MoveInstallArgs(InstallParams params) {
10839            super(params.origin, params.move, params.observer, params.installFlags,
10840                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10841                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10842        }
10843
10844        int copyApk(IMediaContainerService imcs, boolean temp) {
10845            Slog.d(TAG, "Moving " + move.packageName + " from " + move.fromUuid + " to "
10846                    + move.toUuid);
10847            synchronized (mInstaller) {
10848                if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
10849                        move.dataAppName, move.appId, move.seinfo) != 0) {
10850                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10851                }
10852            }
10853
10854            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
10855            resourceFile = codeFile;
10856            Slog.d(TAG, "codeFile after move is " + codeFile);
10857
10858            return PackageManager.INSTALL_SUCCEEDED;
10859        }
10860
10861        int doPreInstall(int status) {
10862            if (status != PackageManager.INSTALL_SUCCEEDED) {
10863                cleanUp();
10864            }
10865            return status;
10866        }
10867
10868        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10869            if (status != PackageManager.INSTALL_SUCCEEDED) {
10870                cleanUp();
10871                return false;
10872            }
10873
10874            // Reflect the move in app info
10875            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10876            pkg.applicationInfo.setCodePath(pkg.codePath);
10877            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10878            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10879            pkg.applicationInfo.setResourcePath(pkg.codePath);
10880            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10881            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10882
10883            return true;
10884        }
10885
10886        int doPostInstall(int status, int uid) {
10887            if (status != PackageManager.INSTALL_SUCCEEDED) {
10888                cleanUp();
10889            }
10890            return status;
10891        }
10892
10893        @Override
10894        String getCodePath() {
10895            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10896        }
10897
10898        @Override
10899        String getResourcePath() {
10900            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10901        }
10902
10903        private boolean cleanUp() {
10904            if (codeFile == null || !codeFile.exists()) {
10905                return false;
10906            }
10907
10908            if (codeFile.isDirectory()) {
10909                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10910            } else {
10911                codeFile.delete();
10912            }
10913
10914            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10915                resourceFile.delete();
10916            }
10917
10918            return true;
10919        }
10920
10921        void cleanUpResourcesLI() {
10922            cleanUp();
10923        }
10924
10925        boolean doPostDeleteLI(boolean delete) {
10926            // XXX err, shouldn't we respect the delete flag?
10927            cleanUpResourcesLI();
10928            return true;
10929        }
10930    }
10931
10932    static String getAsecPackageName(String packageCid) {
10933        int idx = packageCid.lastIndexOf("-");
10934        if (idx == -1) {
10935            return packageCid;
10936        }
10937        return packageCid.substring(0, idx);
10938    }
10939
10940    // Utility method used to create code paths based on package name and available index.
10941    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
10942        String idxStr = "";
10943        int idx = 1;
10944        // Fall back to default value of idx=1 if prefix is not
10945        // part of oldCodePath
10946        if (oldCodePath != null) {
10947            String subStr = oldCodePath;
10948            // Drop the suffix right away
10949            if (suffix != null && subStr.endsWith(suffix)) {
10950                subStr = subStr.substring(0, subStr.length() - suffix.length());
10951            }
10952            // If oldCodePath already contains prefix find out the
10953            // ending index to either increment or decrement.
10954            int sidx = subStr.lastIndexOf(prefix);
10955            if (sidx != -1) {
10956                subStr = subStr.substring(sidx + prefix.length());
10957                if (subStr != null) {
10958                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
10959                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
10960                    }
10961                    try {
10962                        idx = Integer.parseInt(subStr);
10963                        if (idx <= 1) {
10964                            idx++;
10965                        } else {
10966                            idx--;
10967                        }
10968                    } catch(NumberFormatException e) {
10969                    }
10970                }
10971            }
10972        }
10973        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
10974        return prefix + idxStr;
10975    }
10976
10977    private File getNextCodePath(File targetDir, String packageName) {
10978        int suffix = 1;
10979        File result;
10980        do {
10981            result = new File(targetDir, packageName + "-" + suffix);
10982            suffix++;
10983        } while (result.exists());
10984        return result;
10985    }
10986
10987    // Utility method that returns the relative package path with respect
10988    // to the installation directory. Like say for /data/data/com.test-1.apk
10989    // string com.test-1 is returned.
10990    static String deriveCodePathName(String codePath) {
10991        if (codePath == null) {
10992            return null;
10993        }
10994        final File codeFile = new File(codePath);
10995        final String name = codeFile.getName();
10996        if (codeFile.isDirectory()) {
10997            return name;
10998        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
10999            final int lastDot = name.lastIndexOf('.');
11000            return name.substring(0, lastDot);
11001        } else {
11002            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11003            return null;
11004        }
11005    }
11006
11007    class PackageInstalledInfo {
11008        String name;
11009        int uid;
11010        // The set of users that originally had this package installed.
11011        int[] origUsers;
11012        // The set of users that now have this package installed.
11013        int[] newUsers;
11014        PackageParser.Package pkg;
11015        int returnCode;
11016        String returnMsg;
11017        PackageRemovedInfo removedInfo;
11018
11019        public void setError(int code, String msg) {
11020            returnCode = code;
11021            returnMsg = msg;
11022            Slog.w(TAG, msg);
11023        }
11024
11025        public void setError(String msg, PackageParserException e) {
11026            returnCode = e.error;
11027            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11028            Slog.w(TAG, msg, e);
11029        }
11030
11031        public void setError(String msg, PackageManagerException e) {
11032            returnCode = e.error;
11033            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11034            Slog.w(TAG, msg, e);
11035        }
11036
11037        // In some error cases we want to convey more info back to the observer
11038        String origPackage;
11039        String origPermission;
11040    }
11041
11042    /*
11043     * Install a non-existing package.
11044     */
11045    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11046            UserHandle user, String installerPackageName, String volumeUuid,
11047            PackageInstalledInfo res) {
11048        // Remember this for later, in case we need to rollback this install
11049        String pkgName = pkg.packageName;
11050
11051        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11052        final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName,
11053                UserHandle.USER_OWNER).exists();
11054        synchronized(mPackages) {
11055            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11056                // A package with the same name is already installed, though
11057                // it has been renamed to an older name.  The package we
11058                // are trying to install should be installed as an update to
11059                // the existing one, but that has not been requested, so bail.
11060                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11061                        + " without first uninstalling package running as "
11062                        + mSettings.mRenamedPackages.get(pkgName));
11063                return;
11064            }
11065            if (mPackages.containsKey(pkgName)) {
11066                // Don't allow installation over an existing package with the same name.
11067                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11068                        + " without first uninstalling.");
11069                return;
11070            }
11071        }
11072
11073        try {
11074            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11075                    System.currentTimeMillis(), user);
11076
11077            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11078            // delete the partially installed application. the data directory will have to be
11079            // restored if it was already existing
11080            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11081                // remove package from internal structures.  Note that we want deletePackageX to
11082                // delete the package data and cache directories that it created in
11083                // scanPackageLocked, unless those directories existed before we even tried to
11084                // install.
11085                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11086                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11087                                res.removedInfo, true);
11088            }
11089
11090        } catch (PackageManagerException e) {
11091            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11092        }
11093    }
11094
11095    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11096        // Upgrade keysets are being used.  Determine if new package has a superset of the
11097        // required keys.
11098        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11099        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11100        for (int i = 0; i < upgradeKeySets.length; i++) {
11101            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11102            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
11103                return true;
11104            }
11105        }
11106        return false;
11107    }
11108
11109    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11110            UserHandle user, String installerPackageName, String volumeUuid,
11111            PackageInstalledInfo res) {
11112        final PackageParser.Package oldPackage;
11113        final String pkgName = pkg.packageName;
11114        final int[] allUsers;
11115        final boolean[] perUserInstalled;
11116        final boolean weFroze;
11117
11118        // First find the old package info and check signatures
11119        synchronized(mPackages) {
11120            oldPackage = mPackages.get(pkgName);
11121            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11122            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11123            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
11124                // default to original signature matching
11125                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11126                    != PackageManager.SIGNATURE_MATCH) {
11127                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11128                            "New package has a different signature: " + pkgName);
11129                    return;
11130                }
11131            } else {
11132                if(!checkUpgradeKeySetLP(ps, pkg)) {
11133                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11134                            "New package not signed by keys specified by upgrade-keysets: "
11135                            + pkgName);
11136                    return;
11137                }
11138            }
11139
11140            // In case of rollback, remember per-user/profile install state
11141            allUsers = sUserManager.getUserIds();
11142            perUserInstalled = new boolean[allUsers.length];
11143            for (int i = 0; i < allUsers.length; i++) {
11144                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11145            }
11146
11147            // Mark the app as frozen to prevent launching during the upgrade
11148            // process, and then kill all running instances
11149            if (!ps.frozen) {
11150                ps.frozen = true;
11151                weFroze = true;
11152            } else {
11153                weFroze = false;
11154            }
11155        }
11156
11157        // Now that we're guarded by frozen state, kill app during upgrade
11158        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11159
11160        try {
11161            boolean sysPkg = (isSystemApp(oldPackage));
11162            if (sysPkg) {
11163                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11164                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11165            } else {
11166                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11167                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11168            }
11169        } finally {
11170            // Regardless of success or failure of upgrade steps above, always
11171            // unfreeze the package if we froze it
11172            if (weFroze) {
11173                unfreezePackage(pkgName);
11174            }
11175        }
11176    }
11177
11178    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11179            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11180            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11181            String volumeUuid, PackageInstalledInfo res) {
11182        String pkgName = deletedPackage.packageName;
11183        boolean deletedPkg = true;
11184        boolean updatedSettings = false;
11185
11186        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11187                + deletedPackage);
11188        long origUpdateTime;
11189        if (pkg.mExtras != null) {
11190            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11191        } else {
11192            origUpdateTime = 0;
11193        }
11194
11195        // First delete the existing package while retaining the data directory
11196        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11197                res.removedInfo, true)) {
11198            // If the existing package wasn't successfully deleted
11199            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11200            deletedPkg = false;
11201        } else {
11202            // Successfully deleted the old package; proceed with replace.
11203
11204            // If deleted package lived in a container, give users a chance to
11205            // relinquish resources before killing.
11206            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11207                if (DEBUG_INSTALL) {
11208                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11209                }
11210                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11211                final ArrayList<String> pkgList = new ArrayList<String>(1);
11212                pkgList.add(deletedPackage.applicationInfo.packageName);
11213                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11214            }
11215
11216            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11217            try {
11218                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11219                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11220                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11221                        perUserInstalled, res, user);
11222                updatedSettings = true;
11223            } catch (PackageManagerException e) {
11224                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11225            }
11226        }
11227
11228        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11229            // remove package from internal structures.  Note that we want deletePackageX to
11230            // delete the package data and cache directories that it created in
11231            // scanPackageLocked, unless those directories existed before we even tried to
11232            // install.
11233            if(updatedSettings) {
11234                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11235                deletePackageLI(
11236                        pkgName, null, true, allUsers, perUserInstalled,
11237                        PackageManager.DELETE_KEEP_DATA,
11238                                res.removedInfo, true);
11239            }
11240            // Since we failed to install the new package we need to restore the old
11241            // package that we deleted.
11242            if (deletedPkg) {
11243                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11244                File restoreFile = new File(deletedPackage.codePath);
11245                // Parse old package
11246                boolean oldExternal = isExternal(deletedPackage);
11247                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11248                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11249                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11250                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11251                try {
11252                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11253                } catch (PackageManagerException e) {
11254                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11255                            + e.getMessage());
11256                    return;
11257                }
11258                // Restore of old package succeeded. Update permissions.
11259                // writer
11260                synchronized (mPackages) {
11261                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11262                            UPDATE_PERMISSIONS_ALL);
11263                    // can downgrade to reader
11264                    mSettings.writeLPr();
11265                }
11266                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11267            }
11268        }
11269    }
11270
11271    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11272            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11273            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11274            String volumeUuid, PackageInstalledInfo res) {
11275        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11276                + ", old=" + deletedPackage);
11277        boolean disabledSystem = false;
11278        boolean updatedSettings = false;
11279        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11280        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11281                != 0) {
11282            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11283        }
11284        String packageName = deletedPackage.packageName;
11285        if (packageName == null) {
11286            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11287                    "Attempt to delete null packageName.");
11288            return;
11289        }
11290        PackageParser.Package oldPkg;
11291        PackageSetting oldPkgSetting;
11292        // reader
11293        synchronized (mPackages) {
11294            oldPkg = mPackages.get(packageName);
11295            oldPkgSetting = mSettings.mPackages.get(packageName);
11296            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11297                    (oldPkgSetting == null)) {
11298                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11299                        "Couldn't find package:" + packageName + " information");
11300                return;
11301            }
11302        }
11303
11304        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11305        res.removedInfo.removedPackage = packageName;
11306        // Remove existing system package
11307        removePackageLI(oldPkgSetting, true);
11308        // writer
11309        synchronized (mPackages) {
11310            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11311            if (!disabledSystem && deletedPackage != null) {
11312                // We didn't need to disable the .apk as a current system package,
11313                // which means we are replacing another update that is already
11314                // installed.  We need to make sure to delete the older one's .apk.
11315                res.removedInfo.args = createInstallArgsForExisting(0,
11316                        deletedPackage.applicationInfo.getCodePath(),
11317                        deletedPackage.applicationInfo.getResourcePath(),
11318                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11319            } else {
11320                res.removedInfo.args = null;
11321            }
11322        }
11323
11324        // Successfully disabled the old package. Now proceed with re-installation
11325        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11326
11327        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11328        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11329
11330        PackageParser.Package newPackage = null;
11331        try {
11332            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11333            if (newPackage.mExtras != null) {
11334                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11335                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11336                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11337
11338                // is the update attempting to change shared user? that isn't going to work...
11339                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11340                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11341                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11342                            + " to " + newPkgSetting.sharedUser);
11343                    updatedSettings = true;
11344                }
11345            }
11346
11347            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11348                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11349                        perUserInstalled, res, user);
11350                updatedSettings = true;
11351            }
11352
11353        } catch (PackageManagerException e) {
11354            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11355        }
11356
11357        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11358            // Re installation failed. Restore old information
11359            // Remove new pkg information
11360            if (newPackage != null) {
11361                removeInstalledPackageLI(newPackage, true);
11362            }
11363            // Add back the old system package
11364            try {
11365                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11366            } catch (PackageManagerException e) {
11367                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11368            }
11369            // Restore the old system information in Settings
11370            synchronized (mPackages) {
11371                if (disabledSystem) {
11372                    mSettings.enableSystemPackageLPw(packageName);
11373                }
11374                if (updatedSettings) {
11375                    mSettings.setInstallerPackageName(packageName,
11376                            oldPkgSetting.installerPackageName);
11377                }
11378                mSettings.writeLPr();
11379            }
11380        }
11381    }
11382
11383    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
11384            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
11385            UserHandle user) {
11386        String pkgName = newPackage.packageName;
11387        synchronized (mPackages) {
11388            //write settings. the installStatus will be incomplete at this stage.
11389            //note that the new package setting would have already been
11390            //added to mPackages. It hasn't been persisted yet.
11391            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11392            mSettings.writeLPr();
11393        }
11394
11395        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11396
11397        synchronized (mPackages) {
11398            updatePermissionsLPw(newPackage.packageName, newPackage,
11399                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11400                            ? UPDATE_PERMISSIONS_ALL : 0));
11401            // For system-bundled packages, we assume that installing an upgraded version
11402            // of the package implies that the user actually wants to run that new code,
11403            // so we enable the package.
11404            PackageSetting ps = mSettings.mPackages.get(pkgName);
11405            if (ps != null) {
11406                if (isSystemApp(newPackage)) {
11407                    // NB: implicit assumption that system package upgrades apply to all users
11408                    if (DEBUG_INSTALL) {
11409                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
11410                    }
11411                    if (res.origUsers != null) {
11412                        for (int userHandle : res.origUsers) {
11413                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
11414                                    userHandle, installerPackageName);
11415                        }
11416                    }
11417                    // Also convey the prior install/uninstall state
11418                    if (allUsers != null && perUserInstalled != null) {
11419                        for (int i = 0; i < allUsers.length; i++) {
11420                            if (DEBUG_INSTALL) {
11421                                Slog.d(TAG, "    user " + allUsers[i]
11422                                        + " => " + perUserInstalled[i]);
11423                            }
11424                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
11425                        }
11426                        // these install state changes will be persisted in the
11427                        // upcoming call to mSettings.writeLPr().
11428                    }
11429                }
11430                // It's implied that when a user requests installation, they want the app to be
11431                // installed and enabled.
11432                int userId = user.getIdentifier();
11433                if (userId != UserHandle.USER_ALL) {
11434                    ps.setInstalled(true, userId);
11435                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
11436                }
11437            }
11438            res.name = pkgName;
11439            res.uid = newPackage.applicationInfo.uid;
11440            res.pkg = newPackage;
11441            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
11442            mSettings.setInstallerPackageName(pkgName, installerPackageName);
11443            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11444            //to update install status
11445            mSettings.writeLPr();
11446        }
11447    }
11448
11449    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
11450        final int installFlags = args.installFlags;
11451        final String installerPackageName = args.installerPackageName;
11452        final String volumeUuid = args.volumeUuid;
11453        final File tmpPackageFile = new File(args.getCodePath());
11454        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
11455        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
11456                || (args.volumeUuid != null));
11457        boolean replace = false;
11458        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
11459        // Result object to be returned
11460        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11461
11462        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
11463        // Retrieve PackageSettings and parse package
11464        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
11465                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
11466                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11467        PackageParser pp = new PackageParser();
11468        pp.setSeparateProcesses(mSeparateProcesses);
11469        pp.setDisplayMetrics(mMetrics);
11470
11471        final PackageParser.Package pkg;
11472        try {
11473            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
11474        } catch (PackageParserException e) {
11475            res.setError("Failed parse during installPackageLI", e);
11476            return;
11477        }
11478
11479        // Mark that we have an install time CPU ABI override.
11480        pkg.cpuAbiOverride = args.abiOverride;
11481
11482        String pkgName = res.name = pkg.packageName;
11483        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
11484            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
11485                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
11486                return;
11487            }
11488        }
11489
11490        try {
11491            pp.collectCertificates(pkg, parseFlags);
11492            pp.collectManifestDigest(pkg);
11493        } catch (PackageParserException e) {
11494            res.setError("Failed collect during installPackageLI", e);
11495            return;
11496        }
11497
11498        /* If the installer passed in a manifest digest, compare it now. */
11499        if (args.manifestDigest != null) {
11500            if (DEBUG_INSTALL) {
11501                final String parsedManifest = pkg.manifestDigest == null ? "null"
11502                        : pkg.manifestDigest.toString();
11503                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
11504                        + parsedManifest);
11505            }
11506
11507            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
11508                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
11509                return;
11510            }
11511        } else if (DEBUG_INSTALL) {
11512            final String parsedManifest = pkg.manifestDigest == null
11513                    ? "null" : pkg.manifestDigest.toString();
11514            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
11515        }
11516
11517        // Get rid of all references to package scan path via parser.
11518        pp = null;
11519        String oldCodePath = null;
11520        boolean systemApp = false;
11521        synchronized (mPackages) {
11522            // Check if installing already existing package
11523            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11524                String oldName = mSettings.mRenamedPackages.get(pkgName);
11525                if (pkg.mOriginalPackages != null
11526                        && pkg.mOriginalPackages.contains(oldName)
11527                        && mPackages.containsKey(oldName)) {
11528                    // This package is derived from an original package,
11529                    // and this device has been updating from that original
11530                    // name.  We must continue using the original name, so
11531                    // rename the new package here.
11532                    pkg.setPackageName(oldName);
11533                    pkgName = pkg.packageName;
11534                    replace = true;
11535                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
11536                            + oldName + " pkgName=" + pkgName);
11537                } else if (mPackages.containsKey(pkgName)) {
11538                    // This package, under its official name, already exists
11539                    // on the device; we should replace it.
11540                    replace = true;
11541                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
11542                }
11543
11544                // Prevent apps opting out from runtime permissions
11545                if (replace) {
11546                    PackageParser.Package oldPackage = mPackages.get(pkgName);
11547                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
11548                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
11549                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
11550                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
11551                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
11552                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
11553                                        + " doesn't support runtime permissions but the old"
11554                                        + " target SDK " + oldTargetSdk + " does.");
11555                        return;
11556                    }
11557                }
11558            }
11559
11560            PackageSetting ps = mSettings.mPackages.get(pkgName);
11561            if (ps != null) {
11562                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
11563
11564                // Quick sanity check that we're signed correctly if updating;
11565                // we'll check this again later when scanning, but we want to
11566                // bail early here before tripping over redefined permissions.
11567                if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
11568                    try {
11569                        verifySignaturesLP(ps, pkg);
11570                    } catch (PackageManagerException e) {
11571                        res.setError(e.error, e.getMessage());
11572                        return;
11573                    }
11574                } else {
11575                    if (!checkUpgradeKeySetLP(ps, pkg)) {
11576                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
11577                                + pkg.packageName + " upgrade keys do not match the "
11578                                + "previously installed version");
11579                        return;
11580                    }
11581                }
11582
11583                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
11584                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
11585                    systemApp = (ps.pkg.applicationInfo.flags &
11586                            ApplicationInfo.FLAG_SYSTEM) != 0;
11587                }
11588                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11589            }
11590
11591            // Check whether the newly-scanned package wants to define an already-defined perm
11592            int N = pkg.permissions.size();
11593            for (int i = N-1; i >= 0; i--) {
11594                PackageParser.Permission perm = pkg.permissions.get(i);
11595                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
11596                if (bp != null) {
11597                    // If the defining package is signed with our cert, it's okay.  This
11598                    // also includes the "updating the same package" case, of course.
11599                    // "updating same package" could also involve key-rotation.
11600                    final boolean sigsOk;
11601                    if (!bp.sourcePackage.equals(pkg.packageName)
11602                            || !(bp.packageSetting instanceof PackageSetting)
11603                            || !bp.packageSetting.keySetData.isUsingUpgradeKeySets()
11604                            || ((PackageSetting) bp.packageSetting).sharedUser != null) {
11605                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
11606                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
11607                    } else {
11608                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
11609                    }
11610                    if (!sigsOk) {
11611                        // If the owning package is the system itself, we log but allow
11612                        // install to proceed; we fail the install on all other permission
11613                        // redefinitions.
11614                        if (!bp.sourcePackage.equals("android")) {
11615                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
11616                                    + pkg.packageName + " attempting to redeclare permission "
11617                                    + perm.info.name + " already owned by " + bp.sourcePackage);
11618                            res.origPermission = perm.info.name;
11619                            res.origPackage = bp.sourcePackage;
11620                            return;
11621                        } else {
11622                            Slog.w(TAG, "Package " + pkg.packageName
11623                                    + " attempting to redeclare system permission "
11624                                    + perm.info.name + "; ignoring new declaration");
11625                            pkg.permissions.remove(i);
11626                        }
11627                    }
11628                }
11629            }
11630
11631        }
11632
11633        if (systemApp && onExternal) {
11634            // Disable updates to system apps on sdcard
11635            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11636                    "Cannot install updates to system apps on sdcard");
11637            return;
11638        }
11639
11640        if (args.move != null) {
11641            // We did an in-place move, so dex is ready to roll
11642            scanFlags |= SCAN_NO_DEX;
11643            scanFlags |= SCAN_MOVE;
11644        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
11645            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
11646            scanFlags |= SCAN_NO_DEX;
11647
11648            try {
11649                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
11650                        true /* extract libs */);
11651            } catch (PackageManagerException pme) {
11652                Slog.e(TAG, "Error deriving application ABI", pme);
11653                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
11654                return;
11655            }
11656
11657            // Run dexopt before old package gets removed, to minimize time when app is unavailable
11658            int result = mPackageDexOptimizer
11659                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
11660                            false /* defer */, false /* inclDependencies */);
11661            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
11662                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
11663                return;
11664            }
11665        }
11666
11667        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
11668            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
11669            return;
11670        }
11671
11672        startIntentFilterVerifications(args.user.getIdentifier(), pkg);
11673
11674        if (replace) {
11675            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
11676                    installerPackageName, volumeUuid, res);
11677        } else {
11678            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
11679                    args.user, installerPackageName, volumeUuid, res);
11680        }
11681        synchronized (mPackages) {
11682            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11683            if (ps != null) {
11684                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11685            }
11686        }
11687    }
11688
11689    private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) {
11690        if (mIntentFilterVerifierComponent == null) {
11691            Slog.d(TAG, "No IntentFilter verification will not be done as "
11692                    + "there is no IntentFilterVerifier available!");
11693            return;
11694        }
11695
11696        final int verifierUid = getPackageUid(
11697                mIntentFilterVerifierComponent.getPackageName(),
11698                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
11699
11700        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
11701        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
11702        msg.obj = pkg;
11703        msg.arg1 = userId;
11704        msg.arg2 = verifierUid;
11705
11706        mHandler.sendMessage(msg);
11707    }
11708
11709    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid,
11710            PackageParser.Package pkg) {
11711        int size = pkg.activities.size();
11712        if (size == 0) {
11713            Slog.d(TAG, "No activity, so no need to verify any IntentFilter!");
11714            return;
11715        }
11716
11717        final boolean hasDomainURLs = hasDomainURLs(pkg);
11718        if (!hasDomainURLs) {
11719            Slog.d(TAG, "No domain URLs, so no need to verify any IntentFilter!");
11720            return;
11721        }
11722
11723        Slog.d(TAG, "Checking for userId:" + userId + " if any IntentFilter from the " + size
11724                + " Activities needs verification ...");
11725
11726        final int verificationId = mIntentFilterVerificationToken++;
11727        int count = 0;
11728        final String packageName = pkg.packageName;
11729        ArrayList<String> allHosts = new ArrayList<>();
11730
11731        synchronized (mPackages) {
11732            for (PackageParser.Activity a : pkg.activities) {
11733                for (ActivityIntentInfo filter : a.intents) {
11734                    boolean needsFilterVerification = filter.needsVerification();
11735                    if (needsFilterVerification && needsNetworkVerificationLPr(filter)) {
11736                        Slog.d(TAG, "Verification needed for IntentFilter:" + filter.toString());
11737                        mIntentFilterVerifier.addOneIntentFilterVerification(
11738                                verifierUid, userId, verificationId, filter, packageName);
11739                        count++;
11740                    } else if (!needsFilterVerification) {
11741                        Slog.d(TAG, "No verification needed for IntentFilter:" + filter.toString());
11742                        if (hasValidDomains(filter)) {
11743                            ArrayList<String> hosts = filter.getHostsList();
11744                            if (hosts.size() > 0) {
11745                                allHosts.addAll(hosts);
11746                            } else {
11747                                if (allHosts.isEmpty()) {
11748                                    allHosts.add("*");
11749                                }
11750                            }
11751                        }
11752                    } else {
11753                        Slog.d(TAG, "Verification already done for IntentFilter:"
11754                                + filter.toString());
11755                    }
11756                }
11757            }
11758        }
11759
11760        if (count > 0) {
11761            mIntentFilterVerifier.startVerifications(userId);
11762            Slog.d(TAG, "Started " + count + " IntentFilter verification"
11763                    + (count > 1 ? "s" : "") +  " for userId:" + userId + "!");
11764        } else {
11765            Slog.d(TAG, "No need to start any IntentFilter verification!");
11766            if (allHosts.size() > 0 && mSettings.createIntentFilterVerificationIfNeededLPw(
11767                    packageName, allHosts) != null) {
11768                scheduleWriteSettingsLocked();
11769            }
11770        }
11771    }
11772
11773    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
11774        final ComponentName cn  = filter.activity.getComponentName();
11775        final String packageName = cn.getPackageName();
11776
11777        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
11778                packageName);
11779        if (ivi == null) {
11780            return true;
11781        }
11782        int status = ivi.getStatus();
11783        switch (status) {
11784            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
11785            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
11786                return true;
11787
11788            default:
11789                // Nothing to do
11790                return false;
11791        }
11792    }
11793
11794    private boolean isSystemComponentOrPersistentPrivApp(PackageParser.Package pkg) {
11795        return UserHandle.getAppId(pkg.applicationInfo.uid) < FIRST_APPLICATION_UID
11796                || ((pkg.applicationInfo.privateFlags
11797                        & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0
11798                && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0);
11799    }
11800
11801    private static boolean isMultiArch(PackageSetting ps) {
11802        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
11803    }
11804
11805    private static boolean isMultiArch(ApplicationInfo info) {
11806        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
11807    }
11808
11809    private static boolean isExternal(PackageParser.Package pkg) {
11810        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11811    }
11812
11813    private static boolean isExternal(PackageSetting ps) {
11814        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11815    }
11816
11817    private static boolean isExternal(ApplicationInfo info) {
11818        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11819    }
11820
11821    private static boolean isSystemApp(PackageParser.Package pkg) {
11822        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
11823    }
11824
11825    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
11826        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
11827    }
11828
11829    private static boolean hasDomainURLs(PackageParser.Package pkg) {
11830        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
11831    }
11832
11833    private static boolean isSystemApp(PackageSetting ps) {
11834        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
11835    }
11836
11837    private static boolean isUpdatedSystemApp(PackageSetting ps) {
11838        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
11839    }
11840
11841    private int packageFlagsToInstallFlags(PackageSetting ps) {
11842        int installFlags = 0;
11843        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
11844            // This existing package was an external ASEC install when we have
11845            // the external flag without a UUID
11846            installFlags |= PackageManager.INSTALL_EXTERNAL;
11847        }
11848        if (ps.isForwardLocked()) {
11849            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
11850        }
11851        return installFlags;
11852    }
11853
11854    private void deleteTempPackageFiles() {
11855        final FilenameFilter filter = new FilenameFilter() {
11856            public boolean accept(File dir, String name) {
11857                return name.startsWith("vmdl") && name.endsWith(".tmp");
11858            }
11859        };
11860        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
11861            file.delete();
11862        }
11863    }
11864
11865    @Override
11866    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
11867            int flags) {
11868        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
11869                flags);
11870    }
11871
11872    @Override
11873    public void deletePackage(final String packageName,
11874            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
11875        mContext.enforceCallingOrSelfPermission(
11876                android.Manifest.permission.DELETE_PACKAGES, null);
11877        final int uid = Binder.getCallingUid();
11878        if (UserHandle.getUserId(uid) != userId) {
11879            mContext.enforceCallingPermission(
11880                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
11881                    "deletePackage for user " + userId);
11882        }
11883        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
11884            try {
11885                observer.onPackageDeleted(packageName,
11886                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
11887            } catch (RemoteException re) {
11888            }
11889            return;
11890        }
11891
11892        boolean uninstallBlocked = false;
11893        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
11894            int[] users = sUserManager.getUserIds();
11895            for (int i = 0; i < users.length; ++i) {
11896                if (getBlockUninstallForUser(packageName, users[i])) {
11897                    uninstallBlocked = true;
11898                    break;
11899                }
11900            }
11901        } else {
11902            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
11903        }
11904        if (uninstallBlocked) {
11905            try {
11906                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
11907                        null);
11908            } catch (RemoteException re) {
11909            }
11910            return;
11911        }
11912
11913        if (DEBUG_REMOVE) {
11914            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
11915        }
11916        // Queue up an async operation since the package deletion may take a little while.
11917        mHandler.post(new Runnable() {
11918            public void run() {
11919                mHandler.removeCallbacks(this);
11920                final int returnCode = deletePackageX(packageName, userId, flags);
11921                if (observer != null) {
11922                    try {
11923                        observer.onPackageDeleted(packageName, returnCode, null);
11924                    } catch (RemoteException e) {
11925                        Log.i(TAG, "Observer no longer exists.");
11926                    } //end catch
11927                } //end if
11928            } //end run
11929        });
11930    }
11931
11932    private boolean isPackageDeviceAdmin(String packageName, int userId) {
11933        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
11934                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
11935        try {
11936            if (dpm != null) {
11937                if (dpm.isDeviceOwner(packageName)) {
11938                    return true;
11939                }
11940                int[] users;
11941                if (userId == UserHandle.USER_ALL) {
11942                    users = sUserManager.getUserIds();
11943                } else {
11944                    users = new int[]{userId};
11945                }
11946                for (int i = 0; i < users.length; ++i) {
11947                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
11948                        return true;
11949                    }
11950                }
11951            }
11952        } catch (RemoteException e) {
11953        }
11954        return false;
11955    }
11956
11957    /**
11958     *  This method is an internal method that could be get invoked either
11959     *  to delete an installed package or to clean up a failed installation.
11960     *  After deleting an installed package, a broadcast is sent to notify any
11961     *  listeners that the package has been installed. For cleaning up a failed
11962     *  installation, the broadcast is not necessary since the package's
11963     *  installation wouldn't have sent the initial broadcast either
11964     *  The key steps in deleting a package are
11965     *  deleting the package information in internal structures like mPackages,
11966     *  deleting the packages base directories through installd
11967     *  updating mSettings to reflect current status
11968     *  persisting settings for later use
11969     *  sending a broadcast if necessary
11970     */
11971    private int deletePackageX(String packageName, int userId, int flags) {
11972        final PackageRemovedInfo info = new PackageRemovedInfo();
11973        final boolean res;
11974
11975        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
11976                ? UserHandle.ALL : new UserHandle(userId);
11977
11978        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
11979            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
11980            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
11981        }
11982
11983        boolean removedForAllUsers = false;
11984        boolean systemUpdate = false;
11985
11986        // for the uninstall-updates case and restricted profiles, remember the per-
11987        // userhandle installed state
11988        int[] allUsers;
11989        boolean[] perUserInstalled;
11990        synchronized (mPackages) {
11991            PackageSetting ps = mSettings.mPackages.get(packageName);
11992            allUsers = sUserManager.getUserIds();
11993            perUserInstalled = new boolean[allUsers.length];
11994            for (int i = 0; i < allUsers.length; i++) {
11995                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11996            }
11997        }
11998
11999        synchronized (mInstallLock) {
12000            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12001            res = deletePackageLI(packageName, removeForUser,
12002                    true, allUsers, perUserInstalled,
12003                    flags | REMOVE_CHATTY, info, true);
12004            systemUpdate = info.isRemovedPackageSystemUpdate;
12005            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12006                removedForAllUsers = true;
12007            }
12008            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12009                    + " removedForAllUsers=" + removedForAllUsers);
12010        }
12011
12012        if (res) {
12013            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12014
12015            // If the removed package was a system update, the old system package
12016            // was re-enabled; we need to broadcast this information
12017            if (systemUpdate) {
12018                Bundle extras = new Bundle(1);
12019                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12020                        ? info.removedAppId : info.uid);
12021                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12022
12023                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12024                        extras, null, null, null);
12025                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12026                        extras, null, null, null);
12027                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12028                        null, packageName, null, null);
12029            }
12030        }
12031        // Force a gc here.
12032        Runtime.getRuntime().gc();
12033        // Delete the resources here after sending the broadcast to let
12034        // other processes clean up before deleting resources.
12035        if (info.args != null) {
12036            synchronized (mInstallLock) {
12037                info.args.doPostDeleteLI(true);
12038            }
12039        }
12040
12041        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12042    }
12043
12044    class PackageRemovedInfo {
12045        String removedPackage;
12046        int uid = -1;
12047        int removedAppId = -1;
12048        int[] removedUsers = null;
12049        boolean isRemovedPackageSystemUpdate = false;
12050        // Clean up resources deleted packages.
12051        InstallArgs args = null;
12052
12053        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12054            Bundle extras = new Bundle(1);
12055            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12056            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12057            if (replacing) {
12058                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12059            }
12060            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12061            if (removedPackage != null) {
12062                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12063                        extras, null, null, removedUsers);
12064                if (fullRemove && !replacing) {
12065                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12066                            extras, null, null, removedUsers);
12067                }
12068            }
12069            if (removedAppId >= 0) {
12070                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12071                        removedUsers);
12072            }
12073        }
12074    }
12075
12076    /*
12077     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12078     * flag is not set, the data directory is removed as well.
12079     * make sure this flag is set for partially installed apps. If not its meaningless to
12080     * delete a partially installed application.
12081     */
12082    private void removePackageDataLI(PackageSetting ps,
12083            int[] allUserHandles, boolean[] perUserInstalled,
12084            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12085        String packageName = ps.name;
12086        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12087        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12088        // Retrieve object to delete permissions for shared user later on
12089        final PackageSetting deletedPs;
12090        // reader
12091        synchronized (mPackages) {
12092            deletedPs = mSettings.mPackages.get(packageName);
12093            if (outInfo != null) {
12094                outInfo.removedPackage = packageName;
12095                outInfo.removedUsers = deletedPs != null
12096                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12097                        : null;
12098            }
12099        }
12100        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12101            removeDataDirsLI(ps.volumeUuid, packageName);
12102            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12103        }
12104        // writer
12105        synchronized (mPackages) {
12106            if (deletedPs != null) {
12107                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12108                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12109                    clearDefaultBrowserIfNeeded(packageName);
12110                    if (outInfo != null) {
12111                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12112                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12113                    }
12114                    updatePermissionsLPw(deletedPs.name, null, 0);
12115                    if (deletedPs.sharedUser != null) {
12116                        // Remove permissions associated with package. Since runtime
12117                        // permissions are per user we have to kill the removed package
12118                        // or packages running under the shared user of the removed
12119                        // package if revoking the permissions requested only by the removed
12120                        // package is successful and this causes a change in gids.
12121                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12122                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12123                                    userId);
12124                            if (userIdToKill == UserHandle.USER_ALL
12125                                    || userIdToKill >= UserHandle.USER_OWNER) {
12126                                // If gids changed for this user, kill all affected packages.
12127                                mHandler.post(new Runnable() {
12128                                    @Override
12129                                    public void run() {
12130                                        // This has to happen with no lock held.
12131                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12132                                                KILL_APP_REASON_GIDS_CHANGED);
12133                                    }
12134                                });
12135                            break;
12136                            }
12137                        }
12138                    }
12139                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12140                }
12141                // make sure to preserve per-user disabled state if this removal was just
12142                // a downgrade of a system app to the factory package
12143                if (allUserHandles != null && perUserInstalled != null) {
12144                    if (DEBUG_REMOVE) {
12145                        Slog.d(TAG, "Propagating install state across downgrade");
12146                    }
12147                    for (int i = 0; i < allUserHandles.length; i++) {
12148                        if (DEBUG_REMOVE) {
12149                            Slog.d(TAG, "    user " + allUserHandles[i]
12150                                    + " => " + perUserInstalled[i]);
12151                        }
12152                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12153                    }
12154                }
12155            }
12156            // can downgrade to reader
12157            if (writeSettings) {
12158                // Save settings now
12159                mSettings.writeLPr();
12160            }
12161        }
12162        if (outInfo != null) {
12163            // A user ID was deleted here. Go through all users and remove it
12164            // from KeyStore.
12165            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12166        }
12167    }
12168
12169    static boolean locationIsPrivileged(File path) {
12170        try {
12171            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12172                    .getCanonicalPath();
12173            return path.getCanonicalPath().startsWith(privilegedAppDir);
12174        } catch (IOException e) {
12175            Slog.e(TAG, "Unable to access code path " + path);
12176        }
12177        return false;
12178    }
12179
12180    /*
12181     * Tries to delete system package.
12182     */
12183    private boolean deleteSystemPackageLI(PackageSetting newPs,
12184            int[] allUserHandles, boolean[] perUserInstalled,
12185            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12186        final boolean applyUserRestrictions
12187                = (allUserHandles != null) && (perUserInstalled != null);
12188        PackageSetting disabledPs = null;
12189        // Confirm if the system package has been updated
12190        // An updated system app can be deleted. This will also have to restore
12191        // the system pkg from system partition
12192        // reader
12193        synchronized (mPackages) {
12194            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12195        }
12196        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12197                + " disabledPs=" + disabledPs);
12198        if (disabledPs == null) {
12199            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12200            return false;
12201        } else if (DEBUG_REMOVE) {
12202            Slog.d(TAG, "Deleting system pkg from data partition");
12203        }
12204        if (DEBUG_REMOVE) {
12205            if (applyUserRestrictions) {
12206                Slog.d(TAG, "Remembering install states:");
12207                for (int i = 0; i < allUserHandles.length; i++) {
12208                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12209                }
12210            }
12211        }
12212        // Delete the updated package
12213        outInfo.isRemovedPackageSystemUpdate = true;
12214        if (disabledPs.versionCode < newPs.versionCode) {
12215            // Delete data for downgrades
12216            flags &= ~PackageManager.DELETE_KEEP_DATA;
12217        } else {
12218            // Preserve data by setting flag
12219            flags |= PackageManager.DELETE_KEEP_DATA;
12220        }
12221        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12222                allUserHandles, perUserInstalled, outInfo, writeSettings);
12223        if (!ret) {
12224            return false;
12225        }
12226        // writer
12227        synchronized (mPackages) {
12228            // Reinstate the old system package
12229            mSettings.enableSystemPackageLPw(newPs.name);
12230            // Remove any native libraries from the upgraded package.
12231            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12232        }
12233        // Install the system package
12234        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12235        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12236        if (locationIsPrivileged(disabledPs.codePath)) {
12237            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12238        }
12239
12240        final PackageParser.Package newPkg;
12241        try {
12242            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12243        } catch (PackageManagerException e) {
12244            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12245            return false;
12246        }
12247
12248        // writer
12249        synchronized (mPackages) {
12250            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12251            updatePermissionsLPw(newPkg.packageName, newPkg,
12252                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12253            if (applyUserRestrictions) {
12254                if (DEBUG_REMOVE) {
12255                    Slog.d(TAG, "Propagating install state across reinstall");
12256                }
12257                for (int i = 0; i < allUserHandles.length; i++) {
12258                    if (DEBUG_REMOVE) {
12259                        Slog.d(TAG, "    user " + allUserHandles[i]
12260                                + " => " + perUserInstalled[i]);
12261                    }
12262                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12263                }
12264                // Regardless of writeSettings we need to ensure that this restriction
12265                // state propagation is persisted
12266                mSettings.writeAllUsersPackageRestrictionsLPr();
12267            }
12268            // can downgrade to reader here
12269            if (writeSettings) {
12270                mSettings.writeLPr();
12271            }
12272        }
12273        return true;
12274    }
12275
12276    private boolean deleteInstalledPackageLI(PackageSetting ps,
12277            boolean deleteCodeAndResources, int flags,
12278            int[] allUserHandles, boolean[] perUserInstalled,
12279            PackageRemovedInfo outInfo, boolean writeSettings) {
12280        if (outInfo != null) {
12281            outInfo.uid = ps.appId;
12282        }
12283
12284        // Delete package data from internal structures and also remove data if flag is set
12285        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12286
12287        // Delete application code and resources
12288        if (deleteCodeAndResources && (outInfo != null)) {
12289            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12290                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12291            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12292        }
12293        return true;
12294    }
12295
12296    @Override
12297    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12298            int userId) {
12299        mContext.enforceCallingOrSelfPermission(
12300                android.Manifest.permission.DELETE_PACKAGES, null);
12301        synchronized (mPackages) {
12302            PackageSetting ps = mSettings.mPackages.get(packageName);
12303            if (ps == null) {
12304                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12305                return false;
12306            }
12307            if (!ps.getInstalled(userId)) {
12308                // Can't block uninstall for an app that is not installed or enabled.
12309                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12310                return false;
12311            }
12312            ps.setBlockUninstall(blockUninstall, userId);
12313            mSettings.writePackageRestrictionsLPr(userId);
12314        }
12315        return true;
12316    }
12317
12318    @Override
12319    public boolean getBlockUninstallForUser(String packageName, int userId) {
12320        synchronized (mPackages) {
12321            PackageSetting ps = mSettings.mPackages.get(packageName);
12322            if (ps == null) {
12323                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
12324                return false;
12325            }
12326            return ps.getBlockUninstall(userId);
12327        }
12328    }
12329
12330    /*
12331     * This method handles package deletion in general
12332     */
12333    private boolean deletePackageLI(String packageName, UserHandle user,
12334            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
12335            int flags, PackageRemovedInfo outInfo,
12336            boolean writeSettings) {
12337        if (packageName == null) {
12338            Slog.w(TAG, "Attempt to delete null packageName.");
12339            return false;
12340        }
12341        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
12342        PackageSetting ps;
12343        boolean dataOnly = false;
12344        int removeUser = -1;
12345        int appId = -1;
12346        synchronized (mPackages) {
12347            ps = mSettings.mPackages.get(packageName);
12348            if (ps == null) {
12349                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12350                return false;
12351            }
12352            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
12353                    && user.getIdentifier() != UserHandle.USER_ALL) {
12354                // The caller is asking that the package only be deleted for a single
12355                // user.  To do this, we just mark its uninstalled state and delete
12356                // its data.  If this is a system app, we only allow this to happen if
12357                // they have set the special DELETE_SYSTEM_APP which requests different
12358                // semantics than normal for uninstalling system apps.
12359                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
12360                ps.setUserState(user.getIdentifier(),
12361                        COMPONENT_ENABLED_STATE_DEFAULT,
12362                        false, //installed
12363                        true,  //stopped
12364                        true,  //notLaunched
12365                        false, //hidden
12366                        null, null, null,
12367                        false, // blockUninstall
12368                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
12369                if (!isSystemApp(ps)) {
12370                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
12371                        // Other user still have this package installed, so all
12372                        // we need to do is clear this user's data and save that
12373                        // it is uninstalled.
12374                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
12375                        removeUser = user.getIdentifier();
12376                        appId = ps.appId;
12377                        scheduleWritePackageRestrictionsLocked(removeUser);
12378                    } else {
12379                        // We need to set it back to 'installed' so the uninstall
12380                        // broadcasts will be sent correctly.
12381                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
12382                        ps.setInstalled(true, user.getIdentifier());
12383                    }
12384                } else {
12385                    // This is a system app, so we assume that the
12386                    // other users still have this package installed, so all
12387                    // we need to do is clear this user's data and save that
12388                    // it is uninstalled.
12389                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
12390                    removeUser = user.getIdentifier();
12391                    appId = ps.appId;
12392                    scheduleWritePackageRestrictionsLocked(removeUser);
12393                }
12394            }
12395        }
12396
12397        if (removeUser >= 0) {
12398            // From above, we determined that we are deleting this only
12399            // for a single user.  Continue the work here.
12400            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
12401            if (outInfo != null) {
12402                outInfo.removedPackage = packageName;
12403                outInfo.removedAppId = appId;
12404                outInfo.removedUsers = new int[] {removeUser};
12405            }
12406            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
12407            removeKeystoreDataIfNeeded(removeUser, appId);
12408            schedulePackageCleaning(packageName, removeUser, false);
12409            synchronized (mPackages) {
12410                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
12411                    scheduleWritePackageRestrictionsLocked(removeUser);
12412                }
12413            }
12414            return true;
12415        }
12416
12417        if (dataOnly) {
12418            // Delete application data first
12419            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
12420            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
12421            return true;
12422        }
12423
12424        boolean ret = false;
12425        if (isSystemApp(ps)) {
12426            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
12427            // When an updated system application is deleted we delete the existing resources as well and
12428            // fall back to existing code in system partition
12429            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
12430                    flags, outInfo, writeSettings);
12431        } else {
12432            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
12433            // Kill application pre-emptively especially for apps on sd.
12434            killApplication(packageName, ps.appId, "uninstall pkg");
12435            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
12436                    allUserHandles, perUserInstalled,
12437                    outInfo, writeSettings);
12438        }
12439
12440        return ret;
12441    }
12442
12443    private final class ClearStorageConnection implements ServiceConnection {
12444        IMediaContainerService mContainerService;
12445
12446        @Override
12447        public void onServiceConnected(ComponentName name, IBinder service) {
12448            synchronized (this) {
12449                mContainerService = IMediaContainerService.Stub.asInterface(service);
12450                notifyAll();
12451            }
12452        }
12453
12454        @Override
12455        public void onServiceDisconnected(ComponentName name) {
12456        }
12457    }
12458
12459    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
12460        final boolean mounted;
12461        if (Environment.isExternalStorageEmulated()) {
12462            mounted = true;
12463        } else {
12464            final String status = Environment.getExternalStorageState();
12465
12466            mounted = status.equals(Environment.MEDIA_MOUNTED)
12467                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
12468        }
12469
12470        if (!mounted) {
12471            return;
12472        }
12473
12474        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
12475        int[] users;
12476        if (userId == UserHandle.USER_ALL) {
12477            users = sUserManager.getUserIds();
12478        } else {
12479            users = new int[] { userId };
12480        }
12481        final ClearStorageConnection conn = new ClearStorageConnection();
12482        if (mContext.bindServiceAsUser(
12483                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
12484            try {
12485                for (int curUser : users) {
12486                    long timeout = SystemClock.uptimeMillis() + 5000;
12487                    synchronized (conn) {
12488                        long now = SystemClock.uptimeMillis();
12489                        while (conn.mContainerService == null && now < timeout) {
12490                            try {
12491                                conn.wait(timeout - now);
12492                            } catch (InterruptedException e) {
12493                            }
12494                        }
12495                    }
12496                    if (conn.mContainerService == null) {
12497                        return;
12498                    }
12499
12500                    final UserEnvironment userEnv = new UserEnvironment(curUser);
12501                    clearDirectory(conn.mContainerService,
12502                            userEnv.buildExternalStorageAppCacheDirs(packageName));
12503                    if (allData) {
12504                        clearDirectory(conn.mContainerService,
12505                                userEnv.buildExternalStorageAppDataDirs(packageName));
12506                        clearDirectory(conn.mContainerService,
12507                                userEnv.buildExternalStorageAppMediaDirs(packageName));
12508                    }
12509                }
12510            } finally {
12511                mContext.unbindService(conn);
12512            }
12513        }
12514    }
12515
12516    @Override
12517    public void clearApplicationUserData(final String packageName,
12518            final IPackageDataObserver observer, final int userId) {
12519        mContext.enforceCallingOrSelfPermission(
12520                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
12521        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
12522        // Queue up an async operation since the package deletion may take a little while.
12523        mHandler.post(new Runnable() {
12524            public void run() {
12525                mHandler.removeCallbacks(this);
12526                final boolean succeeded;
12527                synchronized (mInstallLock) {
12528                    succeeded = clearApplicationUserDataLI(packageName, userId);
12529                }
12530                clearExternalStorageDataSync(packageName, userId, true);
12531                if (succeeded) {
12532                    // invoke DeviceStorageMonitor's update method to clear any notifications
12533                    DeviceStorageMonitorInternal
12534                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
12535                    if (dsm != null) {
12536                        dsm.checkMemory();
12537                    }
12538                }
12539                if(observer != null) {
12540                    try {
12541                        observer.onRemoveCompleted(packageName, succeeded);
12542                    } catch (RemoteException e) {
12543                        Log.i(TAG, "Observer no longer exists.");
12544                    }
12545                } //end if observer
12546            } //end run
12547        });
12548    }
12549
12550    private boolean clearApplicationUserDataLI(String packageName, int userId) {
12551        if (packageName == null) {
12552            Slog.w(TAG, "Attempt to delete null packageName.");
12553            return false;
12554        }
12555
12556        // Try finding details about the requested package
12557        PackageParser.Package pkg;
12558        synchronized (mPackages) {
12559            pkg = mPackages.get(packageName);
12560            if (pkg == null) {
12561                final PackageSetting ps = mSettings.mPackages.get(packageName);
12562                if (ps != null) {
12563                    pkg = ps.pkg;
12564                }
12565            }
12566        }
12567
12568        if (pkg == null) {
12569            Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12570        }
12571
12572        // Always delete data directories for package, even if we found no other
12573        // record of app. This helps users recover from UID mismatches without
12574        // resorting to a full data wipe.
12575        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
12576        if (retCode < 0) {
12577            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
12578            return false;
12579        }
12580
12581        if (pkg == null) {
12582            return false;
12583        }
12584
12585        if (pkg != null && pkg.applicationInfo != null) {
12586            final int appId = pkg.applicationInfo.uid;
12587            removeKeystoreDataIfNeeded(userId, appId);
12588        }
12589
12590        // Create a native library symlink only if we have native libraries
12591        // and if the native libraries are 32 bit libraries. We do not provide
12592        // this symlink for 64 bit libraries.
12593        if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null &&
12594                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
12595            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
12596            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
12597                    nativeLibPath, userId) < 0) {
12598                Slog.w(TAG, "Failed linking native library dir");
12599                return false;
12600            }
12601        }
12602
12603        return true;
12604    }
12605
12606    /**
12607     * Remove entries from the keystore daemon. Will only remove it if the
12608     * {@code appId} is valid.
12609     */
12610    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
12611        if (appId < 0) {
12612            return;
12613        }
12614
12615        final KeyStore keyStore = KeyStore.getInstance();
12616        if (keyStore != null) {
12617            if (userId == UserHandle.USER_ALL) {
12618                for (final int individual : sUserManager.getUserIds()) {
12619                    keyStore.clearUid(UserHandle.getUid(individual, appId));
12620                }
12621            } else {
12622                keyStore.clearUid(UserHandle.getUid(userId, appId));
12623            }
12624        } else {
12625            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
12626        }
12627    }
12628
12629    @Override
12630    public void deleteApplicationCacheFiles(final String packageName,
12631            final IPackageDataObserver observer) {
12632        mContext.enforceCallingOrSelfPermission(
12633                android.Manifest.permission.DELETE_CACHE_FILES, null);
12634        // Queue up an async operation since the package deletion may take a little while.
12635        final int userId = UserHandle.getCallingUserId();
12636        mHandler.post(new Runnable() {
12637            public void run() {
12638                mHandler.removeCallbacks(this);
12639                final boolean succeded;
12640                synchronized (mInstallLock) {
12641                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
12642                }
12643                clearExternalStorageDataSync(packageName, userId, false);
12644                if (observer != null) {
12645                    try {
12646                        observer.onRemoveCompleted(packageName, succeded);
12647                    } catch (RemoteException e) {
12648                        Log.i(TAG, "Observer no longer exists.");
12649                    }
12650                } //end if observer
12651            } //end run
12652        });
12653    }
12654
12655    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
12656        if (packageName == null) {
12657            Slog.w(TAG, "Attempt to delete null packageName.");
12658            return false;
12659        }
12660        PackageParser.Package p;
12661        synchronized (mPackages) {
12662            p = mPackages.get(packageName);
12663        }
12664        if (p == null) {
12665            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12666            return false;
12667        }
12668        final ApplicationInfo applicationInfo = p.applicationInfo;
12669        if (applicationInfo == null) {
12670            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12671            return false;
12672        }
12673        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
12674        if (retCode < 0) {
12675            Slog.w(TAG, "Couldn't remove cache files for package: "
12676                       + packageName + " u" + userId);
12677            return false;
12678        }
12679        return true;
12680    }
12681
12682    @Override
12683    public void getPackageSizeInfo(final String packageName, int userHandle,
12684            final IPackageStatsObserver observer) {
12685        mContext.enforceCallingOrSelfPermission(
12686                android.Manifest.permission.GET_PACKAGE_SIZE, null);
12687        if (packageName == null) {
12688            throw new IllegalArgumentException("Attempt to get size of null packageName");
12689        }
12690
12691        PackageStats stats = new PackageStats(packageName, userHandle);
12692
12693        /*
12694         * Queue up an async operation since the package measurement may take a
12695         * little while.
12696         */
12697        Message msg = mHandler.obtainMessage(INIT_COPY);
12698        msg.obj = new MeasureParams(stats, observer);
12699        mHandler.sendMessage(msg);
12700    }
12701
12702    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
12703            PackageStats pStats) {
12704        if (packageName == null) {
12705            Slog.w(TAG, "Attempt to get size of null packageName.");
12706            return false;
12707        }
12708        PackageParser.Package p;
12709        boolean dataOnly = false;
12710        String libDirRoot = null;
12711        String asecPath = null;
12712        PackageSetting ps = null;
12713        synchronized (mPackages) {
12714            p = mPackages.get(packageName);
12715            ps = mSettings.mPackages.get(packageName);
12716            if(p == null) {
12717                dataOnly = true;
12718                if((ps == null) || (ps.pkg == null)) {
12719                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12720                    return false;
12721                }
12722                p = ps.pkg;
12723            }
12724            if (ps != null) {
12725                libDirRoot = ps.legacyNativeLibraryPathString;
12726            }
12727            if (p != null && (isExternal(p) || p.isForwardLocked())) {
12728                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
12729                if (secureContainerId != null) {
12730                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
12731                }
12732            }
12733        }
12734        String publicSrcDir = null;
12735        if(!dataOnly) {
12736            final ApplicationInfo applicationInfo = p.applicationInfo;
12737            if (applicationInfo == null) {
12738                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12739                return false;
12740            }
12741            if (p.isForwardLocked()) {
12742                publicSrcDir = applicationInfo.getBaseResourcePath();
12743            }
12744        }
12745        // TODO: extend to measure size of split APKs
12746        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
12747        // not just the first level.
12748        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
12749        // just the primary.
12750        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
12751        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
12752                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
12753        if (res < 0) {
12754            return false;
12755        }
12756
12757        // Fix-up for forward-locked applications in ASEC containers.
12758        if (!isExternal(p)) {
12759            pStats.codeSize += pStats.externalCodeSize;
12760            pStats.externalCodeSize = 0L;
12761        }
12762
12763        return true;
12764    }
12765
12766
12767    @Override
12768    public void addPackageToPreferred(String packageName) {
12769        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
12770    }
12771
12772    @Override
12773    public void removePackageFromPreferred(String packageName) {
12774        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
12775    }
12776
12777    @Override
12778    public List<PackageInfo> getPreferredPackages(int flags) {
12779        return new ArrayList<PackageInfo>();
12780    }
12781
12782    private int getUidTargetSdkVersionLockedLPr(int uid) {
12783        Object obj = mSettings.getUserIdLPr(uid);
12784        if (obj instanceof SharedUserSetting) {
12785            final SharedUserSetting sus = (SharedUserSetting) obj;
12786            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
12787            final Iterator<PackageSetting> it = sus.packages.iterator();
12788            while (it.hasNext()) {
12789                final PackageSetting ps = it.next();
12790                if (ps.pkg != null) {
12791                    int v = ps.pkg.applicationInfo.targetSdkVersion;
12792                    if (v < vers) vers = v;
12793                }
12794            }
12795            return vers;
12796        } else if (obj instanceof PackageSetting) {
12797            final PackageSetting ps = (PackageSetting) obj;
12798            if (ps.pkg != null) {
12799                return ps.pkg.applicationInfo.targetSdkVersion;
12800            }
12801        }
12802        return Build.VERSION_CODES.CUR_DEVELOPMENT;
12803    }
12804
12805    @Override
12806    public void addPreferredActivity(IntentFilter filter, int match,
12807            ComponentName[] set, ComponentName activity, int userId) {
12808        addPreferredActivityInternal(filter, match, set, activity, true, userId,
12809                "Adding preferred");
12810    }
12811
12812    private void addPreferredActivityInternal(IntentFilter filter, int match,
12813            ComponentName[] set, ComponentName activity, boolean always, int userId,
12814            String opname) {
12815        // writer
12816        int callingUid = Binder.getCallingUid();
12817        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
12818        if (filter.countActions() == 0) {
12819            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
12820            return;
12821        }
12822        synchronized (mPackages) {
12823            if (mContext.checkCallingOrSelfPermission(
12824                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12825                    != PackageManager.PERMISSION_GRANTED) {
12826                if (getUidTargetSdkVersionLockedLPr(callingUid)
12827                        < Build.VERSION_CODES.FROYO) {
12828                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
12829                            + callingUid);
12830                    return;
12831                }
12832                mContext.enforceCallingOrSelfPermission(
12833                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12834            }
12835
12836            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
12837            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
12838                    + userId + ":");
12839            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12840            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
12841            scheduleWritePackageRestrictionsLocked(userId);
12842        }
12843    }
12844
12845    @Override
12846    public void replacePreferredActivity(IntentFilter filter, int match,
12847            ComponentName[] set, ComponentName activity, int userId) {
12848        if (filter.countActions() != 1) {
12849            throw new IllegalArgumentException(
12850                    "replacePreferredActivity expects filter to have only 1 action.");
12851        }
12852        if (filter.countDataAuthorities() != 0
12853                || filter.countDataPaths() != 0
12854                || filter.countDataSchemes() > 1
12855                || filter.countDataTypes() != 0) {
12856            throw new IllegalArgumentException(
12857                    "replacePreferredActivity expects filter to have no data authorities, " +
12858                    "paths, or types; and at most one scheme.");
12859        }
12860
12861        final int callingUid = Binder.getCallingUid();
12862        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
12863        synchronized (mPackages) {
12864            if (mContext.checkCallingOrSelfPermission(
12865                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12866                    != PackageManager.PERMISSION_GRANTED) {
12867                if (getUidTargetSdkVersionLockedLPr(callingUid)
12868                        < Build.VERSION_CODES.FROYO) {
12869                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
12870                            + Binder.getCallingUid());
12871                    return;
12872                }
12873                mContext.enforceCallingOrSelfPermission(
12874                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12875            }
12876
12877            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
12878            if (pir != null) {
12879                // Get all of the existing entries that exactly match this filter.
12880                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
12881                if (existing != null && existing.size() == 1) {
12882                    PreferredActivity cur = existing.get(0);
12883                    if (DEBUG_PREFERRED) {
12884                        Slog.i(TAG, "Checking replace of preferred:");
12885                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12886                        if (!cur.mPref.mAlways) {
12887                            Slog.i(TAG, "  -- CUR; not mAlways!");
12888                        } else {
12889                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
12890                            Slog.i(TAG, "  -- CUR: mSet="
12891                                    + Arrays.toString(cur.mPref.mSetComponents));
12892                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
12893                            Slog.i(TAG, "  -- NEW: mMatch="
12894                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
12895                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
12896                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
12897                        }
12898                    }
12899                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
12900                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
12901                            && cur.mPref.sameSet(set)) {
12902                        // Setting the preferred activity to what it happens to be already
12903                        if (DEBUG_PREFERRED) {
12904                            Slog.i(TAG, "Replacing with same preferred activity "
12905                                    + cur.mPref.mShortComponent + " for user "
12906                                    + userId + ":");
12907                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12908                        }
12909                        return;
12910                    }
12911                }
12912
12913                if (existing != null) {
12914                    if (DEBUG_PREFERRED) {
12915                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
12916                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12917                    }
12918                    for (int i = 0; i < existing.size(); i++) {
12919                        PreferredActivity pa = existing.get(i);
12920                        if (DEBUG_PREFERRED) {
12921                            Slog.i(TAG, "Removing existing preferred activity "
12922                                    + pa.mPref.mComponent + ":");
12923                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
12924                        }
12925                        pir.removeFilter(pa);
12926                    }
12927                }
12928            }
12929            addPreferredActivityInternal(filter, match, set, activity, true, userId,
12930                    "Replacing preferred");
12931        }
12932    }
12933
12934    @Override
12935    public void clearPackagePreferredActivities(String packageName) {
12936        final int uid = Binder.getCallingUid();
12937        // writer
12938        synchronized (mPackages) {
12939            PackageParser.Package pkg = mPackages.get(packageName);
12940            if (pkg == null || pkg.applicationInfo.uid != uid) {
12941                if (mContext.checkCallingOrSelfPermission(
12942                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12943                        != PackageManager.PERMISSION_GRANTED) {
12944                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
12945                            < Build.VERSION_CODES.FROYO) {
12946                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
12947                                + Binder.getCallingUid());
12948                        return;
12949                    }
12950                    mContext.enforceCallingOrSelfPermission(
12951                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12952                }
12953            }
12954
12955            int user = UserHandle.getCallingUserId();
12956            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
12957                scheduleWritePackageRestrictionsLocked(user);
12958            }
12959        }
12960    }
12961
12962    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
12963    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
12964        ArrayList<PreferredActivity> removed = null;
12965        boolean changed = false;
12966        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12967            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
12968            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12969            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
12970                continue;
12971            }
12972            Iterator<PreferredActivity> it = pir.filterIterator();
12973            while (it.hasNext()) {
12974                PreferredActivity pa = it.next();
12975                // Mark entry for removal only if it matches the package name
12976                // and the entry is of type "always".
12977                if (packageName == null ||
12978                        (pa.mPref.mComponent.getPackageName().equals(packageName)
12979                                && pa.mPref.mAlways)) {
12980                    if (removed == null) {
12981                        removed = new ArrayList<PreferredActivity>();
12982                    }
12983                    removed.add(pa);
12984                }
12985            }
12986            if (removed != null) {
12987                for (int j=0; j<removed.size(); j++) {
12988                    PreferredActivity pa = removed.get(j);
12989                    pir.removeFilter(pa);
12990                }
12991                changed = true;
12992            }
12993        }
12994        return changed;
12995    }
12996
12997    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
12998    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
12999        if (userId == UserHandle.USER_ALL) {
13000            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13001                    sUserManager.getUserIds())) {
13002                for (int oneUserId : sUserManager.getUserIds()) {
13003                    scheduleWritePackageRestrictionsLocked(oneUserId);
13004                }
13005            }
13006        } else {
13007            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13008                scheduleWritePackageRestrictionsLocked(userId);
13009            }
13010        }
13011    }
13012
13013
13014    void clearDefaultBrowserIfNeeded(String packageName) {
13015        for (int oneUserId : sUserManager.getUserIds()) {
13016            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13017            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13018            if (packageName.equals(defaultBrowserPackageName)) {
13019                setDefaultBrowserPackageName(null, oneUserId);
13020            }
13021        }
13022    }
13023
13024    @Override
13025    public void resetPreferredActivities(int userId) {
13026        /* TODO: Actually use userId. Why is it being passed in? */
13027        mContext.enforceCallingOrSelfPermission(
13028                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13029        // writer
13030        synchronized (mPackages) {
13031            int user = UserHandle.getCallingUserId();
13032            clearPackagePreferredActivitiesLPw(null, user);
13033            mSettings.readDefaultPreferredAppsLPw(this, user);
13034            scheduleWritePackageRestrictionsLocked(user);
13035        }
13036    }
13037
13038    @Override
13039    public int getPreferredActivities(List<IntentFilter> outFilters,
13040            List<ComponentName> outActivities, String packageName) {
13041
13042        int num = 0;
13043        final int userId = UserHandle.getCallingUserId();
13044        // reader
13045        synchronized (mPackages) {
13046            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13047            if (pir != null) {
13048                final Iterator<PreferredActivity> it = pir.filterIterator();
13049                while (it.hasNext()) {
13050                    final PreferredActivity pa = it.next();
13051                    if (packageName == null
13052                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13053                                    && pa.mPref.mAlways)) {
13054                        if (outFilters != null) {
13055                            outFilters.add(new IntentFilter(pa));
13056                        }
13057                        if (outActivities != null) {
13058                            outActivities.add(pa.mPref.mComponent);
13059                        }
13060                    }
13061                }
13062            }
13063        }
13064
13065        return num;
13066    }
13067
13068    @Override
13069    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13070            int userId) {
13071        int callingUid = Binder.getCallingUid();
13072        if (callingUid != Process.SYSTEM_UID) {
13073            throw new SecurityException(
13074                    "addPersistentPreferredActivity can only be run by the system");
13075        }
13076        if (filter.countActions() == 0) {
13077            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13078            return;
13079        }
13080        synchronized (mPackages) {
13081            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13082                    " :");
13083            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13084            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13085                    new PersistentPreferredActivity(filter, activity));
13086            scheduleWritePackageRestrictionsLocked(userId);
13087        }
13088    }
13089
13090    @Override
13091    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13092        int callingUid = Binder.getCallingUid();
13093        if (callingUid != Process.SYSTEM_UID) {
13094            throw new SecurityException(
13095                    "clearPackagePersistentPreferredActivities can only be run by the system");
13096        }
13097        ArrayList<PersistentPreferredActivity> removed = null;
13098        boolean changed = false;
13099        synchronized (mPackages) {
13100            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13101                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13102                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13103                        .valueAt(i);
13104                if (userId != thisUserId) {
13105                    continue;
13106                }
13107                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13108                while (it.hasNext()) {
13109                    PersistentPreferredActivity ppa = it.next();
13110                    // Mark entry for removal only if it matches the package name.
13111                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13112                        if (removed == null) {
13113                            removed = new ArrayList<PersistentPreferredActivity>();
13114                        }
13115                        removed.add(ppa);
13116                    }
13117                }
13118                if (removed != null) {
13119                    for (int j=0; j<removed.size(); j++) {
13120                        PersistentPreferredActivity ppa = removed.get(j);
13121                        ppir.removeFilter(ppa);
13122                    }
13123                    changed = true;
13124                }
13125            }
13126
13127            if (changed) {
13128                scheduleWritePackageRestrictionsLocked(userId);
13129            }
13130        }
13131    }
13132
13133    /**
13134     * Non-Binder method, support for the backup/restore mechanism: write the
13135     * full set of preferred activities in its canonical XML format.  Returns true
13136     * on success; false otherwise.
13137     */
13138    @Override
13139    public byte[] getPreferredActivityBackup(int userId) {
13140        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13141            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13142        }
13143
13144        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13145        try {
13146            final XmlSerializer serializer = new FastXmlSerializer();
13147            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13148            serializer.startDocument(null, true);
13149            serializer.startTag(null, TAG_PREFERRED_BACKUP);
13150
13151            synchronized (mPackages) {
13152                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13153            }
13154
13155            serializer.endTag(null, TAG_PREFERRED_BACKUP);
13156            serializer.endDocument();
13157            serializer.flush();
13158        } catch (Exception e) {
13159            if (DEBUG_BACKUP) {
13160                Slog.e(TAG, "Unable to write preferred activities for backup", e);
13161            }
13162            return null;
13163        }
13164
13165        return dataStream.toByteArray();
13166    }
13167
13168    @Override
13169    public void restorePreferredActivities(byte[] backup, int userId) {
13170        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13171            throw new SecurityException("Only the system may call restorePreferredActivities()");
13172        }
13173
13174        try {
13175            final XmlPullParser parser = Xml.newPullParser();
13176            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13177
13178            int type;
13179            while ((type = parser.next()) != XmlPullParser.START_TAG
13180                    && type != XmlPullParser.END_DOCUMENT) {
13181            }
13182            if (type != XmlPullParser.START_TAG) {
13183                // oops didn't find a start tag?!
13184                if (DEBUG_BACKUP) {
13185                    Slog.e(TAG, "Didn't find start tag during restore");
13186                }
13187                return;
13188            }
13189
13190            // this is supposed to be TAG_PREFERRED_BACKUP
13191            if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) {
13192                if (DEBUG_BACKUP) {
13193                    Slog.e(TAG, "Found unexpected tag " + parser.getName());
13194                }
13195                return;
13196            }
13197
13198            // skip interfering stuff, then we're aligned with the backing implementation
13199            while ((type = parser.next()) == XmlPullParser.TEXT) { }
13200            synchronized (mPackages) {
13201                mSettings.readPreferredActivitiesLPw(parser, userId);
13202            }
13203        } catch (Exception e) {
13204            if (DEBUG_BACKUP) {
13205                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13206            }
13207        }
13208    }
13209
13210    @Override
13211    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
13212            int sourceUserId, int targetUserId, int flags) {
13213        mContext.enforceCallingOrSelfPermission(
13214                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13215        int callingUid = Binder.getCallingUid();
13216        enforceOwnerRights(ownerPackage, callingUid);
13217        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13218        if (intentFilter.countActions() == 0) {
13219            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
13220            return;
13221        }
13222        synchronized (mPackages) {
13223            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
13224                    ownerPackage, targetUserId, flags);
13225            CrossProfileIntentResolver resolver =
13226                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13227            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
13228            // We have all those whose filter is equal. Now checking if the rest is equal as well.
13229            if (existing != null) {
13230                int size = existing.size();
13231                for (int i = 0; i < size; i++) {
13232                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
13233                        return;
13234                    }
13235                }
13236            }
13237            resolver.addFilter(newFilter);
13238            scheduleWritePackageRestrictionsLocked(sourceUserId);
13239        }
13240    }
13241
13242    @Override
13243    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
13244        mContext.enforceCallingOrSelfPermission(
13245                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13246        int callingUid = Binder.getCallingUid();
13247        enforceOwnerRights(ownerPackage, callingUid);
13248        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13249        synchronized (mPackages) {
13250            CrossProfileIntentResolver resolver =
13251                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13252            ArraySet<CrossProfileIntentFilter> set =
13253                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
13254            for (CrossProfileIntentFilter filter : set) {
13255                if (filter.getOwnerPackage().equals(ownerPackage)) {
13256                    resolver.removeFilter(filter);
13257                }
13258            }
13259            scheduleWritePackageRestrictionsLocked(sourceUserId);
13260        }
13261    }
13262
13263    // Enforcing that callingUid is owning pkg on userId
13264    private void enforceOwnerRights(String pkg, int callingUid) {
13265        // The system owns everything.
13266        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
13267            return;
13268        }
13269        int callingUserId = UserHandle.getUserId(callingUid);
13270        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
13271        if (pi == null) {
13272            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
13273                    + callingUserId);
13274        }
13275        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
13276            throw new SecurityException("Calling uid " + callingUid
13277                    + " does not own package " + pkg);
13278        }
13279    }
13280
13281    @Override
13282    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
13283        Intent intent = new Intent(Intent.ACTION_MAIN);
13284        intent.addCategory(Intent.CATEGORY_HOME);
13285
13286        final int callingUserId = UserHandle.getCallingUserId();
13287        List<ResolveInfo> list = queryIntentActivities(intent, null,
13288                PackageManager.GET_META_DATA, callingUserId);
13289        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
13290                true, false, false, callingUserId);
13291
13292        allHomeCandidates.clear();
13293        if (list != null) {
13294            for (ResolveInfo ri : list) {
13295                allHomeCandidates.add(ri);
13296            }
13297        }
13298        return (preferred == null || preferred.activityInfo == null)
13299                ? null
13300                : new ComponentName(preferred.activityInfo.packageName,
13301                        preferred.activityInfo.name);
13302    }
13303
13304    @Override
13305    public void setApplicationEnabledSetting(String appPackageName,
13306            int newState, int flags, int userId, String callingPackage) {
13307        if (!sUserManager.exists(userId)) return;
13308        if (callingPackage == null) {
13309            callingPackage = Integer.toString(Binder.getCallingUid());
13310        }
13311        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
13312    }
13313
13314    @Override
13315    public void setComponentEnabledSetting(ComponentName componentName,
13316            int newState, int flags, int userId) {
13317        if (!sUserManager.exists(userId)) return;
13318        setEnabledSetting(componentName.getPackageName(),
13319                componentName.getClassName(), newState, flags, userId, null);
13320    }
13321
13322    private void setEnabledSetting(final String packageName, String className, int newState,
13323            final int flags, int userId, String callingPackage) {
13324        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
13325              || newState == COMPONENT_ENABLED_STATE_ENABLED
13326              || newState == COMPONENT_ENABLED_STATE_DISABLED
13327              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
13328              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
13329            throw new IllegalArgumentException("Invalid new component state: "
13330                    + newState);
13331        }
13332        PackageSetting pkgSetting;
13333        final int uid = Binder.getCallingUid();
13334        final int permission = mContext.checkCallingOrSelfPermission(
13335                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13336        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
13337        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13338        boolean sendNow = false;
13339        boolean isApp = (className == null);
13340        String componentName = isApp ? packageName : className;
13341        int packageUid = -1;
13342        ArrayList<String> components;
13343
13344        // writer
13345        synchronized (mPackages) {
13346            pkgSetting = mSettings.mPackages.get(packageName);
13347            if (pkgSetting == null) {
13348                if (className == null) {
13349                    throw new IllegalArgumentException(
13350                            "Unknown package: " + packageName);
13351                }
13352                throw new IllegalArgumentException(
13353                        "Unknown component: " + packageName
13354                        + "/" + className);
13355            }
13356            // Allow root and verify that userId is not being specified by a different user
13357            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
13358                throw new SecurityException(
13359                        "Permission Denial: attempt to change component state from pid="
13360                        + Binder.getCallingPid()
13361                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
13362            }
13363            if (className == null) {
13364                // We're dealing with an application/package level state change
13365                if (pkgSetting.getEnabled(userId) == newState) {
13366                    // Nothing to do
13367                    return;
13368                }
13369                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
13370                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
13371                    // Don't care about who enables an app.
13372                    callingPackage = null;
13373                }
13374                pkgSetting.setEnabled(newState, userId, callingPackage);
13375                // pkgSetting.pkg.mSetEnabled = newState;
13376            } else {
13377                // We're dealing with a component level state change
13378                // First, verify that this is a valid class name.
13379                PackageParser.Package pkg = pkgSetting.pkg;
13380                if (pkg == null || !pkg.hasComponentClassName(className)) {
13381                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
13382                        throw new IllegalArgumentException("Component class " + className
13383                                + " does not exist in " + packageName);
13384                    } else {
13385                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
13386                                + className + " does not exist in " + packageName);
13387                    }
13388                }
13389                switch (newState) {
13390                case COMPONENT_ENABLED_STATE_ENABLED:
13391                    if (!pkgSetting.enableComponentLPw(className, userId)) {
13392                        return;
13393                    }
13394                    break;
13395                case COMPONENT_ENABLED_STATE_DISABLED:
13396                    if (!pkgSetting.disableComponentLPw(className, userId)) {
13397                        return;
13398                    }
13399                    break;
13400                case COMPONENT_ENABLED_STATE_DEFAULT:
13401                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
13402                        return;
13403                    }
13404                    break;
13405                default:
13406                    Slog.e(TAG, "Invalid new component state: " + newState);
13407                    return;
13408                }
13409            }
13410            scheduleWritePackageRestrictionsLocked(userId);
13411            components = mPendingBroadcasts.get(userId, packageName);
13412            final boolean newPackage = components == null;
13413            if (newPackage) {
13414                components = new ArrayList<String>();
13415            }
13416            if (!components.contains(componentName)) {
13417                components.add(componentName);
13418            }
13419            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
13420                sendNow = true;
13421                // Purge entry from pending broadcast list if another one exists already
13422                // since we are sending one right away.
13423                mPendingBroadcasts.remove(userId, packageName);
13424            } else {
13425                if (newPackage) {
13426                    mPendingBroadcasts.put(userId, packageName, components);
13427                }
13428                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
13429                    // Schedule a message
13430                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
13431                }
13432            }
13433        }
13434
13435        long callingId = Binder.clearCallingIdentity();
13436        try {
13437            if (sendNow) {
13438                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
13439                sendPackageChangedBroadcast(packageName,
13440                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
13441            }
13442        } finally {
13443            Binder.restoreCallingIdentity(callingId);
13444        }
13445    }
13446
13447    private void sendPackageChangedBroadcast(String packageName,
13448            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
13449        if (DEBUG_INSTALL)
13450            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
13451                    + componentNames);
13452        Bundle extras = new Bundle(4);
13453        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
13454        String nameList[] = new String[componentNames.size()];
13455        componentNames.toArray(nameList);
13456        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
13457        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
13458        extras.putInt(Intent.EXTRA_UID, packageUid);
13459        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
13460                new int[] {UserHandle.getUserId(packageUid)});
13461    }
13462
13463    @Override
13464    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
13465        if (!sUserManager.exists(userId)) return;
13466        final int uid = Binder.getCallingUid();
13467        final int permission = mContext.checkCallingOrSelfPermission(
13468                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13469        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13470        enforceCrossUserPermission(uid, userId, true, true, "stop package");
13471        // writer
13472        synchronized (mPackages) {
13473            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
13474                    allowedByPermission, uid, userId)) {
13475                scheduleWritePackageRestrictionsLocked(userId);
13476            }
13477        }
13478    }
13479
13480    @Override
13481    public String getInstallerPackageName(String packageName) {
13482        // reader
13483        synchronized (mPackages) {
13484            return mSettings.getInstallerPackageNameLPr(packageName);
13485        }
13486    }
13487
13488    @Override
13489    public int getApplicationEnabledSetting(String packageName, int userId) {
13490        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13491        int uid = Binder.getCallingUid();
13492        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
13493        // reader
13494        synchronized (mPackages) {
13495            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
13496        }
13497    }
13498
13499    @Override
13500    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
13501        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13502        int uid = Binder.getCallingUid();
13503        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
13504        // reader
13505        synchronized (mPackages) {
13506            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
13507        }
13508    }
13509
13510    @Override
13511    public void enterSafeMode() {
13512        enforceSystemOrRoot("Only the system can request entering safe mode");
13513
13514        if (!mSystemReady) {
13515            mSafeMode = true;
13516        }
13517    }
13518
13519    @Override
13520    public void systemReady() {
13521        mSystemReady = true;
13522
13523        // Read the compatibilty setting when the system is ready.
13524        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
13525                mContext.getContentResolver(),
13526                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
13527        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
13528        if (DEBUG_SETTINGS) {
13529            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
13530        }
13531
13532        synchronized (mPackages) {
13533            // Verify that all of the preferred activity components actually
13534            // exist.  It is possible for applications to be updated and at
13535            // that point remove a previously declared activity component that
13536            // had been set as a preferred activity.  We try to clean this up
13537            // the next time we encounter that preferred activity, but it is
13538            // possible for the user flow to never be able to return to that
13539            // situation so here we do a sanity check to make sure we haven't
13540            // left any junk around.
13541            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
13542            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13543                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13544                removed.clear();
13545                for (PreferredActivity pa : pir.filterSet()) {
13546                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
13547                        removed.add(pa);
13548                    }
13549                }
13550                if (removed.size() > 0) {
13551                    for (int r=0; r<removed.size(); r++) {
13552                        PreferredActivity pa = removed.get(r);
13553                        Slog.w(TAG, "Removing dangling preferred activity: "
13554                                + pa.mPref.mComponent);
13555                        pir.removeFilter(pa);
13556                    }
13557                    mSettings.writePackageRestrictionsLPr(
13558                            mSettings.mPreferredActivities.keyAt(i));
13559                }
13560            }
13561        }
13562        sUserManager.systemReady();
13563
13564        // Kick off any messages waiting for system ready
13565        if (mPostSystemReadyMessages != null) {
13566            for (Message msg : mPostSystemReadyMessages) {
13567                msg.sendToTarget();
13568            }
13569            mPostSystemReadyMessages = null;
13570        }
13571
13572        // Watch for external volumes that come and go over time
13573        final StorageManager storage = mContext.getSystemService(StorageManager.class);
13574        storage.registerListener(mStorageListener);
13575
13576        mInstallerService.systemReady();
13577        mPackageDexOptimizer.systemReady();
13578    }
13579
13580    @Override
13581    public boolean isSafeMode() {
13582        return mSafeMode;
13583    }
13584
13585    @Override
13586    public boolean hasSystemUidErrors() {
13587        return mHasSystemUidErrors;
13588    }
13589
13590    static String arrayToString(int[] array) {
13591        StringBuffer buf = new StringBuffer(128);
13592        buf.append('[');
13593        if (array != null) {
13594            for (int i=0; i<array.length; i++) {
13595                if (i > 0) buf.append(", ");
13596                buf.append(array[i]);
13597            }
13598        }
13599        buf.append(']');
13600        return buf.toString();
13601    }
13602
13603    static class DumpState {
13604        public static final int DUMP_LIBS = 1 << 0;
13605        public static final int DUMP_FEATURES = 1 << 1;
13606        public static final int DUMP_RESOLVERS = 1 << 2;
13607        public static final int DUMP_PERMISSIONS = 1 << 3;
13608        public static final int DUMP_PACKAGES = 1 << 4;
13609        public static final int DUMP_SHARED_USERS = 1 << 5;
13610        public static final int DUMP_MESSAGES = 1 << 6;
13611        public static final int DUMP_PROVIDERS = 1 << 7;
13612        public static final int DUMP_VERIFIERS = 1 << 8;
13613        public static final int DUMP_PREFERRED = 1 << 9;
13614        public static final int DUMP_PREFERRED_XML = 1 << 10;
13615        public static final int DUMP_KEYSETS = 1 << 11;
13616        public static final int DUMP_VERSION = 1 << 12;
13617        public static final int DUMP_INSTALLS = 1 << 13;
13618        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
13619        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
13620
13621        public static final int OPTION_SHOW_FILTERS = 1 << 0;
13622
13623        private int mTypes;
13624
13625        private int mOptions;
13626
13627        private boolean mTitlePrinted;
13628
13629        private SharedUserSetting mSharedUser;
13630
13631        public boolean isDumping(int type) {
13632            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
13633                return true;
13634            }
13635
13636            return (mTypes & type) != 0;
13637        }
13638
13639        public void setDump(int type) {
13640            mTypes |= type;
13641        }
13642
13643        public boolean isOptionEnabled(int option) {
13644            return (mOptions & option) != 0;
13645        }
13646
13647        public void setOptionEnabled(int option) {
13648            mOptions |= option;
13649        }
13650
13651        public boolean onTitlePrinted() {
13652            final boolean printed = mTitlePrinted;
13653            mTitlePrinted = true;
13654            return printed;
13655        }
13656
13657        public boolean getTitlePrinted() {
13658            return mTitlePrinted;
13659        }
13660
13661        public void setTitlePrinted(boolean enabled) {
13662            mTitlePrinted = enabled;
13663        }
13664
13665        public SharedUserSetting getSharedUser() {
13666            return mSharedUser;
13667        }
13668
13669        public void setSharedUser(SharedUserSetting user) {
13670            mSharedUser = user;
13671        }
13672    }
13673
13674    @Override
13675    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
13676        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
13677                != PackageManager.PERMISSION_GRANTED) {
13678            pw.println("Permission Denial: can't dump ActivityManager from from pid="
13679                    + Binder.getCallingPid()
13680                    + ", uid=" + Binder.getCallingUid()
13681                    + " without permission "
13682                    + android.Manifest.permission.DUMP);
13683            return;
13684        }
13685
13686        DumpState dumpState = new DumpState();
13687        boolean fullPreferred = false;
13688        boolean checkin = false;
13689
13690        String packageName = null;
13691
13692        int opti = 0;
13693        while (opti < args.length) {
13694            String opt = args[opti];
13695            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
13696                break;
13697            }
13698            opti++;
13699
13700            if ("-a".equals(opt)) {
13701                // Right now we only know how to print all.
13702            } else if ("-h".equals(opt)) {
13703                pw.println("Package manager dump options:");
13704                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
13705                pw.println("    --checkin: dump for a checkin");
13706                pw.println("    -f: print details of intent filters");
13707                pw.println("    -h: print this help");
13708                pw.println("  cmd may be one of:");
13709                pw.println("    l[ibraries]: list known shared libraries");
13710                pw.println("    f[ibraries]: list device features");
13711                pw.println("    k[eysets]: print known keysets");
13712                pw.println("    r[esolvers]: dump intent resolvers");
13713                pw.println("    perm[issions]: dump permissions");
13714                pw.println("    pref[erred]: print preferred package settings");
13715                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
13716                pw.println("    prov[iders]: dump content providers");
13717                pw.println("    p[ackages]: dump installed packages");
13718                pw.println("    s[hared-users]: dump shared user IDs");
13719                pw.println("    m[essages]: print collected runtime messages");
13720                pw.println("    v[erifiers]: print package verifier info");
13721                pw.println("    version: print database version info");
13722                pw.println("    write: write current settings now");
13723                pw.println("    <package.name>: info about given package");
13724                pw.println("    installs: details about install sessions");
13725                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
13726                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
13727                return;
13728            } else if ("--checkin".equals(opt)) {
13729                checkin = true;
13730            } else if ("-f".equals(opt)) {
13731                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
13732            } else {
13733                pw.println("Unknown argument: " + opt + "; use -h for help");
13734            }
13735        }
13736
13737        // Is the caller requesting to dump a particular piece of data?
13738        if (opti < args.length) {
13739            String cmd = args[opti];
13740            opti++;
13741            // Is this a package name?
13742            if ("android".equals(cmd) || cmd.contains(".")) {
13743                packageName = cmd;
13744                // When dumping a single package, we always dump all of its
13745                // filter information since the amount of data will be reasonable.
13746                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
13747            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
13748                dumpState.setDump(DumpState.DUMP_LIBS);
13749            } else if ("f".equals(cmd) || "features".equals(cmd)) {
13750                dumpState.setDump(DumpState.DUMP_FEATURES);
13751            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
13752                dumpState.setDump(DumpState.DUMP_RESOLVERS);
13753            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
13754                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
13755            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
13756                dumpState.setDump(DumpState.DUMP_PREFERRED);
13757            } else if ("preferred-xml".equals(cmd)) {
13758                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
13759                if (opti < args.length && "--full".equals(args[opti])) {
13760                    fullPreferred = true;
13761                    opti++;
13762                }
13763            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
13764                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
13765            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
13766                dumpState.setDump(DumpState.DUMP_PACKAGES);
13767            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
13768                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
13769            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
13770                dumpState.setDump(DumpState.DUMP_PROVIDERS);
13771            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
13772                dumpState.setDump(DumpState.DUMP_MESSAGES);
13773            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
13774                dumpState.setDump(DumpState.DUMP_VERIFIERS);
13775            } else if ("i".equals(cmd) || "ifv".equals(cmd)
13776                    || "intent-filter-verifiers".equals(cmd)) {
13777                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
13778            } else if ("version".equals(cmd)) {
13779                dumpState.setDump(DumpState.DUMP_VERSION);
13780            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
13781                dumpState.setDump(DumpState.DUMP_KEYSETS);
13782            } else if ("installs".equals(cmd)) {
13783                dumpState.setDump(DumpState.DUMP_INSTALLS);
13784            } else if ("write".equals(cmd)) {
13785                synchronized (mPackages) {
13786                    mSettings.writeLPr();
13787                    pw.println("Settings written.");
13788                    return;
13789                }
13790            }
13791        }
13792
13793        if (checkin) {
13794            pw.println("vers,1");
13795        }
13796
13797        // reader
13798        synchronized (mPackages) {
13799            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
13800                if (!checkin) {
13801                    if (dumpState.onTitlePrinted())
13802                        pw.println();
13803                    pw.println("Database versions:");
13804                    pw.print("  SDK Version:");
13805                    pw.print(" internal=");
13806                    pw.print(mSettings.mInternalSdkPlatform);
13807                    pw.print(" external=");
13808                    pw.println(mSettings.mExternalSdkPlatform);
13809                    pw.print("  DB Version:");
13810                    pw.print(" internal=");
13811                    pw.print(mSettings.mInternalDatabaseVersion);
13812                    pw.print(" external=");
13813                    pw.println(mSettings.mExternalDatabaseVersion);
13814                }
13815            }
13816
13817            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
13818                if (!checkin) {
13819                    if (dumpState.onTitlePrinted())
13820                        pw.println();
13821                    pw.println("Verifiers:");
13822                    pw.print("  Required: ");
13823                    pw.print(mRequiredVerifierPackage);
13824                    pw.print(" (uid=");
13825                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
13826                    pw.println(")");
13827                } else if (mRequiredVerifierPackage != null) {
13828                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
13829                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
13830                }
13831            }
13832
13833            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
13834                    packageName == null) {
13835                if (mIntentFilterVerifierComponent != null) {
13836                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
13837                    if (!checkin) {
13838                        if (dumpState.onTitlePrinted())
13839                            pw.println();
13840                        pw.println("Intent Filter Verifier:");
13841                        pw.print("  Using: ");
13842                        pw.print(verifierPackageName);
13843                        pw.print(" (uid=");
13844                        pw.print(getPackageUid(verifierPackageName, 0));
13845                        pw.println(")");
13846                    } else if (verifierPackageName != null) {
13847                        pw.print("ifv,"); pw.print(verifierPackageName);
13848                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
13849                    }
13850                } else {
13851                    pw.println();
13852                    pw.println("No Intent Filter Verifier available!");
13853                }
13854            }
13855
13856            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
13857                boolean printedHeader = false;
13858                final Iterator<String> it = mSharedLibraries.keySet().iterator();
13859                while (it.hasNext()) {
13860                    String name = it.next();
13861                    SharedLibraryEntry ent = mSharedLibraries.get(name);
13862                    if (!checkin) {
13863                        if (!printedHeader) {
13864                            if (dumpState.onTitlePrinted())
13865                                pw.println();
13866                            pw.println("Libraries:");
13867                            printedHeader = true;
13868                        }
13869                        pw.print("  ");
13870                    } else {
13871                        pw.print("lib,");
13872                    }
13873                    pw.print(name);
13874                    if (!checkin) {
13875                        pw.print(" -> ");
13876                    }
13877                    if (ent.path != null) {
13878                        if (!checkin) {
13879                            pw.print("(jar) ");
13880                            pw.print(ent.path);
13881                        } else {
13882                            pw.print(",jar,");
13883                            pw.print(ent.path);
13884                        }
13885                    } else {
13886                        if (!checkin) {
13887                            pw.print("(apk) ");
13888                            pw.print(ent.apk);
13889                        } else {
13890                            pw.print(",apk,");
13891                            pw.print(ent.apk);
13892                        }
13893                    }
13894                    pw.println();
13895                }
13896            }
13897
13898            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
13899                if (dumpState.onTitlePrinted())
13900                    pw.println();
13901                if (!checkin) {
13902                    pw.println("Features:");
13903                }
13904                Iterator<String> it = mAvailableFeatures.keySet().iterator();
13905                while (it.hasNext()) {
13906                    String name = it.next();
13907                    if (!checkin) {
13908                        pw.print("  ");
13909                    } else {
13910                        pw.print("feat,");
13911                    }
13912                    pw.println(name);
13913                }
13914            }
13915
13916            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
13917                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
13918                        : "Activity Resolver Table:", "  ", packageName,
13919                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13920                    dumpState.setTitlePrinted(true);
13921                }
13922                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
13923                        : "Receiver Resolver Table:", "  ", packageName,
13924                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13925                    dumpState.setTitlePrinted(true);
13926                }
13927                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
13928                        : "Service Resolver Table:", "  ", packageName,
13929                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13930                    dumpState.setTitlePrinted(true);
13931                }
13932                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
13933                        : "Provider Resolver Table:", "  ", packageName,
13934                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13935                    dumpState.setTitlePrinted(true);
13936                }
13937            }
13938
13939            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
13940                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13941                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13942                    int user = mSettings.mPreferredActivities.keyAt(i);
13943                    if (pir.dump(pw,
13944                            dumpState.getTitlePrinted()
13945                                ? "\nPreferred Activities User " + user + ":"
13946                                : "Preferred Activities User " + user + ":", "  ",
13947                            packageName, true, false)) {
13948                        dumpState.setTitlePrinted(true);
13949                    }
13950                }
13951            }
13952
13953            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
13954                pw.flush();
13955                FileOutputStream fout = new FileOutputStream(fd);
13956                BufferedOutputStream str = new BufferedOutputStream(fout);
13957                XmlSerializer serializer = new FastXmlSerializer();
13958                try {
13959                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
13960                    serializer.startDocument(null, true);
13961                    serializer.setFeature(
13962                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
13963                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
13964                    serializer.endDocument();
13965                    serializer.flush();
13966                } catch (IllegalArgumentException e) {
13967                    pw.println("Failed writing: " + e);
13968                } catch (IllegalStateException e) {
13969                    pw.println("Failed writing: " + e);
13970                } catch (IOException e) {
13971                    pw.println("Failed writing: " + e);
13972                }
13973            }
13974
13975            if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) {
13976                pw.println();
13977                int count = mSettings.mPackages.size();
13978                if (count == 0) {
13979                    pw.println("No domain preferred apps!");
13980                    pw.println();
13981                } else {
13982                    final String prefix = "  ";
13983                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
13984                    if (allPackageSettings.size() == 0) {
13985                        pw.println("No domain preferred apps!");
13986                        pw.println();
13987                    } else {
13988                        pw.println("Domain preferred apps status:");
13989                        pw.println();
13990                        count = 0;
13991                        for (PackageSetting ps : allPackageSettings) {
13992                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
13993                            if (ivi == null || ivi.getPackageName() == null) continue;
13994                            pw.println(prefix + "Package Name: " + ivi.getPackageName());
13995                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
13996                            pw.println(prefix + "Status: " + ivi.getStatusString());
13997                            pw.println();
13998                            count++;
13999                        }
14000                        if (count == 0) {
14001                            pw.println(prefix + "No domain preferred app status!");
14002                            pw.println();
14003                        }
14004                        for (int userId : sUserManager.getUserIds()) {
14005                            pw.println("Domain preferred apps for User " + userId + ":");
14006                            pw.println();
14007                            count = 0;
14008                            for (PackageSetting ps : allPackageSettings) {
14009                                IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14010                                if (ivi == null || ivi.getPackageName() == null) {
14011                                    continue;
14012                                }
14013                                final int status = ps.getDomainVerificationStatusForUser(userId);
14014                                if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
14015                                    continue;
14016                                }
14017                                pw.println(prefix + "Package Name: " + ivi.getPackageName());
14018                                pw.println(prefix + "Domains: " + ivi.getDomainsString());
14019                                String statusStr = IntentFilterVerificationInfo.
14020                                        getStatusStringFromValue(status);
14021                                pw.println(prefix + "Status: " + statusStr);
14022                                pw.println();
14023                                count++;
14024                            }
14025                            if (count == 0) {
14026                                pw.println(prefix + "No domain preferred apps!");
14027                                pw.println();
14028                            }
14029                        }
14030                    }
14031                }
14032            }
14033
14034            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
14035                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
14036                if (packageName == null) {
14037                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
14038                        if (iperm == 0) {
14039                            if (dumpState.onTitlePrinted())
14040                                pw.println();
14041                            pw.println("AppOp Permissions:");
14042                        }
14043                        pw.print("  AppOp Permission ");
14044                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
14045                        pw.println(":");
14046                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
14047                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
14048                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
14049                        }
14050                    }
14051                }
14052            }
14053
14054            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
14055                boolean printedSomething = false;
14056                for (PackageParser.Provider p : mProviders.mProviders.values()) {
14057                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14058                        continue;
14059                    }
14060                    if (!printedSomething) {
14061                        if (dumpState.onTitlePrinted())
14062                            pw.println();
14063                        pw.println("Registered ContentProviders:");
14064                        printedSomething = true;
14065                    }
14066                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
14067                    pw.print("    "); pw.println(p.toString());
14068                }
14069                printedSomething = false;
14070                for (Map.Entry<String, PackageParser.Provider> entry :
14071                        mProvidersByAuthority.entrySet()) {
14072                    PackageParser.Provider p = entry.getValue();
14073                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14074                        continue;
14075                    }
14076                    if (!printedSomething) {
14077                        if (dumpState.onTitlePrinted())
14078                            pw.println();
14079                        pw.println("ContentProvider Authorities:");
14080                        printedSomething = true;
14081                    }
14082                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
14083                    pw.print("    "); pw.println(p.toString());
14084                    if (p.info != null && p.info.applicationInfo != null) {
14085                        final String appInfo = p.info.applicationInfo.toString();
14086                        pw.print("      applicationInfo="); pw.println(appInfo);
14087                    }
14088                }
14089            }
14090
14091            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
14092                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
14093            }
14094
14095            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
14096                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
14097            }
14098
14099            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
14100                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin);
14101            }
14102
14103            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
14104                // XXX should handle packageName != null by dumping only install data that
14105                // the given package is involved with.
14106                if (dumpState.onTitlePrinted()) pw.println();
14107                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
14108            }
14109
14110            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
14111                if (dumpState.onTitlePrinted()) pw.println();
14112                mSettings.dumpReadMessagesLPr(pw, dumpState);
14113
14114                pw.println();
14115                pw.println("Package warning messages:");
14116                BufferedReader in = null;
14117                String line = null;
14118                try {
14119                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14120                    while ((line = in.readLine()) != null) {
14121                        if (line.contains("ignored: updated version")) continue;
14122                        pw.println(line);
14123                    }
14124                } catch (IOException ignored) {
14125                } finally {
14126                    IoUtils.closeQuietly(in);
14127                }
14128            }
14129
14130            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
14131                BufferedReader in = null;
14132                String line = null;
14133                try {
14134                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14135                    while ((line = in.readLine()) != null) {
14136                        if (line.contains("ignored: updated version")) continue;
14137                        pw.print("msg,");
14138                        pw.println(line);
14139                    }
14140                } catch (IOException ignored) {
14141                } finally {
14142                    IoUtils.closeQuietly(in);
14143                }
14144            }
14145        }
14146    }
14147
14148    // ------- apps on sdcard specific code -------
14149    static final boolean DEBUG_SD_INSTALL = false;
14150
14151    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
14152
14153    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
14154
14155    private boolean mMediaMounted = false;
14156
14157    static String getEncryptKey() {
14158        try {
14159            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
14160                    SD_ENCRYPTION_KEYSTORE_NAME);
14161            if (sdEncKey == null) {
14162                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
14163                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
14164                if (sdEncKey == null) {
14165                    Slog.e(TAG, "Failed to create encryption keys");
14166                    return null;
14167                }
14168            }
14169            return sdEncKey;
14170        } catch (NoSuchAlgorithmException nsae) {
14171            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
14172            return null;
14173        } catch (IOException ioe) {
14174            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
14175            return null;
14176        }
14177    }
14178
14179    /*
14180     * Update media status on PackageManager.
14181     */
14182    @Override
14183    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
14184        int callingUid = Binder.getCallingUid();
14185        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
14186            throw new SecurityException("Media status can only be updated by the system");
14187        }
14188        // reader; this apparently protects mMediaMounted, but should probably
14189        // be a different lock in that case.
14190        synchronized (mPackages) {
14191            Log.i(TAG, "Updating external media status from "
14192                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
14193                    + (mediaStatus ? "mounted" : "unmounted"));
14194            if (DEBUG_SD_INSTALL)
14195                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
14196                        + ", mMediaMounted=" + mMediaMounted);
14197            if (mediaStatus == mMediaMounted) {
14198                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
14199                        : 0, -1);
14200                mHandler.sendMessage(msg);
14201                return;
14202            }
14203            mMediaMounted = mediaStatus;
14204        }
14205        // Queue up an async operation since the package installation may take a
14206        // little while.
14207        mHandler.post(new Runnable() {
14208            public void run() {
14209                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
14210            }
14211        });
14212    }
14213
14214    /**
14215     * Called by MountService when the initial ASECs to scan are available.
14216     * Should block until all the ASEC containers are finished being scanned.
14217     */
14218    public void scanAvailableAsecs() {
14219        updateExternalMediaStatusInner(true, false, false);
14220        if (mShouldRestoreconData) {
14221            SELinuxMMAC.setRestoreconDone();
14222            mShouldRestoreconData = false;
14223        }
14224    }
14225
14226    /*
14227     * Collect information of applications on external media, map them against
14228     * existing containers and update information based on current mount status.
14229     * Please note that we always have to report status if reportStatus has been
14230     * set to true especially when unloading packages.
14231     */
14232    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
14233            boolean externalStorage) {
14234        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
14235        int[] uidArr = EmptyArray.INT;
14236
14237        final String[] list = PackageHelper.getSecureContainerList();
14238        if (ArrayUtils.isEmpty(list)) {
14239            Log.i(TAG, "No secure containers found");
14240        } else {
14241            // Process list of secure containers and categorize them
14242            // as active or stale based on their package internal state.
14243
14244            // reader
14245            synchronized (mPackages) {
14246                for (String cid : list) {
14247                    // Leave stages untouched for now; installer service owns them
14248                    if (PackageInstallerService.isStageName(cid)) continue;
14249
14250                    if (DEBUG_SD_INSTALL)
14251                        Log.i(TAG, "Processing container " + cid);
14252                    String pkgName = getAsecPackageName(cid);
14253                    if (pkgName == null) {
14254                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
14255                        continue;
14256                    }
14257                    if (DEBUG_SD_INSTALL)
14258                        Log.i(TAG, "Looking for pkg : " + pkgName);
14259
14260                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
14261                    if (ps == null) {
14262                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
14263                        continue;
14264                    }
14265
14266                    /*
14267                     * Skip packages that are not external if we're unmounting
14268                     * external storage.
14269                     */
14270                    if (externalStorage && !isMounted && !isExternal(ps)) {
14271                        continue;
14272                    }
14273
14274                    final AsecInstallArgs args = new AsecInstallArgs(cid,
14275                            getAppDexInstructionSets(ps), ps.isForwardLocked());
14276                    // The package status is changed only if the code path
14277                    // matches between settings and the container id.
14278                    if (ps.codePathString != null
14279                            && ps.codePathString.startsWith(args.getCodePath())) {
14280                        if (DEBUG_SD_INSTALL) {
14281                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
14282                                    + " at code path: " + ps.codePathString);
14283                        }
14284
14285                        // We do have a valid package installed on sdcard
14286                        processCids.put(args, ps.codePathString);
14287                        final int uid = ps.appId;
14288                        if (uid != -1) {
14289                            uidArr = ArrayUtils.appendInt(uidArr, uid);
14290                        }
14291                    } else {
14292                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
14293                                + ps.codePathString);
14294                    }
14295                }
14296            }
14297
14298            Arrays.sort(uidArr);
14299        }
14300
14301        // Process packages with valid entries.
14302        if (isMounted) {
14303            if (DEBUG_SD_INSTALL)
14304                Log.i(TAG, "Loading packages");
14305            loadMediaPackages(processCids, uidArr);
14306            startCleaningPackages();
14307            mInstallerService.onSecureContainersAvailable();
14308        } else {
14309            if (DEBUG_SD_INSTALL)
14310                Log.i(TAG, "Unloading packages");
14311            unloadMediaPackages(processCids, uidArr, reportStatus);
14312        }
14313    }
14314
14315    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14316            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
14317        final int size = infos.size();
14318        final String[] packageNames = new String[size];
14319        final int[] packageUids = new int[size];
14320        for (int i = 0; i < size; i++) {
14321            final ApplicationInfo info = infos.get(i);
14322            packageNames[i] = info.packageName;
14323            packageUids[i] = info.uid;
14324        }
14325        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
14326                finishedReceiver);
14327    }
14328
14329    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14330            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14331        sendResourcesChangedBroadcast(mediaStatus, replacing,
14332                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
14333    }
14334
14335    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14336            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14337        int size = pkgList.length;
14338        if (size > 0) {
14339            // Send broadcasts here
14340            Bundle extras = new Bundle();
14341            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14342            if (uidArr != null) {
14343                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
14344            }
14345            if (replacing) {
14346                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
14347            }
14348            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
14349                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
14350            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
14351        }
14352    }
14353
14354   /*
14355     * Look at potentially valid container ids from processCids If package
14356     * information doesn't match the one on record or package scanning fails,
14357     * the cid is added to list of removeCids. We currently don't delete stale
14358     * containers.
14359     */
14360    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
14361        ArrayList<String> pkgList = new ArrayList<String>();
14362        Set<AsecInstallArgs> keys = processCids.keySet();
14363
14364        for (AsecInstallArgs args : keys) {
14365            String codePath = processCids.get(args);
14366            if (DEBUG_SD_INSTALL)
14367                Log.i(TAG, "Loading container : " + args.cid);
14368            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14369            try {
14370                // Make sure there are no container errors first.
14371                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
14372                    Slog.e(TAG, "Failed to mount cid : " + args.cid
14373                            + " when installing from sdcard");
14374                    continue;
14375                }
14376                // Check code path here.
14377                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
14378                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
14379                            + " does not match one in settings " + codePath);
14380                    continue;
14381                }
14382                // Parse package
14383                int parseFlags = mDefParseFlags;
14384                if (args.isExternalAsec()) {
14385                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
14386                }
14387                if (args.isFwdLocked()) {
14388                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
14389                }
14390
14391                synchronized (mInstallLock) {
14392                    PackageParser.Package pkg = null;
14393                    try {
14394                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
14395                    } catch (PackageManagerException e) {
14396                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
14397                    }
14398                    // Scan the package
14399                    if (pkg != null) {
14400                        /*
14401                         * TODO why is the lock being held? doPostInstall is
14402                         * called in other places without the lock. This needs
14403                         * to be straightened out.
14404                         */
14405                        // writer
14406                        synchronized (mPackages) {
14407                            retCode = PackageManager.INSTALL_SUCCEEDED;
14408                            pkgList.add(pkg.packageName);
14409                            // Post process args
14410                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
14411                                    pkg.applicationInfo.uid);
14412                        }
14413                    } else {
14414                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
14415                    }
14416                }
14417
14418            } finally {
14419                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
14420                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
14421                }
14422            }
14423        }
14424        // writer
14425        synchronized (mPackages) {
14426            // If the platform SDK has changed since the last time we booted,
14427            // we need to re-grant app permission to catch any new ones that
14428            // appear. This is really a hack, and means that apps can in some
14429            // cases get permissions that the user didn't initially explicitly
14430            // allow... it would be nice to have some better way to handle
14431            // this situation.
14432            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
14433            if (regrantPermissions)
14434                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
14435                        + mSdkVersion + "; regranting permissions for external storage");
14436            mSettings.mExternalSdkPlatform = mSdkVersion;
14437
14438            // Make sure group IDs have been assigned, and any permission
14439            // changes in other apps are accounted for
14440            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
14441                    | (regrantPermissions
14442                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
14443                            : 0));
14444
14445            mSettings.updateExternalDatabaseVersion();
14446
14447            // can downgrade to reader
14448            // Persist settings
14449            mSettings.writeLPr();
14450        }
14451        // Send a broadcast to let everyone know we are done processing
14452        if (pkgList.size() > 0) {
14453            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
14454        }
14455    }
14456
14457   /*
14458     * Utility method to unload a list of specified containers
14459     */
14460    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
14461        // Just unmount all valid containers.
14462        for (AsecInstallArgs arg : cidArgs) {
14463            synchronized (mInstallLock) {
14464                arg.doPostDeleteLI(false);
14465           }
14466       }
14467   }
14468
14469    /*
14470     * Unload packages mounted on external media. This involves deleting package
14471     * data from internal structures, sending broadcasts about diabled packages,
14472     * gc'ing to free up references, unmounting all secure containers
14473     * corresponding to packages on external media, and posting a
14474     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
14475     * that we always have to post this message if status has been requested no
14476     * matter what.
14477     */
14478    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
14479            final boolean reportStatus) {
14480        if (DEBUG_SD_INSTALL)
14481            Log.i(TAG, "unloading media packages");
14482        ArrayList<String> pkgList = new ArrayList<String>();
14483        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
14484        final Set<AsecInstallArgs> keys = processCids.keySet();
14485        for (AsecInstallArgs args : keys) {
14486            String pkgName = args.getPackageName();
14487            if (DEBUG_SD_INSTALL)
14488                Log.i(TAG, "Trying to unload pkg : " + pkgName);
14489            // Delete package internally
14490            PackageRemovedInfo outInfo = new PackageRemovedInfo();
14491            synchronized (mInstallLock) {
14492                boolean res = deletePackageLI(pkgName, null, false, null, null,
14493                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
14494                if (res) {
14495                    pkgList.add(pkgName);
14496                } else {
14497                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
14498                    failedList.add(args);
14499                }
14500            }
14501        }
14502
14503        // reader
14504        synchronized (mPackages) {
14505            // We didn't update the settings after removing each package;
14506            // write them now for all packages.
14507            mSettings.writeLPr();
14508        }
14509
14510        // We have to absolutely send UPDATED_MEDIA_STATUS only
14511        // after confirming that all the receivers processed the ordered
14512        // broadcast when packages get disabled, force a gc to clean things up.
14513        // and unload all the containers.
14514        if (pkgList.size() > 0) {
14515            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
14516                    new IIntentReceiver.Stub() {
14517                public void performReceive(Intent intent, int resultCode, String data,
14518                        Bundle extras, boolean ordered, boolean sticky,
14519                        int sendingUser) throws RemoteException {
14520                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
14521                            reportStatus ? 1 : 0, 1, keys);
14522                    mHandler.sendMessage(msg);
14523                }
14524            });
14525        } else {
14526            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
14527                    keys);
14528            mHandler.sendMessage(msg);
14529        }
14530    }
14531
14532    private void loadPrivatePackages(VolumeInfo vol) {
14533        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
14534        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
14535        synchronized (mInstallLock) {
14536        synchronized (mPackages) {
14537            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14538            for (PackageSetting ps : packages) {
14539                final PackageParser.Package pkg;
14540                try {
14541                    pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null);
14542                    loaded.add(pkg.applicationInfo);
14543                } catch (PackageManagerException e) {
14544                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
14545                }
14546            }
14547
14548            // TODO: regrant any permissions that changed based since original install
14549
14550            mSettings.writeLPr();
14551        }
14552        }
14553
14554        Slog.d(TAG, "Loaded packages " + loaded);
14555        sendResourcesChangedBroadcast(true, false, loaded, null);
14556    }
14557
14558    private void unloadPrivatePackages(VolumeInfo vol) {
14559        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
14560        synchronized (mInstallLock) {
14561        synchronized (mPackages) {
14562            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14563            for (PackageSetting ps : packages) {
14564                if (ps.pkg == null) continue;
14565
14566                final ApplicationInfo info = ps.pkg.applicationInfo;
14567                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
14568                if (deletePackageLI(ps.name, null, false, null, null,
14569                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
14570                    unloaded.add(info);
14571                } else {
14572                    Slog.w(TAG, "Failed to unload " + ps.codePath);
14573                }
14574            }
14575
14576            mSettings.writeLPr();
14577        }
14578        }
14579
14580        Slog.d(TAG, "Unloaded packages " + unloaded);
14581        sendResourcesChangedBroadcast(false, false, unloaded, null);
14582    }
14583
14584    private void unfreezePackage(String packageName) {
14585        synchronized (mPackages) {
14586            final PackageSetting ps = mSettings.mPackages.get(packageName);
14587            if (ps != null) {
14588                ps.frozen = false;
14589            }
14590        }
14591    }
14592
14593    @Override
14594    public int movePackage(final String packageName, final String volumeUuid) {
14595        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
14596
14597        final int moveId = mNextMoveId.getAndIncrement();
14598        try {
14599            movePackageInternal(packageName, volumeUuid, moveId);
14600        } catch (PackageManagerException e) {
14601            Slog.d(TAG, "Failed to move " + packageName, e);
14602            mMoveCallbacks.notifyStatusChanged(moveId,
14603                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
14604        }
14605        return moveId;
14606    }
14607
14608    private void movePackageInternal(final String packageName, final String volumeUuid,
14609            final int moveId) throws PackageManagerException {
14610        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
14611        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14612        final PackageManager pm = mContext.getPackageManager();
14613
14614        final boolean currentAsec;
14615        final String currentVolumeUuid;
14616        final File codeFile;
14617        final String installerPackageName;
14618        final String packageAbiOverride;
14619        final int appId;
14620        final String seinfo;
14621        final String label;
14622
14623        // reader
14624        synchronized (mPackages) {
14625            final PackageParser.Package pkg = mPackages.get(packageName);
14626            final PackageSetting ps = mSettings.mPackages.get(packageName);
14627            if (pkg == null || ps == null) {
14628                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
14629            }
14630
14631            if (pkg.applicationInfo.isSystemApp()) {
14632                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
14633                        "Cannot move system application");
14634            }
14635
14636            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
14637                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14638                        "Package already moved to " + volumeUuid);
14639            }
14640
14641            final File probe = new File(pkg.codePath);
14642            final File probeOat = new File(probe, "oat");
14643            if (!probe.isDirectory() || !probeOat.isDirectory()) {
14644                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14645                        "Move only supported for modern cluster style installs");
14646            }
14647
14648            if (ps.frozen) {
14649                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
14650                        "Failed to move already frozen package");
14651            }
14652            ps.frozen = true;
14653
14654            currentAsec = pkg.applicationInfo.isForwardLocked()
14655                    || pkg.applicationInfo.isExternalAsec();
14656            currentVolumeUuid = ps.volumeUuid;
14657            codeFile = new File(pkg.codePath);
14658            installerPackageName = ps.installerPackageName;
14659            packageAbiOverride = ps.cpuAbiOverrideString;
14660            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
14661            seinfo = pkg.applicationInfo.seinfo;
14662            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
14663        }
14664
14665        // Now that we're guarded by frozen state, kill app during move
14666        killApplication(packageName, appId, "move pkg");
14667
14668        final Bundle extras = new Bundle();
14669        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
14670        extras.putString(Intent.EXTRA_TITLE, label);
14671        mMoveCallbacks.notifyCreated(moveId, extras);
14672
14673        int installFlags;
14674        final boolean moveCompleteApp;
14675        final File measurePath;
14676
14677        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
14678            installFlags = INSTALL_INTERNAL;
14679            moveCompleteApp = !currentAsec;
14680            measurePath = Environment.getDataAppDirectory(volumeUuid);
14681        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
14682            installFlags = INSTALL_EXTERNAL;
14683            moveCompleteApp = false;
14684            measurePath = storage.getPrimaryPhysicalVolume().getPath();
14685        } else {
14686            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
14687            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
14688                    || !volume.isMountedWritable()) {
14689                unfreezePackage(packageName);
14690                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14691                        "Move location not mounted private volume");
14692            }
14693
14694            Preconditions.checkState(!currentAsec);
14695
14696            installFlags = INSTALL_INTERNAL;
14697            moveCompleteApp = true;
14698            measurePath = Environment.getDataAppDirectory(volumeUuid);
14699        }
14700
14701        final PackageStats stats = new PackageStats(null, -1);
14702        synchronized (mInstaller) {
14703            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
14704                unfreezePackage(packageName);
14705                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14706                        "Failed to measure package size");
14707            }
14708        }
14709
14710        Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " + stats.dataSize);
14711
14712        final long startFreeBytes = measurePath.getFreeSpace();
14713        final long sizeBytes;
14714        if (moveCompleteApp) {
14715            sizeBytes = stats.codeSize + stats.dataSize;
14716        } else {
14717            sizeBytes = stats.codeSize;
14718        }
14719
14720        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
14721            unfreezePackage(packageName);
14722            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14723                    "Not enough free space to move");
14724        }
14725
14726        mMoveCallbacks.notifyStatusChanged(moveId, 10);
14727
14728        final CountDownLatch installedLatch = new CountDownLatch(1);
14729        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
14730            @Override
14731            public void onUserActionRequired(Intent intent) throws RemoteException {
14732                throw new IllegalStateException();
14733            }
14734
14735            @Override
14736            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
14737                    Bundle extras) throws RemoteException {
14738                Slog.d(TAG, "Install result for move: "
14739                        + PackageManager.installStatusToString(returnCode, msg));
14740
14741                installedLatch.countDown();
14742
14743                // Regardless of success or failure of the move operation,
14744                // always unfreeze the package
14745                unfreezePackage(packageName);
14746
14747                final int status = PackageManager.installStatusToPublicStatus(returnCode);
14748                switch (status) {
14749                    case PackageInstaller.STATUS_SUCCESS:
14750                        mMoveCallbacks.notifyStatusChanged(moveId,
14751                                PackageManager.MOVE_SUCCEEDED);
14752                        break;
14753                    case PackageInstaller.STATUS_FAILURE_STORAGE:
14754                        mMoveCallbacks.notifyStatusChanged(moveId,
14755                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
14756                        break;
14757                    default:
14758                        mMoveCallbacks.notifyStatusChanged(moveId,
14759                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
14760                        break;
14761                }
14762            }
14763        };
14764
14765        final MoveInfo move;
14766        if (moveCompleteApp) {
14767            // Kick off a thread to report progress estimates
14768            new Thread() {
14769                @Override
14770                public void run() {
14771                    while (true) {
14772                        try {
14773                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
14774                                break;
14775                            }
14776                        } catch (InterruptedException ignored) {
14777                        }
14778
14779                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
14780                        final int progress = 10 + (int) MathUtils.constrain(
14781                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
14782                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
14783                    }
14784                }
14785            }.start();
14786
14787            final String dataAppName = codeFile.getName();
14788            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
14789                    dataAppName, appId, seinfo);
14790        } else {
14791            move = null;
14792        }
14793
14794        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
14795
14796        final Message msg = mHandler.obtainMessage(INIT_COPY);
14797        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
14798        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
14799                installerPackageName, volumeUuid, null, user, packageAbiOverride);
14800        mHandler.sendMessage(msg);
14801    }
14802
14803    @Override
14804    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
14805        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
14806
14807        final int realMoveId = mNextMoveId.getAndIncrement();
14808        final Bundle extras = new Bundle();
14809        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
14810        mMoveCallbacks.notifyCreated(realMoveId, extras);
14811
14812        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
14813            @Override
14814            public void onCreated(int moveId, Bundle extras) {
14815                // Ignored
14816            }
14817
14818            @Override
14819            public void onStatusChanged(int moveId, int status, long estMillis) {
14820                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
14821            }
14822        };
14823
14824        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14825        storage.setPrimaryStorageUuid(volumeUuid, callback);
14826        return realMoveId;
14827    }
14828
14829    @Override
14830    public int getMoveStatus(int moveId) {
14831        mContext.enforceCallingOrSelfPermission(
14832                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
14833        return mMoveCallbacks.mLastStatus.get(moveId);
14834    }
14835
14836    @Override
14837    public void registerMoveCallback(IPackageMoveObserver callback) {
14838        mContext.enforceCallingOrSelfPermission(
14839                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
14840        mMoveCallbacks.register(callback);
14841    }
14842
14843    @Override
14844    public void unregisterMoveCallback(IPackageMoveObserver callback) {
14845        mContext.enforceCallingOrSelfPermission(
14846                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
14847        mMoveCallbacks.unregister(callback);
14848    }
14849
14850    @Override
14851    public boolean setInstallLocation(int loc) {
14852        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
14853                null);
14854        if (getInstallLocation() == loc) {
14855            return true;
14856        }
14857        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
14858                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
14859            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
14860                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
14861            return true;
14862        }
14863        return false;
14864   }
14865
14866    @Override
14867    public int getInstallLocation() {
14868        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14869                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
14870                PackageHelper.APP_INSTALL_AUTO);
14871    }
14872
14873    /** Called by UserManagerService */
14874    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
14875        mDirtyUsers.remove(userHandle);
14876        mSettings.removeUserLPw(userHandle);
14877        mPendingBroadcasts.remove(userHandle);
14878        if (mInstaller != null) {
14879            // Technically, we shouldn't be doing this with the package lock
14880            // held.  However, this is very rare, and there is already so much
14881            // other disk I/O going on, that we'll let it slide for now.
14882            final StorageManager storage = StorageManager.from(mContext);
14883            final List<VolumeInfo> vols = storage.getVolumes();
14884            for (VolumeInfo vol : vols) {
14885                if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) {
14886                    final String volumeUuid = vol.getFsUuid();
14887                    Slog.d(TAG, "Removing user data on volume " + volumeUuid);
14888                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
14889                }
14890            }
14891        }
14892        mUserNeedsBadging.delete(userHandle);
14893        removeUnusedPackagesLILPw(userManager, userHandle);
14894    }
14895
14896    /**
14897     * We're removing userHandle and would like to remove any downloaded packages
14898     * that are no longer in use by any other user.
14899     * @param userHandle the user being removed
14900     */
14901    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
14902        final boolean DEBUG_CLEAN_APKS = false;
14903        int [] users = userManager.getUserIdsLPr();
14904        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
14905        while (psit.hasNext()) {
14906            PackageSetting ps = psit.next();
14907            if (ps.pkg == null) {
14908                continue;
14909            }
14910            final String packageName = ps.pkg.packageName;
14911            // Skip over if system app
14912            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14913                continue;
14914            }
14915            if (DEBUG_CLEAN_APKS) {
14916                Slog.i(TAG, "Checking package " + packageName);
14917            }
14918            boolean keep = false;
14919            for (int i = 0; i < users.length; i++) {
14920                if (users[i] != userHandle && ps.getInstalled(users[i])) {
14921                    keep = true;
14922                    if (DEBUG_CLEAN_APKS) {
14923                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
14924                                + users[i]);
14925                    }
14926                    break;
14927                }
14928            }
14929            if (!keep) {
14930                if (DEBUG_CLEAN_APKS) {
14931                    Slog.i(TAG, "  Removing package " + packageName);
14932                }
14933                mHandler.post(new Runnable() {
14934                    public void run() {
14935                        deletePackageX(packageName, userHandle, 0);
14936                    } //end run
14937                });
14938            }
14939        }
14940    }
14941
14942    /** Called by UserManagerService */
14943    void createNewUserLILPw(int userHandle, File path) {
14944        if (mInstaller != null) {
14945            mInstaller.createUserConfig(userHandle);
14946            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
14947        }
14948    }
14949
14950    void newUserCreatedLILPw(int userHandle) {
14951        // Adding a user requires updating runtime permissions for system apps.
14952        updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
14953    }
14954
14955    @Override
14956    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
14957        mContext.enforceCallingOrSelfPermission(
14958                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14959                "Only package verification agents can read the verifier device identity");
14960
14961        synchronized (mPackages) {
14962            return mSettings.getVerifierDeviceIdentityLPw();
14963        }
14964    }
14965
14966    @Override
14967    public void setPermissionEnforced(String permission, boolean enforced) {
14968        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
14969        if (READ_EXTERNAL_STORAGE.equals(permission)) {
14970            synchronized (mPackages) {
14971                if (mSettings.mReadExternalStorageEnforced == null
14972                        || mSettings.mReadExternalStorageEnforced != enforced) {
14973                    mSettings.mReadExternalStorageEnforced = enforced;
14974                    mSettings.writeLPr();
14975                }
14976            }
14977            // kill any non-foreground processes so we restart them and
14978            // grant/revoke the GID.
14979            final IActivityManager am = ActivityManagerNative.getDefault();
14980            if (am != null) {
14981                final long token = Binder.clearCallingIdentity();
14982                try {
14983                    am.killProcessesBelowForeground("setPermissionEnforcement");
14984                } catch (RemoteException e) {
14985                } finally {
14986                    Binder.restoreCallingIdentity(token);
14987                }
14988            }
14989        } else {
14990            throw new IllegalArgumentException("No selective enforcement for " + permission);
14991        }
14992    }
14993
14994    @Override
14995    @Deprecated
14996    public boolean isPermissionEnforced(String permission) {
14997        return true;
14998    }
14999
15000    @Override
15001    public boolean isStorageLow() {
15002        final long token = Binder.clearCallingIdentity();
15003        try {
15004            final DeviceStorageMonitorInternal
15005                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
15006            if (dsm != null) {
15007                return dsm.isMemoryLow();
15008            } else {
15009                return false;
15010            }
15011        } finally {
15012            Binder.restoreCallingIdentity(token);
15013        }
15014    }
15015
15016    @Override
15017    public IPackageInstaller getPackageInstaller() {
15018        return mInstallerService;
15019    }
15020
15021    private boolean userNeedsBadging(int userId) {
15022        int index = mUserNeedsBadging.indexOfKey(userId);
15023        if (index < 0) {
15024            final UserInfo userInfo;
15025            final long token = Binder.clearCallingIdentity();
15026            try {
15027                userInfo = sUserManager.getUserInfo(userId);
15028            } finally {
15029                Binder.restoreCallingIdentity(token);
15030            }
15031            final boolean b;
15032            if (userInfo != null && userInfo.isManagedProfile()) {
15033                b = true;
15034            } else {
15035                b = false;
15036            }
15037            mUserNeedsBadging.put(userId, b);
15038            return b;
15039        }
15040        return mUserNeedsBadging.valueAt(index);
15041    }
15042
15043    @Override
15044    public KeySet getKeySetByAlias(String packageName, String alias) {
15045        if (packageName == null || alias == null) {
15046            return null;
15047        }
15048        synchronized(mPackages) {
15049            final PackageParser.Package pkg = mPackages.get(packageName);
15050            if (pkg == null) {
15051                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15052                throw new IllegalArgumentException("Unknown package: " + packageName);
15053            }
15054            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15055            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
15056        }
15057    }
15058
15059    @Override
15060    public KeySet getSigningKeySet(String packageName) {
15061        if (packageName == null) {
15062            return null;
15063        }
15064        synchronized(mPackages) {
15065            final PackageParser.Package pkg = mPackages.get(packageName);
15066            if (pkg == null) {
15067                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15068                throw new IllegalArgumentException("Unknown package: " + packageName);
15069            }
15070            if (pkg.applicationInfo.uid != Binder.getCallingUid()
15071                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
15072                throw new SecurityException("May not access signing KeySet of other apps.");
15073            }
15074            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15075            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
15076        }
15077    }
15078
15079    @Override
15080    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
15081        if (packageName == null || ks == null) {
15082            return false;
15083        }
15084        synchronized(mPackages) {
15085            final PackageParser.Package pkg = mPackages.get(packageName);
15086            if (pkg == null) {
15087                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15088                throw new IllegalArgumentException("Unknown package: " + packageName);
15089            }
15090            IBinder ksh = ks.getToken();
15091            if (ksh instanceof KeySetHandle) {
15092                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15093                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
15094            }
15095            return false;
15096        }
15097    }
15098
15099    @Override
15100    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
15101        if (packageName == null || ks == null) {
15102            return false;
15103        }
15104        synchronized(mPackages) {
15105            final PackageParser.Package pkg = mPackages.get(packageName);
15106            if (pkg == null) {
15107                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15108                throw new IllegalArgumentException("Unknown package: " + packageName);
15109            }
15110            IBinder ksh = ks.getToken();
15111            if (ksh instanceof KeySetHandle) {
15112                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15113                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
15114            }
15115            return false;
15116        }
15117    }
15118
15119    public void getUsageStatsIfNoPackageUsageInfo() {
15120        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
15121            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
15122            if (usm == null) {
15123                throw new IllegalStateException("UsageStatsManager must be initialized");
15124            }
15125            long now = System.currentTimeMillis();
15126            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
15127            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
15128                String packageName = entry.getKey();
15129                PackageParser.Package pkg = mPackages.get(packageName);
15130                if (pkg == null) {
15131                    continue;
15132                }
15133                UsageStats usage = entry.getValue();
15134                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
15135                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
15136            }
15137        }
15138    }
15139
15140    /**
15141     * Check and throw if the given before/after packages would be considered a
15142     * downgrade.
15143     */
15144    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
15145            throws PackageManagerException {
15146        if (after.versionCode < before.mVersionCode) {
15147            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15148                    "Update version code " + after.versionCode + " is older than current "
15149                    + before.mVersionCode);
15150        } else if (after.versionCode == before.mVersionCode) {
15151            if (after.baseRevisionCode < before.baseRevisionCode) {
15152                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15153                        "Update base revision code " + after.baseRevisionCode
15154                        + " is older than current " + before.baseRevisionCode);
15155            }
15156
15157            if (!ArrayUtils.isEmpty(after.splitNames)) {
15158                for (int i = 0; i < after.splitNames.length; i++) {
15159                    final String splitName = after.splitNames[i];
15160                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
15161                    if (j != -1) {
15162                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
15163                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15164                                    "Update split " + splitName + " revision code "
15165                                    + after.splitRevisionCodes[i] + " is older than current "
15166                                    + before.splitRevisionCodes[j]);
15167                        }
15168                    }
15169                }
15170            }
15171        }
15172    }
15173
15174    private static class MoveCallbacks extends Handler {
15175        private static final int MSG_CREATED = 1;
15176        private static final int MSG_STATUS_CHANGED = 2;
15177
15178        private final RemoteCallbackList<IPackageMoveObserver>
15179                mCallbacks = new RemoteCallbackList<>();
15180
15181        private final SparseIntArray mLastStatus = new SparseIntArray();
15182
15183        public MoveCallbacks(Looper looper) {
15184            super(looper);
15185        }
15186
15187        public void register(IPackageMoveObserver callback) {
15188            mCallbacks.register(callback);
15189        }
15190
15191        public void unregister(IPackageMoveObserver callback) {
15192            mCallbacks.unregister(callback);
15193        }
15194
15195        @Override
15196        public void handleMessage(Message msg) {
15197            final SomeArgs args = (SomeArgs) msg.obj;
15198            final int n = mCallbacks.beginBroadcast();
15199            for (int i = 0; i < n; i++) {
15200                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
15201                try {
15202                    invokeCallback(callback, msg.what, args);
15203                } catch (RemoteException ignored) {
15204                }
15205            }
15206            mCallbacks.finishBroadcast();
15207            args.recycle();
15208        }
15209
15210        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
15211                throws RemoteException {
15212            switch (what) {
15213                case MSG_CREATED: {
15214                    callback.onCreated(args.argi1, (Bundle) args.arg2);
15215                    break;
15216                }
15217                case MSG_STATUS_CHANGED: {
15218                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
15219                    break;
15220                }
15221            }
15222        }
15223
15224        private void notifyCreated(int moveId, Bundle extras) {
15225            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
15226
15227            final SomeArgs args = SomeArgs.obtain();
15228            args.argi1 = moveId;
15229            args.arg2 = extras;
15230            obtainMessage(MSG_CREATED, args).sendToTarget();
15231        }
15232
15233        private void notifyStatusChanged(int moveId, int status) {
15234            notifyStatusChanged(moveId, status, -1);
15235        }
15236
15237        private void notifyStatusChanged(int moveId, int status, long estMillis) {
15238            Slog.v(TAG, "Move " + moveId + " status " + status);
15239
15240            final SomeArgs args = SomeArgs.obtain();
15241            args.argi1 = moveId;
15242            args.argi2 = status;
15243            args.arg3 = estMillis;
15244            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
15245
15246            synchronized (mLastStatus) {
15247                mLastStatus.put(moveId, status);
15248            }
15249        }
15250    }
15251}
15252