PackageManagerService.java revision 44a2d978d13e2370bdb057c08faede145f937c70
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(), e);
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
6368            // Some system apps still use directory structure for native libraries
6369            // in which case we might end up not detecting abi solely based on apk
6370            // structure. Try to detect abi based on directory structure.
6371            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6372                    pkg.applicationInfo.primaryCpuAbi == null) {
6373                setBundledAppAbisAndRoots(pkg, pkgSetting);
6374                setNativeLibraryPaths(pkg);
6375            }
6376
6377        } else {
6378            if ((scanFlags & SCAN_MOVE) != 0) {
6379                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6380                // but we already have this packages package info in the PackageSetting. We just
6381                // use that and derive the native library path based on the new codepath.
6382                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6383                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6384            }
6385
6386            // Set native library paths again. For moves, the path will be updated based on the
6387            // ABIs we've determined above. For non-moves, the path will be updated based on the
6388            // ABIs we determined during compilation, but the path will depend on the final
6389            // package path (after the rename away from the stage path).
6390            setNativeLibraryPaths(pkg);
6391        }
6392
6393        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6394        final int[] userIds = sUserManager.getUserIds();
6395        synchronized (mInstallLock) {
6396            // Create a native library symlink only if we have native libraries
6397            // and if the native libraries are 32 bit libraries. We do not provide
6398            // this symlink for 64 bit libraries.
6399            if (pkg.applicationInfo.primaryCpuAbi != null &&
6400                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6401                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6402                for (int userId : userIds) {
6403                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6404                            nativeLibPath, userId) < 0) {
6405                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6406                                "Failed linking native library dir (user=" + userId + ")");
6407                    }
6408                }
6409            }
6410        }
6411
6412        // This is a special case for the "system" package, where the ABI is
6413        // dictated by the zygote configuration (and init.rc). We should keep track
6414        // of this ABI so that we can deal with "normal" applications that run under
6415        // the same UID correctly.
6416        if (mPlatformPackage == pkg) {
6417            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6418                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6419        }
6420
6421        // If there's a mismatch between the abi-override in the package setting
6422        // and the abiOverride specified for the install. Warn about this because we
6423        // would've already compiled the app without taking the package setting into
6424        // account.
6425        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
6426            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
6427                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
6428                        " for package: " + pkg.packageName);
6429            }
6430        }
6431
6432        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6433        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6434        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6435
6436        // Copy the derived override back to the parsed package, so that we can
6437        // update the package settings accordingly.
6438        pkg.cpuAbiOverride = cpuAbiOverride;
6439
6440        if (DEBUG_ABI_SELECTION) {
6441            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6442                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6443                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6444        }
6445
6446        // Push the derived path down into PackageSettings so we know what to
6447        // clean up at uninstall time.
6448        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6449
6450        if (DEBUG_ABI_SELECTION) {
6451            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6452                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6453                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6454        }
6455
6456        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6457            // We don't do this here during boot because we can do it all
6458            // at once after scanning all existing packages.
6459            //
6460            // We also do this *before* we perform dexopt on this package, so that
6461            // we can avoid redundant dexopts, and also to make sure we've got the
6462            // code and package path correct.
6463            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
6464                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
6465        }
6466
6467        if ((scanFlags & SCAN_NO_DEX) == 0) {
6468            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
6469                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
6470            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6471                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
6472            }
6473        }
6474        if (mFactoryTest && pkg.requestedPermissions.contains(
6475                android.Manifest.permission.FACTORY_TEST)) {
6476            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
6477        }
6478
6479        ArrayList<PackageParser.Package> clientLibPkgs = null;
6480
6481        // writer
6482        synchronized (mPackages) {
6483            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6484                // Only system apps can add new shared libraries.
6485                if (pkg.libraryNames != null) {
6486                    for (int i=0; i<pkg.libraryNames.size(); i++) {
6487                        String name = pkg.libraryNames.get(i);
6488                        boolean allowed = false;
6489                        if (pkg.isUpdatedSystemApp()) {
6490                            // New library entries can only be added through the
6491                            // system image.  This is important to get rid of a lot
6492                            // of nasty edge cases: for example if we allowed a non-
6493                            // system update of the app to add a library, then uninstalling
6494                            // the update would make the library go away, and assumptions
6495                            // we made such as through app install filtering would now
6496                            // have allowed apps on the device which aren't compatible
6497                            // with it.  Better to just have the restriction here, be
6498                            // conservative, and create many fewer cases that can negatively
6499                            // impact the user experience.
6500                            final PackageSetting sysPs = mSettings
6501                                    .getDisabledSystemPkgLPr(pkg.packageName);
6502                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
6503                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
6504                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
6505                                        allowed = true;
6506                                        allowed = true;
6507                                        break;
6508                                    }
6509                                }
6510                            }
6511                        } else {
6512                            allowed = true;
6513                        }
6514                        if (allowed) {
6515                            if (!mSharedLibraries.containsKey(name)) {
6516                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
6517                            } else if (!name.equals(pkg.packageName)) {
6518                                Slog.w(TAG, "Package " + pkg.packageName + " library "
6519                                        + name + " already exists; skipping");
6520                            }
6521                        } else {
6522                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
6523                                    + name + " that is not declared on system image; skipping");
6524                        }
6525                    }
6526                    if ((scanFlags&SCAN_BOOTING) == 0) {
6527                        // If we are not booting, we need to update any applications
6528                        // that are clients of our shared library.  If we are booting,
6529                        // this will all be done once the scan is complete.
6530                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
6531                    }
6532                }
6533            }
6534        }
6535
6536        // We also need to dexopt any apps that are dependent on this library.  Note that
6537        // if these fail, we should abort the install since installing the library will
6538        // result in some apps being broken.
6539        if (clientLibPkgs != null) {
6540            if ((scanFlags & SCAN_NO_DEX) == 0) {
6541                for (int i = 0; i < clientLibPkgs.size(); i++) {
6542                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
6543                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
6544                            null /* instruction sets */, forceDex,
6545                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
6546                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6547                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
6548                                "scanPackageLI failed to dexopt clientLibPkgs");
6549                    }
6550                }
6551            }
6552        }
6553
6554        // Also need to kill any apps that are dependent on the library.
6555        if (clientLibPkgs != null) {
6556            for (int i=0; i<clientLibPkgs.size(); i++) {
6557                PackageParser.Package clientPkg = clientLibPkgs.get(i);
6558                killApplication(clientPkg.applicationInfo.packageName,
6559                        clientPkg.applicationInfo.uid, "update lib");
6560            }
6561        }
6562
6563        // writer
6564        synchronized (mPackages) {
6565            // We don't expect installation to fail beyond this point
6566
6567            // Add the new setting to mSettings
6568            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
6569            // Add the new setting to mPackages
6570            mPackages.put(pkg.applicationInfo.packageName, pkg);
6571            // Make sure we don't accidentally delete its data.
6572            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
6573            while (iter.hasNext()) {
6574                PackageCleanItem item = iter.next();
6575                if (pkgName.equals(item.packageName)) {
6576                    iter.remove();
6577                }
6578            }
6579
6580            // Take care of first install / last update times.
6581            if (currentTime != 0) {
6582                if (pkgSetting.firstInstallTime == 0) {
6583                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
6584                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
6585                    pkgSetting.lastUpdateTime = currentTime;
6586                }
6587            } else if (pkgSetting.firstInstallTime == 0) {
6588                // We need *something*.  Take time time stamp of the file.
6589                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
6590            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
6591                if (scanFileTime != pkgSetting.timeStamp) {
6592                    // A package on the system image has changed; consider this
6593                    // to be an update.
6594                    pkgSetting.lastUpdateTime = scanFileTime;
6595                }
6596            }
6597
6598            // Add the package's KeySets to the global KeySetManagerService
6599            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6600            try {
6601                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
6602                if (pkg.mKeySetMapping != null) {
6603                    ksms.addDefinedKeySetsToPackageLPw(pkg.packageName, pkg.mKeySetMapping);
6604                    if (pkg.mUpgradeKeySets != null) {
6605                        ksms.addUpgradeKeySetsToPackageLPw(pkg.packageName, pkg.mUpgradeKeySets);
6606                    }
6607                }
6608            } catch (NullPointerException e) {
6609                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
6610            } catch (IllegalArgumentException e) {
6611                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
6612            }
6613
6614            int N = pkg.providers.size();
6615            StringBuilder r = null;
6616            int i;
6617            for (i=0; i<N; i++) {
6618                PackageParser.Provider p = pkg.providers.get(i);
6619                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
6620                        p.info.processName, pkg.applicationInfo.uid);
6621                mProviders.addProvider(p);
6622                p.syncable = p.info.isSyncable;
6623                if (p.info.authority != null) {
6624                    String names[] = p.info.authority.split(";");
6625                    p.info.authority = null;
6626                    for (int j = 0; j < names.length; j++) {
6627                        if (j == 1 && p.syncable) {
6628                            // We only want the first authority for a provider to possibly be
6629                            // syncable, so if we already added this provider using a different
6630                            // authority clear the syncable flag. We copy the provider before
6631                            // changing it because the mProviders object contains a reference
6632                            // to a provider that we don't want to change.
6633                            // Only do this for the second authority since the resulting provider
6634                            // object can be the same for all future authorities for this provider.
6635                            p = new PackageParser.Provider(p);
6636                            p.syncable = false;
6637                        }
6638                        if (!mProvidersByAuthority.containsKey(names[j])) {
6639                            mProvidersByAuthority.put(names[j], p);
6640                            if (p.info.authority == null) {
6641                                p.info.authority = names[j];
6642                            } else {
6643                                p.info.authority = p.info.authority + ";" + names[j];
6644                            }
6645                            if (DEBUG_PACKAGE_SCANNING) {
6646                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6647                                    Log.d(TAG, "Registered content provider: " + names[j]
6648                                            + ", className = " + p.info.name + ", isSyncable = "
6649                                            + p.info.isSyncable);
6650                            }
6651                        } else {
6652                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6653                            Slog.w(TAG, "Skipping provider name " + names[j] +
6654                                    " (in package " + pkg.applicationInfo.packageName +
6655                                    "): name already used by "
6656                                    + ((other != null && other.getComponentName() != null)
6657                                            ? other.getComponentName().getPackageName() : "?"));
6658                        }
6659                    }
6660                }
6661                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6662                    if (r == null) {
6663                        r = new StringBuilder(256);
6664                    } else {
6665                        r.append(' ');
6666                    }
6667                    r.append(p.info.name);
6668                }
6669            }
6670            if (r != null) {
6671                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
6672            }
6673
6674            N = pkg.services.size();
6675            r = null;
6676            for (i=0; i<N; i++) {
6677                PackageParser.Service s = pkg.services.get(i);
6678                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
6679                        s.info.processName, pkg.applicationInfo.uid);
6680                mServices.addService(s);
6681                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6682                    if (r == null) {
6683                        r = new StringBuilder(256);
6684                    } else {
6685                        r.append(' ');
6686                    }
6687                    r.append(s.info.name);
6688                }
6689            }
6690            if (r != null) {
6691                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
6692            }
6693
6694            N = pkg.receivers.size();
6695            r = null;
6696            for (i=0; i<N; i++) {
6697                PackageParser.Activity a = pkg.receivers.get(i);
6698                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6699                        a.info.processName, pkg.applicationInfo.uid);
6700                mReceivers.addActivity(a, "receiver");
6701                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6702                    if (r == null) {
6703                        r = new StringBuilder(256);
6704                    } else {
6705                        r.append(' ');
6706                    }
6707                    r.append(a.info.name);
6708                }
6709            }
6710            if (r != null) {
6711                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
6712            }
6713
6714            N = pkg.activities.size();
6715            r = null;
6716            for (i=0; i<N; i++) {
6717                PackageParser.Activity a = pkg.activities.get(i);
6718                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6719                        a.info.processName, pkg.applicationInfo.uid);
6720                mActivities.addActivity(a, "activity");
6721                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6722                    if (r == null) {
6723                        r = new StringBuilder(256);
6724                    } else {
6725                        r.append(' ');
6726                    }
6727                    r.append(a.info.name);
6728                }
6729            }
6730            if (r != null) {
6731                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
6732            }
6733
6734            N = pkg.permissionGroups.size();
6735            r = null;
6736            for (i=0; i<N; i++) {
6737                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
6738                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
6739                if (cur == null) {
6740                    mPermissionGroups.put(pg.info.name, pg);
6741                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6742                        if (r == null) {
6743                            r = new StringBuilder(256);
6744                        } else {
6745                            r.append(' ');
6746                        }
6747                        r.append(pg.info.name);
6748                    }
6749                } else {
6750                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
6751                            + pg.info.packageName + " ignored: original from "
6752                            + cur.info.packageName);
6753                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6754                        if (r == null) {
6755                            r = new StringBuilder(256);
6756                        } else {
6757                            r.append(' ');
6758                        }
6759                        r.append("DUP:");
6760                        r.append(pg.info.name);
6761                    }
6762                }
6763            }
6764            if (r != null) {
6765                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6766            }
6767
6768            N = pkg.permissions.size();
6769            r = null;
6770            for (i=0; i<N; i++) {
6771                PackageParser.Permission p = pkg.permissions.get(i);
6772
6773                // Now that permission groups have a special meaning, we ignore permission
6774                // groups for legacy apps to prevent unexpected behavior. In particular,
6775                // permissions for one app being granted to someone just becuase they happen
6776                // to be in a group defined by another app (before this had no implications).
6777                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
6778                    p.group = mPermissionGroups.get(p.info.group);
6779                    // Warn for a permission in an unknown group.
6780                    if (p.info.group != null && p.group == null) {
6781                        Slog.w(TAG, "Permission " + p.info.name + " from package "
6782                                + p.info.packageName + " in an unknown group " + p.info.group);
6783                    }
6784                }
6785
6786                ArrayMap<String, BasePermission> permissionMap =
6787                        p.tree ? mSettings.mPermissionTrees
6788                                : mSettings.mPermissions;
6789                BasePermission bp = permissionMap.get(p.info.name);
6790
6791                // Allow system apps to redefine non-system permissions
6792                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
6793                    final boolean currentOwnerIsSystem = (bp.perm != null
6794                            && isSystemApp(bp.perm.owner));
6795                    if (isSystemApp(p.owner)) {
6796                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
6797                            // It's a built-in permission and no owner, take ownership now
6798                            bp.packageSetting = pkgSetting;
6799                            bp.perm = p;
6800                            bp.uid = pkg.applicationInfo.uid;
6801                            bp.sourcePackage = p.info.packageName;
6802                        } else if (!currentOwnerIsSystem) {
6803                            String msg = "New decl " + p.owner + " of permission  "
6804                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
6805                            reportSettingsProblem(Log.WARN, msg);
6806                            bp = null;
6807                        }
6808                    }
6809                }
6810
6811                if (bp == null) {
6812                    bp = new BasePermission(p.info.name, p.info.packageName,
6813                            BasePermission.TYPE_NORMAL);
6814                    permissionMap.put(p.info.name, bp);
6815                }
6816
6817                if (bp.perm == null) {
6818                    if (bp.sourcePackage == null
6819                            || bp.sourcePackage.equals(p.info.packageName)) {
6820                        BasePermission tree = findPermissionTreeLP(p.info.name);
6821                        if (tree == null
6822                                || tree.sourcePackage.equals(p.info.packageName)) {
6823                            bp.packageSetting = pkgSetting;
6824                            bp.perm = p;
6825                            bp.uid = pkg.applicationInfo.uid;
6826                            bp.sourcePackage = p.info.packageName;
6827                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6828                                if (r == null) {
6829                                    r = new StringBuilder(256);
6830                                } else {
6831                                    r.append(' ');
6832                                }
6833                                r.append(p.info.name);
6834                            }
6835                        } else {
6836                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6837                                    + p.info.packageName + " ignored: base tree "
6838                                    + tree.name + " is from package "
6839                                    + tree.sourcePackage);
6840                        }
6841                    } else {
6842                        Slog.w(TAG, "Permission " + p.info.name + " from package "
6843                                + p.info.packageName + " ignored: original from "
6844                                + bp.sourcePackage);
6845                    }
6846                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6847                    if (r == null) {
6848                        r = new StringBuilder(256);
6849                    } else {
6850                        r.append(' ');
6851                    }
6852                    r.append("DUP:");
6853                    r.append(p.info.name);
6854                }
6855                if (bp.perm == p) {
6856                    bp.protectionLevel = p.info.protectionLevel;
6857                }
6858            }
6859
6860            if (r != null) {
6861                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6862            }
6863
6864            N = pkg.instrumentation.size();
6865            r = null;
6866            for (i=0; i<N; i++) {
6867                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6868                a.info.packageName = pkg.applicationInfo.packageName;
6869                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6870                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6871                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6872                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6873                a.info.dataDir = pkg.applicationInfo.dataDir;
6874
6875                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6876                // need other information about the application, like the ABI and what not ?
6877                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6878                mInstrumentation.put(a.getComponentName(), a);
6879                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6880                    if (r == null) {
6881                        r = new StringBuilder(256);
6882                    } else {
6883                        r.append(' ');
6884                    }
6885                    r.append(a.info.name);
6886                }
6887            }
6888            if (r != null) {
6889                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6890            }
6891
6892            if (pkg.protectedBroadcasts != null) {
6893                N = pkg.protectedBroadcasts.size();
6894                for (i=0; i<N; i++) {
6895                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6896                }
6897            }
6898
6899            pkgSetting.setTimeStamp(scanFileTime);
6900
6901            // Create idmap files for pairs of (packages, overlay packages).
6902            // Note: "android", ie framework-res.apk, is handled by native layers.
6903            if (pkg.mOverlayTarget != null) {
6904                // This is an overlay package.
6905                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6906                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6907                        mOverlays.put(pkg.mOverlayTarget,
6908                                new ArrayMap<String, PackageParser.Package>());
6909                    }
6910                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6911                    map.put(pkg.packageName, pkg);
6912                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6913                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6914                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6915                                "scanPackageLI failed to createIdmap");
6916                    }
6917                }
6918            } else if (mOverlays.containsKey(pkg.packageName) &&
6919                    !pkg.packageName.equals("android")) {
6920                // This is a regular package, with one or more known overlay packages.
6921                createIdmapsForPackageLI(pkg);
6922            }
6923        }
6924
6925        return pkg;
6926    }
6927
6928    /**
6929     * Derive the ABI of a non-system package located at {@code scanFile}. This information
6930     * is derived purely on the basis of the contents of {@code scanFile} and
6931     * {@code cpuAbiOverride}.
6932     *
6933     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
6934     */
6935    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
6936                                 String cpuAbiOverride, boolean extractLibs)
6937            throws PackageManagerException {
6938        // TODO: We can probably be smarter about this stuff. For installed apps,
6939        // we can calculate this information at install time once and for all. For
6940        // system apps, we can probably assume that this information doesn't change
6941        // after the first boot scan. As things stand, we do lots of unnecessary work.
6942
6943        // Give ourselves some initial paths; we'll come back for another
6944        // pass once we've determined ABI below.
6945        setNativeLibraryPaths(pkg);
6946
6947        // We would never need to extract libs for forward-locked and external packages,
6948        // since the container service will do it for us. We shouldn't attempt to
6949        // extract libs from system app when it was not updated.
6950        if (pkg.isForwardLocked() || isExternal(pkg) ||
6951            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
6952            extractLibs = false;
6953        }
6954
6955        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
6956        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
6957
6958        NativeLibraryHelper.Handle handle = null;
6959        try {
6960            handle = NativeLibraryHelper.Handle.create(scanFile);
6961            // TODO(multiArch): This can be null for apps that didn't go through the
6962            // usual installation process. We can calculate it again, like we
6963            // do during install time.
6964            //
6965            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
6966            // unnecessary.
6967            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
6968
6969            // Null out the abis so that they can be recalculated.
6970            pkg.applicationInfo.primaryCpuAbi = null;
6971            pkg.applicationInfo.secondaryCpuAbi = null;
6972            if (isMultiArch(pkg.applicationInfo)) {
6973                // Warn if we've set an abiOverride for multi-lib packages..
6974                // By definition, we need to copy both 32 and 64 bit libraries for
6975                // such packages.
6976                if (pkg.cpuAbiOverride != null
6977                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
6978                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
6979                }
6980
6981                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
6982                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
6983                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
6984                    if (extractLibs) {
6985                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
6986                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
6987                                useIsaSpecificSubdirs);
6988                    } else {
6989                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
6990                    }
6991                }
6992
6993                maybeThrowExceptionForMultiArchCopy(
6994                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
6995
6996                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
6997                    if (extractLibs) {
6998                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
6999                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7000                                useIsaSpecificSubdirs);
7001                    } else {
7002                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7003                    }
7004                }
7005
7006                maybeThrowExceptionForMultiArchCopy(
7007                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7008
7009                if (abi64 >= 0) {
7010                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7011                }
7012
7013                if (abi32 >= 0) {
7014                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7015                    if (abi64 >= 0) {
7016                        pkg.applicationInfo.secondaryCpuAbi = abi;
7017                    } else {
7018                        pkg.applicationInfo.primaryCpuAbi = abi;
7019                    }
7020                }
7021            } else {
7022                String[] abiList = (cpuAbiOverride != null) ?
7023                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7024
7025                // Enable gross and lame hacks for apps that are built with old
7026                // SDK tools. We must scan their APKs for renderscript bitcode and
7027                // not launch them if it's present. Don't bother checking on devices
7028                // that don't have 64 bit support.
7029                boolean needsRenderScriptOverride = false;
7030                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7031                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7032                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7033                    needsRenderScriptOverride = true;
7034                }
7035
7036                final int copyRet;
7037                if (extractLibs) {
7038                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7039                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7040                } else {
7041                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7042                }
7043
7044                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7045                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7046                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7047                }
7048
7049                if (copyRet >= 0) {
7050                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7051                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7052                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7053                } else if (needsRenderScriptOverride) {
7054                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7055                }
7056            }
7057        } catch (IOException ioe) {
7058            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7059        } finally {
7060            IoUtils.closeQuietly(handle);
7061        }
7062
7063        // Now that we've calculated the ABIs and determined if it's an internal app,
7064        // we will go ahead and populate the nativeLibraryPath.
7065        setNativeLibraryPaths(pkg);
7066    }
7067
7068    /**
7069     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7070     * i.e, so that all packages can be run inside a single process if required.
7071     *
7072     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7073     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7074     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7075     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7076     * updating a package that belongs to a shared user.
7077     *
7078     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7079     * adds unnecessary complexity.
7080     */
7081    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7082            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7083        String requiredInstructionSet = null;
7084        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7085            requiredInstructionSet = VMRuntime.getInstructionSet(
7086                     scannedPackage.applicationInfo.primaryCpuAbi);
7087        }
7088
7089        PackageSetting requirer = null;
7090        for (PackageSetting ps : packagesForUser) {
7091            // If packagesForUser contains scannedPackage, we skip it. This will happen
7092            // when scannedPackage is an update of an existing package. Without this check,
7093            // we will never be able to change the ABI of any package belonging to a shared
7094            // user, even if it's compatible with other packages.
7095            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7096                if (ps.primaryCpuAbiString == null) {
7097                    continue;
7098                }
7099
7100                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7101                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7102                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7103                    // this but there's not much we can do.
7104                    String errorMessage = "Instruction set mismatch, "
7105                            + ((requirer == null) ? "[caller]" : requirer)
7106                            + " requires " + requiredInstructionSet + " whereas " + ps
7107                            + " requires " + instructionSet;
7108                    Slog.w(TAG, errorMessage);
7109                }
7110
7111                if (requiredInstructionSet == null) {
7112                    requiredInstructionSet = instructionSet;
7113                    requirer = ps;
7114                }
7115            }
7116        }
7117
7118        if (requiredInstructionSet != null) {
7119            String adjustedAbi;
7120            if (requirer != null) {
7121                // requirer != null implies that either scannedPackage was null or that scannedPackage
7122                // did not require an ABI, in which case we have to adjust scannedPackage to match
7123                // the ABI of the set (which is the same as requirer's ABI)
7124                adjustedAbi = requirer.primaryCpuAbiString;
7125                if (scannedPackage != null) {
7126                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7127                }
7128            } else {
7129                // requirer == null implies that we're updating all ABIs in the set to
7130                // match scannedPackage.
7131                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7132            }
7133
7134            for (PackageSetting ps : packagesForUser) {
7135                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7136                    if (ps.primaryCpuAbiString != null) {
7137                        continue;
7138                    }
7139
7140                    ps.primaryCpuAbiString = adjustedAbi;
7141                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7142                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7143                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7144
7145                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7146                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7147                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7148                            ps.primaryCpuAbiString = null;
7149                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7150                            return;
7151                        } else {
7152                            mInstaller.rmdex(ps.codePathString,
7153                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7154                        }
7155                    }
7156                }
7157            }
7158        }
7159    }
7160
7161    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7162        synchronized (mPackages) {
7163            mResolverReplaced = true;
7164            // Set up information for custom user intent resolution activity.
7165            mResolveActivity.applicationInfo = pkg.applicationInfo;
7166            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7167            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7168            mResolveActivity.processName = pkg.applicationInfo.packageName;
7169            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7170            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7171                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7172            mResolveActivity.theme = 0;
7173            mResolveActivity.exported = true;
7174            mResolveActivity.enabled = true;
7175            mResolveInfo.activityInfo = mResolveActivity;
7176            mResolveInfo.priority = 0;
7177            mResolveInfo.preferredOrder = 0;
7178            mResolveInfo.match = 0;
7179            mResolveComponentName = mCustomResolverComponentName;
7180            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7181                    mResolveComponentName);
7182        }
7183    }
7184
7185    private static String calculateBundledApkRoot(final String codePathString) {
7186        final File codePath = new File(codePathString);
7187        final File codeRoot;
7188        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7189            codeRoot = Environment.getRootDirectory();
7190        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7191            codeRoot = Environment.getOemDirectory();
7192        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7193            codeRoot = Environment.getVendorDirectory();
7194        } else {
7195            // Unrecognized code path; take its top real segment as the apk root:
7196            // e.g. /something/app/blah.apk => /something
7197            try {
7198                File f = codePath.getCanonicalFile();
7199                File parent = f.getParentFile();    // non-null because codePath is a file
7200                File tmp;
7201                while ((tmp = parent.getParentFile()) != null) {
7202                    f = parent;
7203                    parent = tmp;
7204                }
7205                codeRoot = f;
7206                Slog.w(TAG, "Unrecognized code path "
7207                        + codePath + " - using " + codeRoot);
7208            } catch (IOException e) {
7209                // Can't canonicalize the code path -- shenanigans?
7210                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7211                return Environment.getRootDirectory().getPath();
7212            }
7213        }
7214        return codeRoot.getPath();
7215    }
7216
7217    /**
7218     * Derive and set the location of native libraries for the given package,
7219     * which varies depending on where and how the package was installed.
7220     */
7221    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7222        final ApplicationInfo info = pkg.applicationInfo;
7223        final String codePath = pkg.codePath;
7224        final File codeFile = new File(codePath);
7225        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7226        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7227
7228        info.nativeLibraryRootDir = null;
7229        info.nativeLibraryRootRequiresIsa = false;
7230        info.nativeLibraryDir = null;
7231        info.secondaryNativeLibraryDir = null;
7232
7233        if (isApkFile(codeFile)) {
7234            // Monolithic install
7235            if (bundledApp) {
7236                // If "/system/lib64/apkname" exists, assume that is the per-package
7237                // native library directory to use; otherwise use "/system/lib/apkname".
7238                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7239                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7240                        getPrimaryInstructionSet(info));
7241
7242                // This is a bundled system app so choose the path based on the ABI.
7243                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7244                // is just the default path.
7245                final String apkName = deriveCodePathName(codePath);
7246                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7247                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7248                        apkName).getAbsolutePath();
7249
7250                if (info.secondaryCpuAbi != null) {
7251                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7252                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7253                            secondaryLibDir, apkName).getAbsolutePath();
7254                }
7255            } else if (asecApp) {
7256                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7257                        .getAbsolutePath();
7258            } else {
7259                final String apkName = deriveCodePathName(codePath);
7260                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7261                        .getAbsolutePath();
7262            }
7263
7264            info.nativeLibraryRootRequiresIsa = false;
7265            info.nativeLibraryDir = info.nativeLibraryRootDir;
7266        } else {
7267            // Cluster install
7268            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7269            info.nativeLibraryRootRequiresIsa = true;
7270
7271            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7272                    getPrimaryInstructionSet(info)).getAbsolutePath();
7273
7274            if (info.secondaryCpuAbi != null) {
7275                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7276                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7277            }
7278        }
7279    }
7280
7281    /**
7282     * Calculate the abis and roots for a bundled app. These can uniquely
7283     * be determined from the contents of the system partition, i.e whether
7284     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7285     * of this information, and instead assume that the system was built
7286     * sensibly.
7287     */
7288    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7289                                           PackageSetting pkgSetting) {
7290        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7291
7292        // If "/system/lib64/apkname" exists, assume that is the per-package
7293        // native library directory to use; otherwise use "/system/lib/apkname".
7294        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7295        setBundledAppAbi(pkg, apkRoot, apkName);
7296        // pkgSetting might be null during rescan following uninstall of updates
7297        // to a bundled app, so accommodate that possibility.  The settings in
7298        // that case will be established later from the parsed package.
7299        //
7300        // If the settings aren't null, sync them up with what we've just derived.
7301        // note that apkRoot isn't stored in the package settings.
7302        if (pkgSetting != null) {
7303            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7304            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7305        }
7306    }
7307
7308    /**
7309     * Deduces the ABI of a bundled app and sets the relevant fields on the
7310     * parsed pkg object.
7311     *
7312     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7313     *        under which system libraries are installed.
7314     * @param apkName the name of the installed package.
7315     */
7316    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7317        final File codeFile = new File(pkg.codePath);
7318
7319        final boolean has64BitLibs;
7320        final boolean has32BitLibs;
7321        if (isApkFile(codeFile)) {
7322            // Monolithic install
7323            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7324            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7325        } else {
7326            // Cluster install
7327            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7328            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7329                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7330                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7331                has64BitLibs = (new File(rootDir, isa)).exists();
7332            } else {
7333                has64BitLibs = false;
7334            }
7335            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7336                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7337                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7338                has32BitLibs = (new File(rootDir, isa)).exists();
7339            } else {
7340                has32BitLibs = false;
7341            }
7342        }
7343
7344        if (has64BitLibs && !has32BitLibs) {
7345            // The package has 64 bit libs, but not 32 bit libs. Its primary
7346            // ABI should be 64 bit. We can safely assume here that the bundled
7347            // native libraries correspond to the most preferred ABI in the list.
7348
7349            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7350            pkg.applicationInfo.secondaryCpuAbi = null;
7351        } else if (has32BitLibs && !has64BitLibs) {
7352            // The package has 32 bit libs but not 64 bit libs. Its primary
7353            // ABI should be 32 bit.
7354
7355            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7356            pkg.applicationInfo.secondaryCpuAbi = null;
7357        } else if (has32BitLibs && has64BitLibs) {
7358            // The application has both 64 and 32 bit bundled libraries. We check
7359            // here that the app declares multiArch support, and warn if it doesn't.
7360            //
7361            // We will be lenient here and record both ABIs. The primary will be the
7362            // ABI that's higher on the list, i.e, a device that's configured to prefer
7363            // 64 bit apps will see a 64 bit primary ABI,
7364
7365            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7366                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7367            }
7368
7369            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7370                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7371                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7372            } else {
7373                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7374                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7375            }
7376        } else {
7377            pkg.applicationInfo.primaryCpuAbi = null;
7378            pkg.applicationInfo.secondaryCpuAbi = null;
7379        }
7380    }
7381
7382    private void killApplication(String pkgName, int appId, String reason) {
7383        // Request the ActivityManager to kill the process(only for existing packages)
7384        // so that we do not end up in a confused state while the user is still using the older
7385        // version of the application while the new one gets installed.
7386        IActivityManager am = ActivityManagerNative.getDefault();
7387        if (am != null) {
7388            try {
7389                am.killApplicationWithAppId(pkgName, appId, reason);
7390            } catch (RemoteException e) {
7391            }
7392        }
7393    }
7394
7395    void removePackageLI(PackageSetting ps, boolean chatty) {
7396        if (DEBUG_INSTALL) {
7397            if (chatty)
7398                Log.d(TAG, "Removing package " + ps.name);
7399        }
7400
7401        // writer
7402        synchronized (mPackages) {
7403            mPackages.remove(ps.name);
7404            final PackageParser.Package pkg = ps.pkg;
7405            if (pkg != null) {
7406                cleanPackageDataStructuresLILPw(pkg, chatty);
7407            }
7408        }
7409    }
7410
7411    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7412        if (DEBUG_INSTALL) {
7413            if (chatty)
7414                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7415        }
7416
7417        // writer
7418        synchronized (mPackages) {
7419            mPackages.remove(pkg.applicationInfo.packageName);
7420            cleanPackageDataStructuresLILPw(pkg, chatty);
7421        }
7422    }
7423
7424    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7425        int N = pkg.providers.size();
7426        StringBuilder r = null;
7427        int i;
7428        for (i=0; i<N; i++) {
7429            PackageParser.Provider p = pkg.providers.get(i);
7430            mProviders.removeProvider(p);
7431            if (p.info.authority == null) {
7432
7433                /* There was another ContentProvider with this authority when
7434                 * this app was installed so this authority is null,
7435                 * Ignore it as we don't have to unregister the provider.
7436                 */
7437                continue;
7438            }
7439            String names[] = p.info.authority.split(";");
7440            for (int j = 0; j < names.length; j++) {
7441                if (mProvidersByAuthority.get(names[j]) == p) {
7442                    mProvidersByAuthority.remove(names[j]);
7443                    if (DEBUG_REMOVE) {
7444                        if (chatty)
7445                            Log.d(TAG, "Unregistered content provider: " + names[j]
7446                                    + ", className = " + p.info.name + ", isSyncable = "
7447                                    + p.info.isSyncable);
7448                    }
7449                }
7450            }
7451            if (DEBUG_REMOVE && chatty) {
7452                if (r == null) {
7453                    r = new StringBuilder(256);
7454                } else {
7455                    r.append(' ');
7456                }
7457                r.append(p.info.name);
7458            }
7459        }
7460        if (r != null) {
7461            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7462        }
7463
7464        N = pkg.services.size();
7465        r = null;
7466        for (i=0; i<N; i++) {
7467            PackageParser.Service s = pkg.services.get(i);
7468            mServices.removeService(s);
7469            if (chatty) {
7470                if (r == null) {
7471                    r = new StringBuilder(256);
7472                } else {
7473                    r.append(' ');
7474                }
7475                r.append(s.info.name);
7476            }
7477        }
7478        if (r != null) {
7479            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
7480        }
7481
7482        N = pkg.receivers.size();
7483        r = null;
7484        for (i=0; i<N; i++) {
7485            PackageParser.Activity a = pkg.receivers.get(i);
7486            mReceivers.removeActivity(a, "receiver");
7487            if (DEBUG_REMOVE && chatty) {
7488                if (r == null) {
7489                    r = new StringBuilder(256);
7490                } else {
7491                    r.append(' ');
7492                }
7493                r.append(a.info.name);
7494            }
7495        }
7496        if (r != null) {
7497            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
7498        }
7499
7500        N = pkg.activities.size();
7501        r = null;
7502        for (i=0; i<N; i++) {
7503            PackageParser.Activity a = pkg.activities.get(i);
7504            mActivities.removeActivity(a, "activity");
7505            if (DEBUG_REMOVE && chatty) {
7506                if (r == null) {
7507                    r = new StringBuilder(256);
7508                } else {
7509                    r.append(' ');
7510                }
7511                r.append(a.info.name);
7512            }
7513        }
7514        if (r != null) {
7515            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
7516        }
7517
7518        N = pkg.permissions.size();
7519        r = null;
7520        for (i=0; i<N; i++) {
7521            PackageParser.Permission p = pkg.permissions.get(i);
7522            BasePermission bp = mSettings.mPermissions.get(p.info.name);
7523            if (bp == null) {
7524                bp = mSettings.mPermissionTrees.get(p.info.name);
7525            }
7526            if (bp != null && bp.perm == p) {
7527                bp.perm = null;
7528                if (DEBUG_REMOVE && chatty) {
7529                    if (r == null) {
7530                        r = new StringBuilder(256);
7531                    } else {
7532                        r.append(' ');
7533                    }
7534                    r.append(p.info.name);
7535                }
7536            }
7537            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7538                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
7539                if (appOpPerms != null) {
7540                    appOpPerms.remove(pkg.packageName);
7541                }
7542            }
7543        }
7544        if (r != null) {
7545            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7546        }
7547
7548        N = pkg.requestedPermissions.size();
7549        r = null;
7550        for (i=0; i<N; i++) {
7551            String perm = pkg.requestedPermissions.get(i);
7552            BasePermission bp = mSettings.mPermissions.get(perm);
7553            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7554                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
7555                if (appOpPerms != null) {
7556                    appOpPerms.remove(pkg.packageName);
7557                    if (appOpPerms.isEmpty()) {
7558                        mAppOpPermissionPackages.remove(perm);
7559                    }
7560                }
7561            }
7562        }
7563        if (r != null) {
7564            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7565        }
7566
7567        N = pkg.instrumentation.size();
7568        r = null;
7569        for (i=0; i<N; i++) {
7570            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7571            mInstrumentation.remove(a.getComponentName());
7572            if (DEBUG_REMOVE && chatty) {
7573                if (r == null) {
7574                    r = new StringBuilder(256);
7575                } else {
7576                    r.append(' ');
7577                }
7578                r.append(a.info.name);
7579            }
7580        }
7581        if (r != null) {
7582            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
7583        }
7584
7585        r = null;
7586        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7587            // Only system apps can hold shared libraries.
7588            if (pkg.libraryNames != null) {
7589                for (i=0; i<pkg.libraryNames.size(); i++) {
7590                    String name = pkg.libraryNames.get(i);
7591                    SharedLibraryEntry cur = mSharedLibraries.get(name);
7592                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
7593                        mSharedLibraries.remove(name);
7594                        if (DEBUG_REMOVE && chatty) {
7595                            if (r == null) {
7596                                r = new StringBuilder(256);
7597                            } else {
7598                                r.append(' ');
7599                            }
7600                            r.append(name);
7601                        }
7602                    }
7603                }
7604            }
7605        }
7606        if (r != null) {
7607            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
7608        }
7609    }
7610
7611    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
7612        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
7613            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
7614                return true;
7615            }
7616        }
7617        return false;
7618    }
7619
7620    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
7621    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
7622    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
7623
7624    private void updatePermissionsLPw(String changingPkg,
7625            PackageParser.Package pkgInfo, int flags) {
7626        // Make sure there are no dangling permission trees.
7627        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
7628        while (it.hasNext()) {
7629            final BasePermission bp = it.next();
7630            if (bp.packageSetting == null) {
7631                // We may not yet have parsed the package, so just see if
7632                // we still know about its settings.
7633                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7634            }
7635            if (bp.packageSetting == null) {
7636                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
7637                        + " from package " + bp.sourcePackage);
7638                it.remove();
7639            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7640                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7641                    Slog.i(TAG, "Removing old permission tree: " + bp.name
7642                            + " from package " + bp.sourcePackage);
7643                    flags |= UPDATE_PERMISSIONS_ALL;
7644                    it.remove();
7645                }
7646            }
7647        }
7648
7649        // Make sure all dynamic permissions have been assigned to a package,
7650        // and make sure there are no dangling permissions.
7651        it = mSettings.mPermissions.values().iterator();
7652        while (it.hasNext()) {
7653            final BasePermission bp = it.next();
7654            if (bp.type == BasePermission.TYPE_DYNAMIC) {
7655                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
7656                        + bp.name + " pkg=" + bp.sourcePackage
7657                        + " info=" + bp.pendingInfo);
7658                if (bp.packageSetting == null && bp.pendingInfo != null) {
7659                    final BasePermission tree = findPermissionTreeLP(bp.name);
7660                    if (tree != null && tree.perm != null) {
7661                        bp.packageSetting = tree.packageSetting;
7662                        bp.perm = new PackageParser.Permission(tree.perm.owner,
7663                                new PermissionInfo(bp.pendingInfo));
7664                        bp.perm.info.packageName = tree.perm.info.packageName;
7665                        bp.perm.info.name = bp.name;
7666                        bp.uid = tree.uid;
7667                    }
7668                }
7669            }
7670            if (bp.packageSetting == null) {
7671                // We may not yet have parsed the package, so just see if
7672                // we still know about its settings.
7673                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7674            }
7675            if (bp.packageSetting == null) {
7676                Slog.w(TAG, "Removing dangling permission: " + bp.name
7677                        + " from package " + bp.sourcePackage);
7678                it.remove();
7679            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7680                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7681                    Slog.i(TAG, "Removing old permission: " + bp.name
7682                            + " from package " + bp.sourcePackage);
7683                    flags |= UPDATE_PERMISSIONS_ALL;
7684                    it.remove();
7685                }
7686            }
7687        }
7688
7689        // Now update the permissions for all packages, in particular
7690        // replace the granted permissions of the system packages.
7691        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
7692            for (PackageParser.Package pkg : mPackages.values()) {
7693                if (pkg != pkgInfo) {
7694                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
7695                            changingPkg);
7696                }
7697            }
7698        }
7699
7700        if (pkgInfo != null) {
7701            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
7702        }
7703    }
7704
7705    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
7706            String packageOfInterest) {
7707        // IMPORTANT: There are two types of permissions: install and runtime.
7708        // Install time permissions are granted when the app is installed to
7709        // all device users and users added in the future. Runtime permissions
7710        // are granted at runtime explicitly to specific users. Normal and signature
7711        // protected permissions are install time permissions. Dangerous permissions
7712        // are install permissions if the app's target SDK is Lollipop MR1 or older,
7713        // otherwise they are runtime permissions. This function does not manage
7714        // runtime permissions except for the case an app targeting Lollipop MR1
7715        // being upgraded to target a newer SDK, in which case dangerous permissions
7716        // are transformed from install time to runtime ones.
7717
7718        final PackageSetting ps = (PackageSetting) pkg.mExtras;
7719        if (ps == null) {
7720            return;
7721        }
7722
7723        PermissionsState permissionsState = ps.getPermissionsState();
7724        PermissionsState origPermissions = permissionsState;
7725
7726        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
7727
7728        int[] upgradeUserIds = EMPTY_INT_ARRAY;
7729        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
7730
7731        boolean changedInstallPermission = false;
7732
7733        if (replace) {
7734            ps.installPermissionsFixed = false;
7735            if (!ps.isSharedUser()) {
7736                origPermissions = new PermissionsState(permissionsState);
7737                permissionsState.reset();
7738            }
7739        }
7740
7741        permissionsState.setGlobalGids(mGlobalGids);
7742
7743        final int N = pkg.requestedPermissions.size();
7744        for (int i=0; i<N; i++) {
7745            final String name = pkg.requestedPermissions.get(i);
7746            final BasePermission bp = mSettings.mPermissions.get(name);
7747
7748            if (DEBUG_INSTALL) {
7749                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
7750            }
7751
7752            if (bp == null || bp.packageSetting == null) {
7753                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7754                    Slog.w(TAG, "Unknown permission " + name
7755                            + " in package " + pkg.packageName);
7756                }
7757                continue;
7758            }
7759
7760            final String perm = bp.name;
7761            boolean allowedSig = false;
7762            int grant = GRANT_DENIED;
7763
7764            // Keep track of app op permissions.
7765            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7766                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
7767                if (pkgs == null) {
7768                    pkgs = new ArraySet<>();
7769                    mAppOpPermissionPackages.put(bp.name, pkgs);
7770                }
7771                pkgs.add(pkg.packageName);
7772            }
7773
7774            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
7775            switch (level) {
7776                case PermissionInfo.PROTECTION_NORMAL: {
7777                    // For all apps normal permissions are install time ones.
7778                    grant = GRANT_INSTALL;
7779                } break;
7780
7781                case PermissionInfo.PROTECTION_DANGEROUS: {
7782                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
7783                        // For legacy apps dangerous permissions are install time ones.
7784                        grant = GRANT_INSTALL_LEGACY;
7785                    } else if (ps.isSystem()) {
7786                        final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds();
7787                        if (origPermissions.hasInstallPermission(bp.name)) {
7788                            // If a system app had an install permission, then the app was
7789                            // upgraded and we grant the permissions as runtime to all users.
7790                            grant = GRANT_UPGRADE;
7791                            upgradeUserIds = currentUserIds;
7792                        } else if (!Arrays.equals(updatedUserIds, currentUserIds)) {
7793                            // If users changed since the last permissions update for a
7794                            // system app, we grant the permission as runtime to the new users.
7795                            grant = GRANT_UPGRADE;
7796                            upgradeUserIds = currentUserIds;
7797                            for (int userId : updatedUserIds) {
7798                                upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId);
7799                            }
7800                        } else {
7801                            // Otherwise, we grant the permission as runtime if the app
7802                            // already had it, i.e. we preserve runtime permissions.
7803                            grant = GRANT_RUNTIME;
7804                        }
7805                    } else if (origPermissions.hasInstallPermission(bp.name)) {
7806                        // For legacy apps that became modern, install becomes runtime.
7807                        grant = GRANT_UPGRADE;
7808                        upgradeUserIds = currentUserIds;
7809                    } else if (replace) {
7810                        // For upgraded modern apps keep runtime permissions unchanged.
7811                        grant = GRANT_RUNTIME;
7812                    }
7813                } break;
7814
7815                case PermissionInfo.PROTECTION_SIGNATURE: {
7816                    // For all apps signature permissions are install time ones.
7817                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
7818                    if (allowedSig) {
7819                        grant = GRANT_INSTALL;
7820                    }
7821                } break;
7822            }
7823
7824            if (DEBUG_INSTALL) {
7825                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
7826            }
7827
7828            if (grant != GRANT_DENIED) {
7829                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
7830                    // If this is an existing, non-system package, then
7831                    // we can't add any new permissions to it.
7832                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
7833                        // Except...  if this is a permission that was added
7834                        // to the platform (note: need to only do this when
7835                        // updating the platform).
7836                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
7837                            grant = GRANT_DENIED;
7838                        }
7839                    }
7840                }
7841
7842                switch (grant) {
7843                    case GRANT_INSTALL: {
7844                        // Revoke this as runtime permission to handle the case of
7845                        // a runtime permssion being downgraded to an install one.
7846                        for (int userId : UserManagerService.getInstance().getUserIds()) {
7847                            if (origPermissions.getRuntimePermissionState(
7848                                    bp.name, userId) != null) {
7849                                // Revoke the runtime permission and clear the flags.
7850                                origPermissions.revokeRuntimePermission(bp, userId);
7851                                origPermissions.updatePermissionFlags(bp, userId,
7852                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
7853                                // If we revoked a permission permission, we have to write.
7854                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7855                                        changedRuntimePermissionUserIds, userId);
7856                            }
7857                        }
7858                        // Grant an install permission.
7859                        if (permissionsState.grantInstallPermission(bp) !=
7860                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
7861                            changedInstallPermission = true;
7862                        }
7863                    } break;
7864
7865                    case GRANT_INSTALL_LEGACY: {
7866                        // Grant an install permission.
7867                        if (permissionsState.grantInstallPermission(bp) !=
7868                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
7869                            changedInstallPermission = true;
7870                        }
7871                    } break;
7872
7873                    case GRANT_RUNTIME: {
7874                        // Grant previously granted runtime permissions.
7875                        for (int userId : UserManagerService.getInstance().getUserIds()) {
7876                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
7877                                PermissionState permissionState = origPermissions
7878                                        .getRuntimePermissionState(bp.name, userId);
7879                                final int flags = permissionState.getFlags();
7880                                if (permissionsState.grantRuntimePermission(bp, userId) ==
7881                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7882                                    // If we cannot put the permission as it was, we have to write.
7883                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7884                                            changedRuntimePermissionUserIds, userId);
7885                                } else {
7886                                    // System components not only get the permissions but
7887                                    // they are also fixed, so nothing can change that.
7888                                    final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg)
7889                                            ? flags
7890                                            : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
7891                                    // Propagate the permission flags.
7892                                    permissionsState.updatePermissionFlags(bp, userId,
7893                                            newFlags, newFlags);
7894                                }
7895                            }
7896                        }
7897                    } break;
7898
7899                    case GRANT_UPGRADE: {
7900                        // Grant runtime permissions for a previously held install permission.
7901                        PermissionState permissionState = origPermissions
7902                                .getInstallPermissionState(bp.name);
7903                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
7904
7905                        origPermissions.revokeInstallPermission(bp);
7906                        // We will be transferring the permission flags, so clear them.
7907                        origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
7908                                PackageManager.MASK_PERMISSION_FLAGS, 0);
7909
7910                        // If the permission is not to be promoted to runtime we ignore it and
7911                        // also its other flags as they are not applicable to install permissions.
7912                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
7913                            for (int userId : upgradeUserIds) {
7914                                if (permissionsState.grantRuntimePermission(bp, userId) !=
7915                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7916                                    // System components not only get the permissions but
7917                                    // they are also fixed so nothing can change that.
7918                                    final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg)
7919                                            ? flags
7920                                            : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
7921                                    // Transfer the permission flags.
7922                                    permissionsState.updatePermissionFlags(bp, userId,
7923                                            newFlags, newFlags);
7924                                    // If we granted the permission, we have to write.
7925                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7926                                            changedRuntimePermissionUserIds, userId);
7927                                }
7928                            }
7929                        }
7930                    } break;
7931
7932                    default: {
7933                        if (packageOfInterest == null
7934                                || packageOfInterest.equals(pkg.packageName)) {
7935                            Slog.w(TAG, "Not granting permission " + perm
7936                                    + " to package " + pkg.packageName
7937                                    + " because it was previously installed without");
7938                        }
7939                    } break;
7940                }
7941            } else {
7942                if (permissionsState.revokeInstallPermission(bp) !=
7943                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7944                    // Also drop the permission flags.
7945                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
7946                            PackageManager.MASK_PERMISSION_FLAGS, 0);
7947                    changedInstallPermission = true;
7948                    Slog.i(TAG, "Un-granting permission " + perm
7949                            + " from package " + pkg.packageName
7950                            + " (protectionLevel=" + bp.protectionLevel
7951                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7952                            + ")");
7953                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
7954                    // Don't print warning for app op permissions, since it is fine for them
7955                    // not to be granted, there is a UI for the user to decide.
7956                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7957                        Slog.w(TAG, "Not granting permission " + perm
7958                                + " to package " + pkg.packageName
7959                                + " (protectionLevel=" + bp.protectionLevel
7960                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7961                                + ")");
7962                    }
7963                }
7964            }
7965        }
7966
7967        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
7968                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
7969            // This is the first that we have heard about this package, so the
7970            // permissions we have now selected are fixed until explicitly
7971            // changed.
7972            ps.installPermissionsFixed = true;
7973        }
7974
7975        ps.setPermissionsUpdatedForUserIds(currentUserIds);
7976
7977        // Persist the runtime permissions state for users with changes.
7978        for (int userId : changedRuntimePermissionUserIds) {
7979            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
7980        }
7981    }
7982
7983    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
7984        boolean allowed = false;
7985        final int NP = PackageParser.NEW_PERMISSIONS.length;
7986        for (int ip=0; ip<NP; ip++) {
7987            final PackageParser.NewPermissionInfo npi
7988                    = PackageParser.NEW_PERMISSIONS[ip];
7989            if (npi.name.equals(perm)
7990                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
7991                allowed = true;
7992                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
7993                        + pkg.packageName);
7994                break;
7995            }
7996        }
7997        return allowed;
7998    }
7999
8000    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8001            BasePermission bp, PermissionsState origPermissions) {
8002        boolean allowed;
8003        allowed = (compareSignatures(
8004                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8005                        == PackageManager.SIGNATURE_MATCH)
8006                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8007                        == PackageManager.SIGNATURE_MATCH);
8008        if (!allowed && (bp.protectionLevel
8009                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
8010            if (isSystemApp(pkg)) {
8011                // For updated system applications, a system permission
8012                // is granted only if it had been defined by the original application.
8013                if (pkg.isUpdatedSystemApp()) {
8014                    final PackageSetting sysPs = mSettings
8015                            .getDisabledSystemPkgLPr(pkg.packageName);
8016                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8017                        // If the original was granted this permission, we take
8018                        // that grant decision as read and propagate it to the
8019                        // update.
8020                        if (sysPs.isPrivileged()) {
8021                            allowed = true;
8022                        }
8023                    } else {
8024                        // The system apk may have been updated with an older
8025                        // version of the one on the data partition, but which
8026                        // granted a new system permission that it didn't have
8027                        // before.  In this case we do want to allow the app to
8028                        // now get the new permission if the ancestral apk is
8029                        // privileged to get it.
8030                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8031                            for (int j=0;
8032                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8033                                if (perm.equals(
8034                                        sysPs.pkg.requestedPermissions.get(j))) {
8035                                    allowed = true;
8036                                    break;
8037                                }
8038                            }
8039                        }
8040                    }
8041                } else {
8042                    allowed = isPrivilegedApp(pkg);
8043                }
8044            }
8045        }
8046        if (!allowed && (bp.protectionLevel
8047                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8048            // For development permissions, a development permission
8049            // is granted only if it was already granted.
8050            allowed = origPermissions.hasInstallPermission(perm);
8051        }
8052        return allowed;
8053    }
8054
8055    final class ActivityIntentResolver
8056            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8057        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8058                boolean defaultOnly, int userId) {
8059            if (!sUserManager.exists(userId)) return null;
8060            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8061            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8062        }
8063
8064        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8065                int userId) {
8066            if (!sUserManager.exists(userId)) return null;
8067            mFlags = flags;
8068            return super.queryIntent(intent, resolvedType,
8069                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8070        }
8071
8072        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8073                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8074            if (!sUserManager.exists(userId)) return null;
8075            if (packageActivities == null) {
8076                return null;
8077            }
8078            mFlags = flags;
8079            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8080            final int N = packageActivities.size();
8081            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8082                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8083
8084            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8085            for (int i = 0; i < N; ++i) {
8086                intentFilters = packageActivities.get(i).intents;
8087                if (intentFilters != null && intentFilters.size() > 0) {
8088                    PackageParser.ActivityIntentInfo[] array =
8089                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8090                    intentFilters.toArray(array);
8091                    listCut.add(array);
8092                }
8093            }
8094            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8095        }
8096
8097        public final void addActivity(PackageParser.Activity a, String type) {
8098            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8099            mActivities.put(a.getComponentName(), a);
8100            if (DEBUG_SHOW_INFO)
8101                Log.v(
8102                TAG, "  " + type + " " +
8103                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8104            if (DEBUG_SHOW_INFO)
8105                Log.v(TAG, "    Class=" + a.info.name);
8106            final int NI = a.intents.size();
8107            for (int j=0; j<NI; j++) {
8108                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8109                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8110                    intent.setPriority(0);
8111                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8112                            + a.className + " with priority > 0, forcing to 0");
8113                }
8114                if (DEBUG_SHOW_INFO) {
8115                    Log.v(TAG, "    IntentFilter:");
8116                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8117                }
8118                if (!intent.debugCheck()) {
8119                    Log.w(TAG, "==> For Activity " + a.info.name);
8120                }
8121                addFilter(intent);
8122            }
8123        }
8124
8125        public final void removeActivity(PackageParser.Activity a, String type) {
8126            mActivities.remove(a.getComponentName());
8127            if (DEBUG_SHOW_INFO) {
8128                Log.v(TAG, "  " + type + " "
8129                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8130                                : a.info.name) + ":");
8131                Log.v(TAG, "    Class=" + a.info.name);
8132            }
8133            final int NI = a.intents.size();
8134            for (int j=0; j<NI; j++) {
8135                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8136                if (DEBUG_SHOW_INFO) {
8137                    Log.v(TAG, "    IntentFilter:");
8138                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8139                }
8140                removeFilter(intent);
8141            }
8142        }
8143
8144        @Override
8145        protected boolean allowFilterResult(
8146                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8147            ActivityInfo filterAi = filter.activity.info;
8148            for (int i=dest.size()-1; i>=0; i--) {
8149                ActivityInfo destAi = dest.get(i).activityInfo;
8150                if (destAi.name == filterAi.name
8151                        && destAi.packageName == filterAi.packageName) {
8152                    return false;
8153                }
8154            }
8155            return true;
8156        }
8157
8158        @Override
8159        protected ActivityIntentInfo[] newArray(int size) {
8160            return new ActivityIntentInfo[size];
8161        }
8162
8163        @Override
8164        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8165            if (!sUserManager.exists(userId)) return true;
8166            PackageParser.Package p = filter.activity.owner;
8167            if (p != null) {
8168                PackageSetting ps = (PackageSetting)p.mExtras;
8169                if (ps != null) {
8170                    // System apps are never considered stopped for purposes of
8171                    // filtering, because there may be no way for the user to
8172                    // actually re-launch them.
8173                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8174                            && ps.getStopped(userId);
8175                }
8176            }
8177            return false;
8178        }
8179
8180        @Override
8181        protected boolean isPackageForFilter(String packageName,
8182                PackageParser.ActivityIntentInfo info) {
8183            return packageName.equals(info.activity.owner.packageName);
8184        }
8185
8186        @Override
8187        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8188                int match, int userId) {
8189            if (!sUserManager.exists(userId)) return null;
8190            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8191                return null;
8192            }
8193            final PackageParser.Activity activity = info.activity;
8194            if (mSafeMode && (activity.info.applicationInfo.flags
8195                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8196                return null;
8197            }
8198            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8199            if (ps == null) {
8200                return null;
8201            }
8202            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8203                    ps.readUserState(userId), userId);
8204            if (ai == null) {
8205                return null;
8206            }
8207            final ResolveInfo res = new ResolveInfo();
8208            res.activityInfo = ai;
8209            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8210                res.filter = info;
8211            }
8212            if (info != null) {
8213                res.handleAllWebDataURI = info.handleAllWebDataURI();
8214            }
8215            res.priority = info.getPriority();
8216            res.preferredOrder = activity.owner.mPreferredOrder;
8217            //System.out.println("Result: " + res.activityInfo.className +
8218            //                   " = " + res.priority);
8219            res.match = match;
8220            res.isDefault = info.hasDefault;
8221            res.labelRes = info.labelRes;
8222            res.nonLocalizedLabel = info.nonLocalizedLabel;
8223            if (userNeedsBadging(userId)) {
8224                res.noResourceId = true;
8225            } else {
8226                res.icon = info.icon;
8227            }
8228            res.system = res.activityInfo.applicationInfo.isSystemApp();
8229            return res;
8230        }
8231
8232        @Override
8233        protected void sortResults(List<ResolveInfo> results) {
8234            Collections.sort(results, mResolvePrioritySorter);
8235        }
8236
8237        @Override
8238        protected void dumpFilter(PrintWriter out, String prefix,
8239                PackageParser.ActivityIntentInfo filter) {
8240            out.print(prefix); out.print(
8241                    Integer.toHexString(System.identityHashCode(filter.activity)));
8242                    out.print(' ');
8243                    filter.activity.printComponentShortName(out);
8244                    out.print(" filter ");
8245                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8246        }
8247
8248        @Override
8249        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8250            return filter.activity;
8251        }
8252
8253        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8254            PackageParser.Activity activity = (PackageParser.Activity)label;
8255            out.print(prefix); out.print(
8256                    Integer.toHexString(System.identityHashCode(activity)));
8257                    out.print(' ');
8258                    activity.printComponentShortName(out);
8259            if (count > 1) {
8260                out.print(" ("); out.print(count); out.print(" filters)");
8261            }
8262            out.println();
8263        }
8264
8265//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8266//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8267//            final List<ResolveInfo> retList = Lists.newArrayList();
8268//            while (i.hasNext()) {
8269//                final ResolveInfo resolveInfo = i.next();
8270//                if (isEnabledLP(resolveInfo.activityInfo)) {
8271//                    retList.add(resolveInfo);
8272//                }
8273//            }
8274//            return retList;
8275//        }
8276
8277        // Keys are String (activity class name), values are Activity.
8278        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8279                = new ArrayMap<ComponentName, PackageParser.Activity>();
8280        private int mFlags;
8281    }
8282
8283    private final class ServiceIntentResolver
8284            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8285        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8286                boolean defaultOnly, int userId) {
8287            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8288            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8289        }
8290
8291        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8292                int userId) {
8293            if (!sUserManager.exists(userId)) return null;
8294            mFlags = flags;
8295            return super.queryIntent(intent, resolvedType,
8296                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8297        }
8298
8299        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8300                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8301            if (!sUserManager.exists(userId)) return null;
8302            if (packageServices == null) {
8303                return null;
8304            }
8305            mFlags = flags;
8306            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8307            final int N = packageServices.size();
8308            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8309                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8310
8311            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8312            for (int i = 0; i < N; ++i) {
8313                intentFilters = packageServices.get(i).intents;
8314                if (intentFilters != null && intentFilters.size() > 0) {
8315                    PackageParser.ServiceIntentInfo[] array =
8316                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8317                    intentFilters.toArray(array);
8318                    listCut.add(array);
8319                }
8320            }
8321            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8322        }
8323
8324        public final void addService(PackageParser.Service s) {
8325            mServices.put(s.getComponentName(), s);
8326            if (DEBUG_SHOW_INFO) {
8327                Log.v(TAG, "  "
8328                        + (s.info.nonLocalizedLabel != null
8329                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8330                Log.v(TAG, "    Class=" + s.info.name);
8331            }
8332            final int NI = s.intents.size();
8333            int j;
8334            for (j=0; j<NI; j++) {
8335                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8336                if (DEBUG_SHOW_INFO) {
8337                    Log.v(TAG, "    IntentFilter:");
8338                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8339                }
8340                if (!intent.debugCheck()) {
8341                    Log.w(TAG, "==> For Service " + s.info.name);
8342                }
8343                addFilter(intent);
8344            }
8345        }
8346
8347        public final void removeService(PackageParser.Service s) {
8348            mServices.remove(s.getComponentName());
8349            if (DEBUG_SHOW_INFO) {
8350                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8351                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8352                Log.v(TAG, "    Class=" + s.info.name);
8353            }
8354            final int NI = s.intents.size();
8355            int j;
8356            for (j=0; j<NI; j++) {
8357                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8358                if (DEBUG_SHOW_INFO) {
8359                    Log.v(TAG, "    IntentFilter:");
8360                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8361                }
8362                removeFilter(intent);
8363            }
8364        }
8365
8366        @Override
8367        protected boolean allowFilterResult(
8368                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8369            ServiceInfo filterSi = filter.service.info;
8370            for (int i=dest.size()-1; i>=0; i--) {
8371                ServiceInfo destAi = dest.get(i).serviceInfo;
8372                if (destAi.name == filterSi.name
8373                        && destAi.packageName == filterSi.packageName) {
8374                    return false;
8375                }
8376            }
8377            return true;
8378        }
8379
8380        @Override
8381        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8382            return new PackageParser.ServiceIntentInfo[size];
8383        }
8384
8385        @Override
8386        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8387            if (!sUserManager.exists(userId)) return true;
8388            PackageParser.Package p = filter.service.owner;
8389            if (p != null) {
8390                PackageSetting ps = (PackageSetting)p.mExtras;
8391                if (ps != null) {
8392                    // System apps are never considered stopped for purposes of
8393                    // filtering, because there may be no way for the user to
8394                    // actually re-launch them.
8395                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8396                            && ps.getStopped(userId);
8397                }
8398            }
8399            return false;
8400        }
8401
8402        @Override
8403        protected boolean isPackageForFilter(String packageName,
8404                PackageParser.ServiceIntentInfo info) {
8405            return packageName.equals(info.service.owner.packageName);
8406        }
8407
8408        @Override
8409        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8410                int match, int userId) {
8411            if (!sUserManager.exists(userId)) return null;
8412            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8413            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8414                return null;
8415            }
8416            final PackageParser.Service service = info.service;
8417            if (mSafeMode && (service.info.applicationInfo.flags
8418                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8419                return null;
8420            }
8421            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8422            if (ps == null) {
8423                return null;
8424            }
8425            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8426                    ps.readUserState(userId), userId);
8427            if (si == null) {
8428                return null;
8429            }
8430            final ResolveInfo res = new ResolveInfo();
8431            res.serviceInfo = si;
8432            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8433                res.filter = filter;
8434            }
8435            res.priority = info.getPriority();
8436            res.preferredOrder = service.owner.mPreferredOrder;
8437            res.match = match;
8438            res.isDefault = info.hasDefault;
8439            res.labelRes = info.labelRes;
8440            res.nonLocalizedLabel = info.nonLocalizedLabel;
8441            res.icon = info.icon;
8442            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8443            return res;
8444        }
8445
8446        @Override
8447        protected void sortResults(List<ResolveInfo> results) {
8448            Collections.sort(results, mResolvePrioritySorter);
8449        }
8450
8451        @Override
8452        protected void dumpFilter(PrintWriter out, String prefix,
8453                PackageParser.ServiceIntentInfo filter) {
8454            out.print(prefix); out.print(
8455                    Integer.toHexString(System.identityHashCode(filter.service)));
8456                    out.print(' ');
8457                    filter.service.printComponentShortName(out);
8458                    out.print(" filter ");
8459                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8460        }
8461
8462        @Override
8463        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8464            return filter.service;
8465        }
8466
8467        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8468            PackageParser.Service service = (PackageParser.Service)label;
8469            out.print(prefix); out.print(
8470                    Integer.toHexString(System.identityHashCode(service)));
8471                    out.print(' ');
8472                    service.printComponentShortName(out);
8473            if (count > 1) {
8474                out.print(" ("); out.print(count); out.print(" filters)");
8475            }
8476            out.println();
8477        }
8478
8479//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8480//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8481//            final List<ResolveInfo> retList = Lists.newArrayList();
8482//            while (i.hasNext()) {
8483//                final ResolveInfo resolveInfo = (ResolveInfo) i;
8484//                if (isEnabledLP(resolveInfo.serviceInfo)) {
8485//                    retList.add(resolveInfo);
8486//                }
8487//            }
8488//            return retList;
8489//        }
8490
8491        // Keys are String (activity class name), values are Activity.
8492        private final ArrayMap<ComponentName, PackageParser.Service> mServices
8493                = new ArrayMap<ComponentName, PackageParser.Service>();
8494        private int mFlags;
8495    };
8496
8497    private final class ProviderIntentResolver
8498            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
8499        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8500                boolean defaultOnly, int userId) {
8501            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8502            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8503        }
8504
8505        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8506                int userId) {
8507            if (!sUserManager.exists(userId))
8508                return null;
8509            mFlags = flags;
8510            return super.queryIntent(intent, resolvedType,
8511                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8512        }
8513
8514        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8515                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
8516            if (!sUserManager.exists(userId))
8517                return null;
8518            if (packageProviders == null) {
8519                return null;
8520            }
8521            mFlags = flags;
8522            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
8523            final int N = packageProviders.size();
8524            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
8525                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
8526
8527            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
8528            for (int i = 0; i < N; ++i) {
8529                intentFilters = packageProviders.get(i).intents;
8530                if (intentFilters != null && intentFilters.size() > 0) {
8531                    PackageParser.ProviderIntentInfo[] array =
8532                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
8533                    intentFilters.toArray(array);
8534                    listCut.add(array);
8535                }
8536            }
8537            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8538        }
8539
8540        public final void addProvider(PackageParser.Provider p) {
8541            if (mProviders.containsKey(p.getComponentName())) {
8542                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
8543                return;
8544            }
8545
8546            mProviders.put(p.getComponentName(), p);
8547            if (DEBUG_SHOW_INFO) {
8548                Log.v(TAG, "  "
8549                        + (p.info.nonLocalizedLabel != null
8550                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
8551                Log.v(TAG, "    Class=" + p.info.name);
8552            }
8553            final int NI = p.intents.size();
8554            int j;
8555            for (j = 0; j < NI; j++) {
8556                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8557                if (DEBUG_SHOW_INFO) {
8558                    Log.v(TAG, "    IntentFilter:");
8559                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8560                }
8561                if (!intent.debugCheck()) {
8562                    Log.w(TAG, "==> For Provider " + p.info.name);
8563                }
8564                addFilter(intent);
8565            }
8566        }
8567
8568        public final void removeProvider(PackageParser.Provider p) {
8569            mProviders.remove(p.getComponentName());
8570            if (DEBUG_SHOW_INFO) {
8571                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
8572                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
8573                Log.v(TAG, "    Class=" + p.info.name);
8574            }
8575            final int NI = p.intents.size();
8576            int j;
8577            for (j = 0; j < NI; j++) {
8578                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8579                if (DEBUG_SHOW_INFO) {
8580                    Log.v(TAG, "    IntentFilter:");
8581                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8582                }
8583                removeFilter(intent);
8584            }
8585        }
8586
8587        @Override
8588        protected boolean allowFilterResult(
8589                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
8590            ProviderInfo filterPi = filter.provider.info;
8591            for (int i = dest.size() - 1; i >= 0; i--) {
8592                ProviderInfo destPi = dest.get(i).providerInfo;
8593                if (destPi.name == filterPi.name
8594                        && destPi.packageName == filterPi.packageName) {
8595                    return false;
8596                }
8597            }
8598            return true;
8599        }
8600
8601        @Override
8602        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
8603            return new PackageParser.ProviderIntentInfo[size];
8604        }
8605
8606        @Override
8607        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
8608            if (!sUserManager.exists(userId))
8609                return true;
8610            PackageParser.Package p = filter.provider.owner;
8611            if (p != null) {
8612                PackageSetting ps = (PackageSetting) p.mExtras;
8613                if (ps != null) {
8614                    // System apps are never considered stopped for purposes of
8615                    // filtering, because there may be no way for the user to
8616                    // actually re-launch them.
8617                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8618                            && ps.getStopped(userId);
8619                }
8620            }
8621            return false;
8622        }
8623
8624        @Override
8625        protected boolean isPackageForFilter(String packageName,
8626                PackageParser.ProviderIntentInfo info) {
8627            return packageName.equals(info.provider.owner.packageName);
8628        }
8629
8630        @Override
8631        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
8632                int match, int userId) {
8633            if (!sUserManager.exists(userId))
8634                return null;
8635            final PackageParser.ProviderIntentInfo info = filter;
8636            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
8637                return null;
8638            }
8639            final PackageParser.Provider provider = info.provider;
8640            if (mSafeMode && (provider.info.applicationInfo.flags
8641                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
8642                return null;
8643            }
8644            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
8645            if (ps == null) {
8646                return null;
8647            }
8648            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
8649                    ps.readUserState(userId), userId);
8650            if (pi == null) {
8651                return null;
8652            }
8653            final ResolveInfo res = new ResolveInfo();
8654            res.providerInfo = pi;
8655            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
8656                res.filter = filter;
8657            }
8658            res.priority = info.getPriority();
8659            res.preferredOrder = provider.owner.mPreferredOrder;
8660            res.match = match;
8661            res.isDefault = info.hasDefault;
8662            res.labelRes = info.labelRes;
8663            res.nonLocalizedLabel = info.nonLocalizedLabel;
8664            res.icon = info.icon;
8665            res.system = res.providerInfo.applicationInfo.isSystemApp();
8666            return res;
8667        }
8668
8669        @Override
8670        protected void sortResults(List<ResolveInfo> results) {
8671            Collections.sort(results, mResolvePrioritySorter);
8672        }
8673
8674        @Override
8675        protected void dumpFilter(PrintWriter out, String prefix,
8676                PackageParser.ProviderIntentInfo filter) {
8677            out.print(prefix);
8678            out.print(
8679                    Integer.toHexString(System.identityHashCode(filter.provider)));
8680            out.print(' ');
8681            filter.provider.printComponentShortName(out);
8682            out.print(" filter ");
8683            out.println(Integer.toHexString(System.identityHashCode(filter)));
8684        }
8685
8686        @Override
8687        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
8688            return filter.provider;
8689        }
8690
8691        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8692            PackageParser.Provider provider = (PackageParser.Provider)label;
8693            out.print(prefix); out.print(
8694                    Integer.toHexString(System.identityHashCode(provider)));
8695                    out.print(' ');
8696                    provider.printComponentShortName(out);
8697            if (count > 1) {
8698                out.print(" ("); out.print(count); out.print(" filters)");
8699            }
8700            out.println();
8701        }
8702
8703        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
8704                = new ArrayMap<ComponentName, PackageParser.Provider>();
8705        private int mFlags;
8706    };
8707
8708    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
8709            new Comparator<ResolveInfo>() {
8710        public int compare(ResolveInfo r1, ResolveInfo r2) {
8711            int v1 = r1.priority;
8712            int v2 = r2.priority;
8713            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
8714            if (v1 != v2) {
8715                return (v1 > v2) ? -1 : 1;
8716            }
8717            v1 = r1.preferredOrder;
8718            v2 = r2.preferredOrder;
8719            if (v1 != v2) {
8720                return (v1 > v2) ? -1 : 1;
8721            }
8722            if (r1.isDefault != r2.isDefault) {
8723                return r1.isDefault ? -1 : 1;
8724            }
8725            v1 = r1.match;
8726            v2 = r2.match;
8727            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
8728            if (v1 != v2) {
8729                return (v1 > v2) ? -1 : 1;
8730            }
8731            if (r1.system != r2.system) {
8732                return r1.system ? -1 : 1;
8733            }
8734            return 0;
8735        }
8736    };
8737
8738    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
8739            new Comparator<ProviderInfo>() {
8740        public int compare(ProviderInfo p1, ProviderInfo p2) {
8741            final int v1 = p1.initOrder;
8742            final int v2 = p2.initOrder;
8743            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
8744        }
8745    };
8746
8747    final void sendPackageBroadcast(final String action, final String pkg,
8748            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
8749            final int[] userIds) {
8750        mHandler.post(new Runnable() {
8751            @Override
8752            public void run() {
8753                try {
8754                    final IActivityManager am = ActivityManagerNative.getDefault();
8755                    if (am == null) return;
8756                    final int[] resolvedUserIds;
8757                    if (userIds == null) {
8758                        resolvedUserIds = am.getRunningUserIds();
8759                    } else {
8760                        resolvedUserIds = userIds;
8761                    }
8762                    for (int id : resolvedUserIds) {
8763                        final Intent intent = new Intent(action,
8764                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
8765                        if (extras != null) {
8766                            intent.putExtras(extras);
8767                        }
8768                        if (targetPkg != null) {
8769                            intent.setPackage(targetPkg);
8770                        }
8771                        // Modify the UID when posting to other users
8772                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
8773                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
8774                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
8775                            intent.putExtra(Intent.EXTRA_UID, uid);
8776                        }
8777                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
8778                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
8779                        if (DEBUG_BROADCASTS) {
8780                            RuntimeException here = new RuntimeException("here");
8781                            here.fillInStackTrace();
8782                            Slog.d(TAG, "Sending to user " + id + ": "
8783                                    + intent.toShortString(false, true, false, false)
8784                                    + " " + intent.getExtras(), here);
8785                        }
8786                        am.broadcastIntent(null, intent, null, finishedReceiver,
8787                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
8788                                finishedReceiver != null, false, id);
8789                    }
8790                } catch (RemoteException ex) {
8791                }
8792            }
8793        });
8794    }
8795
8796    /**
8797     * Check if the external storage media is available. This is true if there
8798     * is a mounted external storage medium or if the external storage is
8799     * emulated.
8800     */
8801    private boolean isExternalMediaAvailable() {
8802        return mMediaMounted || Environment.isExternalStorageEmulated();
8803    }
8804
8805    @Override
8806    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
8807        // writer
8808        synchronized (mPackages) {
8809            if (!isExternalMediaAvailable()) {
8810                // If the external storage is no longer mounted at this point,
8811                // the caller may not have been able to delete all of this
8812                // packages files and can not delete any more.  Bail.
8813                return null;
8814            }
8815            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
8816            if (lastPackage != null) {
8817                pkgs.remove(lastPackage);
8818            }
8819            if (pkgs.size() > 0) {
8820                return pkgs.get(0);
8821            }
8822        }
8823        return null;
8824    }
8825
8826    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
8827        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
8828                userId, andCode ? 1 : 0, packageName);
8829        if (mSystemReady) {
8830            msg.sendToTarget();
8831        } else {
8832            if (mPostSystemReadyMessages == null) {
8833                mPostSystemReadyMessages = new ArrayList<>();
8834            }
8835            mPostSystemReadyMessages.add(msg);
8836        }
8837    }
8838
8839    void startCleaningPackages() {
8840        // reader
8841        synchronized (mPackages) {
8842            if (!isExternalMediaAvailable()) {
8843                return;
8844            }
8845            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
8846                return;
8847            }
8848        }
8849        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
8850        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
8851        IActivityManager am = ActivityManagerNative.getDefault();
8852        if (am != null) {
8853            try {
8854                am.startService(null, intent, null, UserHandle.USER_OWNER);
8855            } catch (RemoteException e) {
8856            }
8857        }
8858    }
8859
8860    @Override
8861    public void installPackage(String originPath, IPackageInstallObserver2 observer,
8862            int installFlags, String installerPackageName, VerificationParams verificationParams,
8863            String packageAbiOverride) {
8864        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
8865                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
8866    }
8867
8868    @Override
8869    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
8870            int installFlags, String installerPackageName, VerificationParams verificationParams,
8871            String packageAbiOverride, int userId) {
8872        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
8873
8874        final int callingUid = Binder.getCallingUid();
8875        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
8876
8877        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8878            try {
8879                if (observer != null) {
8880                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
8881                }
8882            } catch (RemoteException re) {
8883            }
8884            return;
8885        }
8886
8887        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
8888            installFlags |= PackageManager.INSTALL_FROM_ADB;
8889
8890        } else {
8891            // Caller holds INSTALL_PACKAGES permission, so we're less strict
8892            // about installerPackageName.
8893
8894            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
8895            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
8896        }
8897
8898        UserHandle user;
8899        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
8900            user = UserHandle.ALL;
8901        } else {
8902            user = new UserHandle(userId);
8903        }
8904
8905        // Only system components can circumvent runtime permissions when installing.
8906        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
8907                && mContext.checkCallingOrSelfPermission(Manifest.permission
8908                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
8909            throw new SecurityException("You need the "
8910                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
8911                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
8912        }
8913
8914        verificationParams.setInstallerUid(callingUid);
8915
8916        final File originFile = new File(originPath);
8917        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
8918
8919        final Message msg = mHandler.obtainMessage(INIT_COPY);
8920        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
8921                null, verificationParams, user, packageAbiOverride);
8922        mHandler.sendMessage(msg);
8923    }
8924
8925    void installStage(String packageName, File stagedDir, String stagedCid,
8926            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
8927            String installerPackageName, int installerUid, UserHandle user) {
8928        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
8929                params.referrerUri, installerUid, null);
8930
8931        final OriginInfo origin;
8932        if (stagedDir != null) {
8933            origin = OriginInfo.fromStagedFile(stagedDir);
8934        } else {
8935            origin = OriginInfo.fromStagedContainer(stagedCid);
8936        }
8937
8938        final Message msg = mHandler.obtainMessage(INIT_COPY);
8939        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
8940                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
8941        mHandler.sendMessage(msg);
8942    }
8943
8944    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
8945        Bundle extras = new Bundle(1);
8946        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
8947
8948        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
8949                packageName, extras, null, null, new int[] {userId});
8950        try {
8951            IActivityManager am = ActivityManagerNative.getDefault();
8952            final boolean isSystem =
8953                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
8954            if (isSystem && am.isUserRunning(userId, false)) {
8955                // The just-installed/enabled app is bundled on the system, so presumed
8956                // to be able to run automatically without needing an explicit launch.
8957                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
8958                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
8959                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
8960                        .setPackage(packageName);
8961                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
8962                        android.app.AppOpsManager.OP_NONE, false, false, userId);
8963            }
8964        } catch (RemoteException e) {
8965            // shouldn't happen
8966            Slog.w(TAG, "Unable to bootstrap installed package", e);
8967        }
8968    }
8969
8970    @Override
8971    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
8972            int userId) {
8973        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8974        PackageSetting pkgSetting;
8975        final int uid = Binder.getCallingUid();
8976        enforceCrossUserPermission(uid, userId, true, true,
8977                "setApplicationHiddenSetting for user " + userId);
8978
8979        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
8980            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
8981            return false;
8982        }
8983
8984        long callingId = Binder.clearCallingIdentity();
8985        try {
8986            boolean sendAdded = false;
8987            boolean sendRemoved = false;
8988            // writer
8989            synchronized (mPackages) {
8990                pkgSetting = mSettings.mPackages.get(packageName);
8991                if (pkgSetting == null) {
8992                    return false;
8993                }
8994                if (pkgSetting.getHidden(userId) != hidden) {
8995                    pkgSetting.setHidden(hidden, userId);
8996                    mSettings.writePackageRestrictionsLPr(userId);
8997                    if (hidden) {
8998                        sendRemoved = true;
8999                    } else {
9000                        sendAdded = true;
9001                    }
9002                }
9003            }
9004            if (sendAdded) {
9005                sendPackageAddedForUser(packageName, pkgSetting, userId);
9006                return true;
9007            }
9008            if (sendRemoved) {
9009                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9010                        "hiding pkg");
9011                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9012            }
9013        } finally {
9014            Binder.restoreCallingIdentity(callingId);
9015        }
9016        return false;
9017    }
9018
9019    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9020            int userId) {
9021        final PackageRemovedInfo info = new PackageRemovedInfo();
9022        info.removedPackage = packageName;
9023        info.removedUsers = new int[] {userId};
9024        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9025        info.sendBroadcast(false, false, false);
9026    }
9027
9028    /**
9029     * Returns true if application is not found or there was an error. Otherwise it returns
9030     * the hidden state of the package for the given user.
9031     */
9032    @Override
9033    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9034        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9035        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9036                false, "getApplicationHidden for user " + userId);
9037        PackageSetting pkgSetting;
9038        long callingId = Binder.clearCallingIdentity();
9039        try {
9040            // writer
9041            synchronized (mPackages) {
9042                pkgSetting = mSettings.mPackages.get(packageName);
9043                if (pkgSetting == null) {
9044                    return true;
9045                }
9046                return pkgSetting.getHidden(userId);
9047            }
9048        } finally {
9049            Binder.restoreCallingIdentity(callingId);
9050        }
9051    }
9052
9053    /**
9054     * @hide
9055     */
9056    @Override
9057    public int installExistingPackageAsUser(String packageName, int userId) {
9058        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9059                null);
9060        PackageSetting pkgSetting;
9061        final int uid = Binder.getCallingUid();
9062        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9063                + userId);
9064        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9065            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9066        }
9067
9068        long callingId = Binder.clearCallingIdentity();
9069        try {
9070            boolean sendAdded = false;
9071
9072            // writer
9073            synchronized (mPackages) {
9074                pkgSetting = mSettings.mPackages.get(packageName);
9075                if (pkgSetting == null) {
9076                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9077                }
9078                if (!pkgSetting.getInstalled(userId)) {
9079                    pkgSetting.setInstalled(true, userId);
9080                    pkgSetting.setHidden(false, userId);
9081                    mSettings.writePackageRestrictionsLPr(userId);
9082                    sendAdded = true;
9083                }
9084            }
9085
9086            if (sendAdded) {
9087                sendPackageAddedForUser(packageName, pkgSetting, userId);
9088            }
9089        } finally {
9090            Binder.restoreCallingIdentity(callingId);
9091        }
9092
9093        return PackageManager.INSTALL_SUCCEEDED;
9094    }
9095
9096    boolean isUserRestricted(int userId, String restrictionKey) {
9097        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9098        if (restrictions.getBoolean(restrictionKey, false)) {
9099            Log.w(TAG, "User is restricted: " + restrictionKey);
9100            return true;
9101        }
9102        return false;
9103    }
9104
9105    @Override
9106    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9107        mContext.enforceCallingOrSelfPermission(
9108                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9109                "Only package verification agents can verify applications");
9110
9111        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9112        final PackageVerificationResponse response = new PackageVerificationResponse(
9113                verificationCode, Binder.getCallingUid());
9114        msg.arg1 = id;
9115        msg.obj = response;
9116        mHandler.sendMessage(msg);
9117    }
9118
9119    @Override
9120    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9121            long millisecondsToDelay) {
9122        mContext.enforceCallingOrSelfPermission(
9123                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9124                "Only package verification agents can extend verification timeouts");
9125
9126        final PackageVerificationState state = mPendingVerification.get(id);
9127        final PackageVerificationResponse response = new PackageVerificationResponse(
9128                verificationCodeAtTimeout, Binder.getCallingUid());
9129
9130        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9131            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9132        }
9133        if (millisecondsToDelay < 0) {
9134            millisecondsToDelay = 0;
9135        }
9136        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9137                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9138            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9139        }
9140
9141        if ((state != null) && !state.timeoutExtended()) {
9142            state.extendTimeout();
9143
9144            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9145            msg.arg1 = id;
9146            msg.obj = response;
9147            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9148        }
9149    }
9150
9151    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9152            int verificationCode, UserHandle user) {
9153        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9154        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9155        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9156        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9157        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9158
9159        mContext.sendBroadcastAsUser(intent, user,
9160                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9161    }
9162
9163    private ComponentName matchComponentForVerifier(String packageName,
9164            List<ResolveInfo> receivers) {
9165        ActivityInfo targetReceiver = null;
9166
9167        final int NR = receivers.size();
9168        for (int i = 0; i < NR; i++) {
9169            final ResolveInfo info = receivers.get(i);
9170            if (info.activityInfo == null) {
9171                continue;
9172            }
9173
9174            if (packageName.equals(info.activityInfo.packageName)) {
9175                targetReceiver = info.activityInfo;
9176                break;
9177            }
9178        }
9179
9180        if (targetReceiver == null) {
9181            return null;
9182        }
9183
9184        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9185    }
9186
9187    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9188            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9189        if (pkgInfo.verifiers.length == 0) {
9190            return null;
9191        }
9192
9193        final int N = pkgInfo.verifiers.length;
9194        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9195        for (int i = 0; i < N; i++) {
9196            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9197
9198            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9199                    receivers);
9200            if (comp == null) {
9201                continue;
9202            }
9203
9204            final int verifierUid = getUidForVerifier(verifierInfo);
9205            if (verifierUid == -1) {
9206                continue;
9207            }
9208
9209            if (DEBUG_VERIFY) {
9210                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9211                        + " with the correct signature");
9212            }
9213            sufficientVerifiers.add(comp);
9214            verificationState.addSufficientVerifier(verifierUid);
9215        }
9216
9217        return sufficientVerifiers;
9218    }
9219
9220    private int getUidForVerifier(VerifierInfo verifierInfo) {
9221        synchronized (mPackages) {
9222            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9223            if (pkg == null) {
9224                return -1;
9225            } else if (pkg.mSignatures.length != 1) {
9226                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9227                        + " has more than one signature; ignoring");
9228                return -1;
9229            }
9230
9231            /*
9232             * If the public key of the package's signature does not match
9233             * our expected public key, then this is a different package and
9234             * we should skip.
9235             */
9236
9237            final byte[] expectedPublicKey;
9238            try {
9239                final Signature verifierSig = pkg.mSignatures[0];
9240                final PublicKey publicKey = verifierSig.getPublicKey();
9241                expectedPublicKey = publicKey.getEncoded();
9242            } catch (CertificateException e) {
9243                return -1;
9244            }
9245
9246            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9247
9248            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9249                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9250                        + " does not have the expected public key; ignoring");
9251                return -1;
9252            }
9253
9254            return pkg.applicationInfo.uid;
9255        }
9256    }
9257
9258    @Override
9259    public void finishPackageInstall(int token) {
9260        enforceSystemOrRoot("Only the system is allowed to finish installs");
9261
9262        if (DEBUG_INSTALL) {
9263            Slog.v(TAG, "BM finishing package install for " + token);
9264        }
9265
9266        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9267        mHandler.sendMessage(msg);
9268    }
9269
9270    /**
9271     * Get the verification agent timeout.
9272     *
9273     * @return verification timeout in milliseconds
9274     */
9275    private long getVerificationTimeout() {
9276        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9277                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9278                DEFAULT_VERIFICATION_TIMEOUT);
9279    }
9280
9281    /**
9282     * Get the default verification agent response code.
9283     *
9284     * @return default verification response code
9285     */
9286    private int getDefaultVerificationResponse() {
9287        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9288                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9289                DEFAULT_VERIFICATION_RESPONSE);
9290    }
9291
9292    /**
9293     * Check whether or not package verification has been enabled.
9294     *
9295     * @return true if verification should be performed
9296     */
9297    private boolean isVerificationEnabled(int userId, int installFlags) {
9298        if (!DEFAULT_VERIFY_ENABLE) {
9299            return false;
9300        }
9301
9302        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9303
9304        // Check if installing from ADB
9305        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9306            // Do not run verification in a test harness environment
9307            if (ActivityManager.isRunningInTestHarness()) {
9308                return false;
9309            }
9310            if (ensureVerifyAppsEnabled) {
9311                return true;
9312            }
9313            // Check if the developer does not want package verification for ADB installs
9314            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9315                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9316                return false;
9317            }
9318        }
9319
9320        if (ensureVerifyAppsEnabled) {
9321            return true;
9322        }
9323
9324        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9325                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9326    }
9327
9328    @Override
9329    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9330            throws RemoteException {
9331        mContext.enforceCallingOrSelfPermission(
9332                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9333                "Only intentfilter verification agents can verify applications");
9334
9335        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9336        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9337                Binder.getCallingUid(), verificationCode, failedDomains);
9338        msg.arg1 = id;
9339        msg.obj = response;
9340        mHandler.sendMessage(msg);
9341    }
9342
9343    @Override
9344    public int getIntentVerificationStatus(String packageName, int userId) {
9345        synchronized (mPackages) {
9346            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9347        }
9348    }
9349
9350    @Override
9351    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9352        boolean result = false;
9353        synchronized (mPackages) {
9354            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9355        }
9356        if (result) {
9357            scheduleWritePackageRestrictionsLocked(userId);
9358        }
9359        return result;
9360    }
9361
9362    @Override
9363    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9364        synchronized (mPackages) {
9365            return mSettings.getIntentFilterVerificationsLPr(packageName);
9366        }
9367    }
9368
9369    @Override
9370    public List<IntentFilter> getAllIntentFilters(String packageName) {
9371        if (TextUtils.isEmpty(packageName)) {
9372            return Collections.<IntentFilter>emptyList();
9373        }
9374        synchronized (mPackages) {
9375            PackageParser.Package pkg = mPackages.get(packageName);
9376            if (pkg == null || pkg.activities == null) {
9377                return Collections.<IntentFilter>emptyList();
9378            }
9379            final int count = pkg.activities.size();
9380            ArrayList<IntentFilter> result = new ArrayList<>();
9381            for (int n=0; n<count; n++) {
9382                PackageParser.Activity activity = pkg.activities.get(n);
9383                if (activity.intents != null || activity.intents.size() > 0) {
9384                    result.addAll(activity.intents);
9385                }
9386            }
9387            return result;
9388        }
9389    }
9390
9391    @Override
9392    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9393        synchronized (mPackages) {
9394            boolean result = mSettings.setDefaultBrowserPackageNameLPr(packageName, userId);
9395            if (packageName != null) {
9396                result |= updateIntentVerificationStatus(packageName,
9397                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9398                        UserHandle.myUserId());
9399            }
9400            return result;
9401        }
9402    }
9403
9404    @Override
9405    public String getDefaultBrowserPackageName(int userId) {
9406        synchronized (mPackages) {
9407            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9408        }
9409    }
9410
9411    /**
9412     * Get the "allow unknown sources" setting.
9413     *
9414     * @return the current "allow unknown sources" setting
9415     */
9416    private int getUnknownSourcesSettings() {
9417        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9418                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9419                -1);
9420    }
9421
9422    @Override
9423    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9424        final int uid = Binder.getCallingUid();
9425        // writer
9426        synchronized (mPackages) {
9427            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9428            if (targetPackageSetting == null) {
9429                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9430            }
9431
9432            PackageSetting installerPackageSetting;
9433            if (installerPackageName != null) {
9434                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9435                if (installerPackageSetting == null) {
9436                    throw new IllegalArgumentException("Unknown installer package: "
9437                            + installerPackageName);
9438                }
9439            } else {
9440                installerPackageSetting = null;
9441            }
9442
9443            Signature[] callerSignature;
9444            Object obj = mSettings.getUserIdLPr(uid);
9445            if (obj != null) {
9446                if (obj instanceof SharedUserSetting) {
9447                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9448                } else if (obj instanceof PackageSetting) {
9449                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9450                } else {
9451                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9452                }
9453            } else {
9454                throw new SecurityException("Unknown calling uid " + uid);
9455            }
9456
9457            // Verify: can't set installerPackageName to a package that is
9458            // not signed with the same cert as the caller.
9459            if (installerPackageSetting != null) {
9460                if (compareSignatures(callerSignature,
9461                        installerPackageSetting.signatures.mSignatures)
9462                        != PackageManager.SIGNATURE_MATCH) {
9463                    throw new SecurityException(
9464                            "Caller does not have same cert as new installer package "
9465                            + installerPackageName);
9466                }
9467            }
9468
9469            // Verify: if target already has an installer package, it must
9470            // be signed with the same cert as the caller.
9471            if (targetPackageSetting.installerPackageName != null) {
9472                PackageSetting setting = mSettings.mPackages.get(
9473                        targetPackageSetting.installerPackageName);
9474                // If the currently set package isn't valid, then it's always
9475                // okay to change it.
9476                if (setting != null) {
9477                    if (compareSignatures(callerSignature,
9478                            setting.signatures.mSignatures)
9479                            != PackageManager.SIGNATURE_MATCH) {
9480                        throw new SecurityException(
9481                                "Caller does not have same cert as old installer package "
9482                                + targetPackageSetting.installerPackageName);
9483                    }
9484                }
9485            }
9486
9487            // Okay!
9488            targetPackageSetting.installerPackageName = installerPackageName;
9489            scheduleWriteSettingsLocked();
9490        }
9491    }
9492
9493    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
9494        // Queue up an async operation since the package installation may take a little while.
9495        mHandler.post(new Runnable() {
9496            public void run() {
9497                mHandler.removeCallbacks(this);
9498                 // Result object to be returned
9499                PackageInstalledInfo res = new PackageInstalledInfo();
9500                res.returnCode = currentStatus;
9501                res.uid = -1;
9502                res.pkg = null;
9503                res.removedInfo = new PackageRemovedInfo();
9504                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9505                    args.doPreInstall(res.returnCode);
9506                    synchronized (mInstallLock) {
9507                        installPackageLI(args, res);
9508                    }
9509                    args.doPostInstall(res.returnCode, res.uid);
9510                }
9511
9512                // A restore should be performed at this point if (a) the install
9513                // succeeded, (b) the operation is not an update, and (c) the new
9514                // package has not opted out of backup participation.
9515                final boolean update = res.removedInfo.removedPackage != null;
9516                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
9517                boolean doRestore = !update
9518                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
9519
9520                // Set up the post-install work request bookkeeping.  This will be used
9521                // and cleaned up by the post-install event handling regardless of whether
9522                // there's a restore pass performed.  Token values are >= 1.
9523                int token;
9524                if (mNextInstallToken < 0) mNextInstallToken = 1;
9525                token = mNextInstallToken++;
9526
9527                PostInstallData data = new PostInstallData(args, res);
9528                mRunningInstalls.put(token, data);
9529                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
9530
9531                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
9532                    // Pass responsibility to the Backup Manager.  It will perform a
9533                    // restore if appropriate, then pass responsibility back to the
9534                    // Package Manager to run the post-install observer callbacks
9535                    // and broadcasts.
9536                    IBackupManager bm = IBackupManager.Stub.asInterface(
9537                            ServiceManager.getService(Context.BACKUP_SERVICE));
9538                    if (bm != null) {
9539                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
9540                                + " to BM for possible restore");
9541                        try {
9542                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
9543                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
9544                            } else {
9545                                doRestore = false;
9546                            }
9547                        } catch (RemoteException e) {
9548                            // can't happen; the backup manager is local
9549                        } catch (Exception e) {
9550                            Slog.e(TAG, "Exception trying to enqueue restore", e);
9551                            doRestore = false;
9552                        }
9553                    } else {
9554                        Slog.e(TAG, "Backup Manager not found!");
9555                        doRestore = false;
9556                    }
9557                }
9558
9559                if (!doRestore) {
9560                    // No restore possible, or the Backup Manager was mysteriously not
9561                    // available -- just fire the post-install work request directly.
9562                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
9563                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9564                    mHandler.sendMessage(msg);
9565                }
9566            }
9567        });
9568    }
9569
9570    private abstract class HandlerParams {
9571        private static final int MAX_RETRIES = 4;
9572
9573        /**
9574         * Number of times startCopy() has been attempted and had a non-fatal
9575         * error.
9576         */
9577        private int mRetries = 0;
9578
9579        /** User handle for the user requesting the information or installation. */
9580        private final UserHandle mUser;
9581
9582        HandlerParams(UserHandle user) {
9583            mUser = user;
9584        }
9585
9586        UserHandle getUser() {
9587            return mUser;
9588        }
9589
9590        final boolean startCopy() {
9591            boolean res;
9592            try {
9593                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
9594
9595                if (++mRetries > MAX_RETRIES) {
9596                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
9597                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
9598                    handleServiceError();
9599                    return false;
9600                } else {
9601                    handleStartCopy();
9602                    res = true;
9603                }
9604            } catch (RemoteException e) {
9605                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
9606                mHandler.sendEmptyMessage(MCS_RECONNECT);
9607                res = false;
9608            }
9609            handleReturnCode();
9610            return res;
9611        }
9612
9613        final void serviceError() {
9614            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
9615            handleServiceError();
9616            handleReturnCode();
9617        }
9618
9619        abstract void handleStartCopy() throws RemoteException;
9620        abstract void handleServiceError();
9621        abstract void handleReturnCode();
9622    }
9623
9624    class MeasureParams extends HandlerParams {
9625        private final PackageStats mStats;
9626        private boolean mSuccess;
9627
9628        private final IPackageStatsObserver mObserver;
9629
9630        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
9631            super(new UserHandle(stats.userHandle));
9632            mObserver = observer;
9633            mStats = stats;
9634        }
9635
9636        @Override
9637        public String toString() {
9638            return "MeasureParams{"
9639                + Integer.toHexString(System.identityHashCode(this))
9640                + " " + mStats.packageName + "}";
9641        }
9642
9643        @Override
9644        void handleStartCopy() throws RemoteException {
9645            synchronized (mInstallLock) {
9646                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
9647            }
9648
9649            if (mSuccess) {
9650                final boolean mounted;
9651                if (Environment.isExternalStorageEmulated()) {
9652                    mounted = true;
9653                } else {
9654                    final String status = Environment.getExternalStorageState();
9655                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
9656                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
9657                }
9658
9659                if (mounted) {
9660                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
9661
9662                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
9663                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
9664
9665                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
9666                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
9667
9668                    // Always subtract cache size, since it's a subdirectory
9669                    mStats.externalDataSize -= mStats.externalCacheSize;
9670
9671                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
9672                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
9673
9674                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
9675                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
9676                }
9677            }
9678        }
9679
9680        @Override
9681        void handleReturnCode() {
9682            if (mObserver != null) {
9683                try {
9684                    mObserver.onGetStatsCompleted(mStats, mSuccess);
9685                } catch (RemoteException e) {
9686                    Slog.i(TAG, "Observer no longer exists.");
9687                }
9688            }
9689        }
9690
9691        @Override
9692        void handleServiceError() {
9693            Slog.e(TAG, "Could not measure application " + mStats.packageName
9694                            + " external storage");
9695        }
9696    }
9697
9698    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
9699            throws RemoteException {
9700        long result = 0;
9701        for (File path : paths) {
9702            result += mcs.calculateDirectorySize(path.getAbsolutePath());
9703        }
9704        return result;
9705    }
9706
9707    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
9708        for (File path : paths) {
9709            try {
9710                mcs.clearDirectory(path.getAbsolutePath());
9711            } catch (RemoteException e) {
9712            }
9713        }
9714    }
9715
9716    static class OriginInfo {
9717        /**
9718         * Location where install is coming from, before it has been
9719         * copied/renamed into place. This could be a single monolithic APK
9720         * file, or a cluster directory. This location may be untrusted.
9721         */
9722        final File file;
9723        final String cid;
9724
9725        /**
9726         * Flag indicating that {@link #file} or {@link #cid} has already been
9727         * staged, meaning downstream users don't need to defensively copy the
9728         * contents.
9729         */
9730        final boolean staged;
9731
9732        /**
9733         * Flag indicating that {@link #file} or {@link #cid} is an already
9734         * installed app that is being moved.
9735         */
9736        final boolean existing;
9737
9738        final String resolvedPath;
9739        final File resolvedFile;
9740
9741        static OriginInfo fromNothing() {
9742            return new OriginInfo(null, null, false, false);
9743        }
9744
9745        static OriginInfo fromUntrustedFile(File file) {
9746            return new OriginInfo(file, null, false, false);
9747        }
9748
9749        static OriginInfo fromExistingFile(File file) {
9750            return new OriginInfo(file, null, false, true);
9751        }
9752
9753        static OriginInfo fromStagedFile(File file) {
9754            return new OriginInfo(file, null, true, false);
9755        }
9756
9757        static OriginInfo fromStagedContainer(String cid) {
9758            return new OriginInfo(null, cid, true, false);
9759        }
9760
9761        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
9762            this.file = file;
9763            this.cid = cid;
9764            this.staged = staged;
9765            this.existing = existing;
9766
9767            if (cid != null) {
9768                resolvedPath = PackageHelper.getSdDir(cid);
9769                resolvedFile = new File(resolvedPath);
9770            } else if (file != null) {
9771                resolvedPath = file.getAbsolutePath();
9772                resolvedFile = file;
9773            } else {
9774                resolvedPath = null;
9775                resolvedFile = null;
9776            }
9777        }
9778    }
9779
9780    class MoveInfo {
9781        final int moveId;
9782        final String fromUuid;
9783        final String toUuid;
9784        final String packageName;
9785        final String dataAppName;
9786        final int appId;
9787        final String seinfo;
9788
9789        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
9790                String dataAppName, int appId, String seinfo) {
9791            this.moveId = moveId;
9792            this.fromUuid = fromUuid;
9793            this.toUuid = toUuid;
9794            this.packageName = packageName;
9795            this.dataAppName = dataAppName;
9796            this.appId = appId;
9797            this.seinfo = seinfo;
9798        }
9799    }
9800
9801    class InstallParams extends HandlerParams {
9802        final OriginInfo origin;
9803        final MoveInfo move;
9804        final IPackageInstallObserver2 observer;
9805        int installFlags;
9806        final String installerPackageName;
9807        final String volumeUuid;
9808        final VerificationParams verificationParams;
9809        private InstallArgs mArgs;
9810        private int mRet;
9811        final String packageAbiOverride;
9812
9813        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
9814                int installFlags, String installerPackageName, String volumeUuid,
9815                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
9816            super(user);
9817            this.origin = origin;
9818            this.move = move;
9819            this.observer = observer;
9820            this.installFlags = installFlags;
9821            this.installerPackageName = installerPackageName;
9822            this.volumeUuid = volumeUuid;
9823            this.verificationParams = verificationParams;
9824            this.packageAbiOverride = packageAbiOverride;
9825        }
9826
9827        @Override
9828        public String toString() {
9829            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
9830                    + " file=" + origin.file + " cid=" + origin.cid + "}";
9831        }
9832
9833        public ManifestDigest getManifestDigest() {
9834            if (verificationParams == null) {
9835                return null;
9836            }
9837            return verificationParams.getManifestDigest();
9838        }
9839
9840        private int installLocationPolicy(PackageInfoLite pkgLite) {
9841            String packageName = pkgLite.packageName;
9842            int installLocation = pkgLite.installLocation;
9843            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9844            // reader
9845            synchronized (mPackages) {
9846                PackageParser.Package pkg = mPackages.get(packageName);
9847                if (pkg != null) {
9848                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
9849                        // Check for downgrading.
9850                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
9851                            try {
9852                                checkDowngrade(pkg, pkgLite);
9853                            } catch (PackageManagerException e) {
9854                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
9855                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
9856                            }
9857                        }
9858                        // Check for updated system application.
9859                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9860                            if (onSd) {
9861                                Slog.w(TAG, "Cannot install update to system app on sdcard");
9862                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
9863                            }
9864                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9865                        } else {
9866                            if (onSd) {
9867                                // Install flag overrides everything.
9868                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9869                            }
9870                            // If current upgrade specifies particular preference
9871                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
9872                                // Application explicitly specified internal.
9873                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9874                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
9875                                // App explictly prefers external. Let policy decide
9876                            } else {
9877                                // Prefer previous location
9878                                if (isExternal(pkg)) {
9879                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9880                                }
9881                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9882                            }
9883                        }
9884                    } else {
9885                        // Invalid install. Return error code
9886                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
9887                    }
9888                }
9889            }
9890            // All the special cases have been taken care of.
9891            // Return result based on recommended install location.
9892            if (onSd) {
9893                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9894            }
9895            return pkgLite.recommendedInstallLocation;
9896        }
9897
9898        /*
9899         * Invoke remote method to get package information and install
9900         * location values. Override install location based on default
9901         * policy if needed and then create install arguments based
9902         * on the install location.
9903         */
9904        public void handleStartCopy() throws RemoteException {
9905            int ret = PackageManager.INSTALL_SUCCEEDED;
9906
9907            // If we're already staged, we've firmly committed to an install location
9908            if (origin.staged) {
9909                if (origin.file != null) {
9910                    installFlags |= PackageManager.INSTALL_INTERNAL;
9911                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
9912                } else if (origin.cid != null) {
9913                    installFlags |= PackageManager.INSTALL_EXTERNAL;
9914                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
9915                } else {
9916                    throw new IllegalStateException("Invalid stage location");
9917                }
9918            }
9919
9920            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9921            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
9922
9923            PackageInfoLite pkgLite = null;
9924
9925            if (onInt && onSd) {
9926                // Check if both bits are set.
9927                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
9928                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9929            } else {
9930                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
9931                        packageAbiOverride);
9932
9933                /*
9934                 * If we have too little free space, try to free cache
9935                 * before giving up.
9936                 */
9937                if (!origin.staged && pkgLite.recommendedInstallLocation
9938                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9939                    // TODO: focus freeing disk space on the target device
9940                    final StorageManager storage = StorageManager.from(mContext);
9941                    final long lowThreshold = storage.getStorageLowBytes(
9942                            Environment.getDataDirectory());
9943
9944                    final long sizeBytes = mContainerService.calculateInstalledSize(
9945                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
9946
9947                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
9948                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
9949                                installFlags, packageAbiOverride);
9950                    }
9951
9952                    /*
9953                     * The cache free must have deleted the file we
9954                     * downloaded to install.
9955                     *
9956                     * TODO: fix the "freeCache" call to not delete
9957                     *       the file we care about.
9958                     */
9959                    if (pkgLite.recommendedInstallLocation
9960                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9961                        pkgLite.recommendedInstallLocation
9962                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
9963                    }
9964                }
9965            }
9966
9967            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9968                int loc = pkgLite.recommendedInstallLocation;
9969                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
9970                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9971                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
9972                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9973                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9974                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9975                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
9976                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
9977                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9978                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
9979                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
9980                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
9981                } else {
9982                    // Override with defaults if needed.
9983                    loc = installLocationPolicy(pkgLite);
9984                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
9985                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
9986                    } else if (!onSd && !onInt) {
9987                        // Override install location with flags
9988                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
9989                            // Set the flag to install on external media.
9990                            installFlags |= PackageManager.INSTALL_EXTERNAL;
9991                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
9992                        } else {
9993                            // Make sure the flag for installing on external
9994                            // media is unset
9995                            installFlags |= PackageManager.INSTALL_INTERNAL;
9996                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
9997                        }
9998                    }
9999                }
10000            }
10001
10002            final InstallArgs args = createInstallArgs(this);
10003            mArgs = args;
10004
10005            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10006                 /*
10007                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10008                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10009                 */
10010                int userIdentifier = getUser().getIdentifier();
10011                if (userIdentifier == UserHandle.USER_ALL
10012                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10013                    userIdentifier = UserHandle.USER_OWNER;
10014                }
10015
10016                /*
10017                 * Determine if we have any installed package verifiers. If we
10018                 * do, then we'll defer to them to verify the packages.
10019                 */
10020                final int requiredUid = mRequiredVerifierPackage == null ? -1
10021                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10022                if (!origin.existing && requiredUid != -1
10023                        && isVerificationEnabled(userIdentifier, installFlags)) {
10024                    final Intent verification = new Intent(
10025                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10026                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10027                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10028                            PACKAGE_MIME_TYPE);
10029                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10030
10031                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10032                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10033                            0 /* TODO: Which userId? */);
10034
10035                    if (DEBUG_VERIFY) {
10036                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10037                                + verification.toString() + " with " + pkgLite.verifiers.length
10038                                + " optional verifiers");
10039                    }
10040
10041                    final int verificationId = mPendingVerificationToken++;
10042
10043                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10044
10045                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10046                            installerPackageName);
10047
10048                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10049                            installFlags);
10050
10051                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10052                            pkgLite.packageName);
10053
10054                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10055                            pkgLite.versionCode);
10056
10057                    if (verificationParams != null) {
10058                        if (verificationParams.getVerificationURI() != null) {
10059                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10060                                 verificationParams.getVerificationURI());
10061                        }
10062                        if (verificationParams.getOriginatingURI() != null) {
10063                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10064                                  verificationParams.getOriginatingURI());
10065                        }
10066                        if (verificationParams.getReferrer() != null) {
10067                            verification.putExtra(Intent.EXTRA_REFERRER,
10068                                  verificationParams.getReferrer());
10069                        }
10070                        if (verificationParams.getOriginatingUid() >= 0) {
10071                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10072                                  verificationParams.getOriginatingUid());
10073                        }
10074                        if (verificationParams.getInstallerUid() >= 0) {
10075                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10076                                  verificationParams.getInstallerUid());
10077                        }
10078                    }
10079
10080                    final PackageVerificationState verificationState = new PackageVerificationState(
10081                            requiredUid, args);
10082
10083                    mPendingVerification.append(verificationId, verificationState);
10084
10085                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10086                            receivers, verificationState);
10087
10088                    /*
10089                     * If any sufficient verifiers were listed in the package
10090                     * manifest, attempt to ask them.
10091                     */
10092                    if (sufficientVerifiers != null) {
10093                        final int N = sufficientVerifiers.size();
10094                        if (N == 0) {
10095                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10096                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10097                        } else {
10098                            for (int i = 0; i < N; i++) {
10099                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10100
10101                                final Intent sufficientIntent = new Intent(verification);
10102                                sufficientIntent.setComponent(verifierComponent);
10103
10104                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
10105                            }
10106                        }
10107                    }
10108
10109                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10110                            mRequiredVerifierPackage, receivers);
10111                    if (ret == PackageManager.INSTALL_SUCCEEDED
10112                            && mRequiredVerifierPackage != null) {
10113                        /*
10114                         * Send the intent to the required verification agent,
10115                         * but only start the verification timeout after the
10116                         * target BroadcastReceivers have run.
10117                         */
10118                        verification.setComponent(requiredVerifierComponent);
10119                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
10120                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10121                                new BroadcastReceiver() {
10122                                    @Override
10123                                    public void onReceive(Context context, Intent intent) {
10124                                        final Message msg = mHandler
10125                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10126                                        msg.arg1 = verificationId;
10127                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10128                                    }
10129                                }, null, 0, null, null);
10130
10131                        /*
10132                         * We don't want the copy to proceed until verification
10133                         * succeeds, so null out this field.
10134                         */
10135                        mArgs = null;
10136                    }
10137                } else {
10138                    /*
10139                     * No package verification is enabled, so immediately start
10140                     * the remote call to initiate copy using temporary file.
10141                     */
10142                    ret = args.copyApk(mContainerService, true);
10143                }
10144            }
10145
10146            mRet = ret;
10147        }
10148
10149        @Override
10150        void handleReturnCode() {
10151            // If mArgs is null, then MCS couldn't be reached. When it
10152            // reconnects, it will try again to install. At that point, this
10153            // will succeed.
10154            if (mArgs != null) {
10155                processPendingInstall(mArgs, mRet);
10156            }
10157        }
10158
10159        @Override
10160        void handleServiceError() {
10161            mArgs = createInstallArgs(this);
10162            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10163        }
10164
10165        public boolean isForwardLocked() {
10166            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10167        }
10168    }
10169
10170    /**
10171     * Used during creation of InstallArgs
10172     *
10173     * @param installFlags package installation flags
10174     * @return true if should be installed on external storage
10175     */
10176    private static boolean installOnExternalAsec(int installFlags) {
10177        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10178            return false;
10179        }
10180        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10181            return true;
10182        }
10183        return false;
10184    }
10185
10186    /**
10187     * Used during creation of InstallArgs
10188     *
10189     * @param installFlags package installation flags
10190     * @return true if should be installed as forward locked
10191     */
10192    private static boolean installForwardLocked(int installFlags) {
10193        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10194    }
10195
10196    private InstallArgs createInstallArgs(InstallParams params) {
10197        if (params.move != null) {
10198            return new MoveInstallArgs(params);
10199        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10200            return new AsecInstallArgs(params);
10201        } else {
10202            return new FileInstallArgs(params);
10203        }
10204    }
10205
10206    /**
10207     * Create args that describe an existing installed package. Typically used
10208     * when cleaning up old installs, or used as a move source.
10209     */
10210    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10211            String resourcePath, String[] instructionSets) {
10212        final boolean isInAsec;
10213        if (installOnExternalAsec(installFlags)) {
10214            /* Apps on SD card are always in ASEC containers. */
10215            isInAsec = true;
10216        } else if (installForwardLocked(installFlags)
10217                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10218            /*
10219             * Forward-locked apps are only in ASEC containers if they're the
10220             * new style
10221             */
10222            isInAsec = true;
10223        } else {
10224            isInAsec = false;
10225        }
10226
10227        if (isInAsec) {
10228            return new AsecInstallArgs(codePath, instructionSets,
10229                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10230        } else {
10231            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10232        }
10233    }
10234
10235    static abstract class InstallArgs {
10236        /** @see InstallParams#origin */
10237        final OriginInfo origin;
10238        /** @see InstallParams#move */
10239        final MoveInfo move;
10240
10241        final IPackageInstallObserver2 observer;
10242        // Always refers to PackageManager flags only
10243        final int installFlags;
10244        final String installerPackageName;
10245        final String volumeUuid;
10246        final ManifestDigest manifestDigest;
10247        final UserHandle user;
10248        final String abiOverride;
10249
10250        // The list of instruction sets supported by this app. This is currently
10251        // only used during the rmdex() phase to clean up resources. We can get rid of this
10252        // if we move dex files under the common app path.
10253        /* nullable */ String[] instructionSets;
10254
10255        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10256                int installFlags, String installerPackageName, String volumeUuid,
10257                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10258                String abiOverride) {
10259            this.origin = origin;
10260            this.move = move;
10261            this.installFlags = installFlags;
10262            this.observer = observer;
10263            this.installerPackageName = installerPackageName;
10264            this.volumeUuid = volumeUuid;
10265            this.manifestDigest = manifestDigest;
10266            this.user = user;
10267            this.instructionSets = instructionSets;
10268            this.abiOverride = abiOverride;
10269        }
10270
10271        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10272        abstract int doPreInstall(int status);
10273
10274        /**
10275         * Rename package into final resting place. All paths on the given
10276         * scanned package should be updated to reflect the rename.
10277         */
10278        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10279        abstract int doPostInstall(int status, int uid);
10280
10281        /** @see PackageSettingBase#codePathString */
10282        abstract String getCodePath();
10283        /** @see PackageSettingBase#resourcePathString */
10284        abstract String getResourcePath();
10285
10286        // Need installer lock especially for dex file removal.
10287        abstract void cleanUpResourcesLI();
10288        abstract boolean doPostDeleteLI(boolean delete);
10289
10290        /**
10291         * Called before the source arguments are copied. This is used mostly
10292         * for MoveParams when it needs to read the source file to put it in the
10293         * destination.
10294         */
10295        int doPreCopy() {
10296            return PackageManager.INSTALL_SUCCEEDED;
10297        }
10298
10299        /**
10300         * Called after the source arguments are copied. This is used mostly for
10301         * MoveParams when it needs to read the source file to put it in the
10302         * destination.
10303         *
10304         * @return
10305         */
10306        int doPostCopy(int uid) {
10307            return PackageManager.INSTALL_SUCCEEDED;
10308        }
10309
10310        protected boolean isFwdLocked() {
10311            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10312        }
10313
10314        protected boolean isExternalAsec() {
10315            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10316        }
10317
10318        UserHandle getUser() {
10319            return user;
10320        }
10321    }
10322
10323    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10324        if (!allCodePaths.isEmpty()) {
10325            if (instructionSets == null) {
10326                throw new IllegalStateException("instructionSet == null");
10327            }
10328            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10329            for (String codePath : allCodePaths) {
10330                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10331                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10332                    if (retCode < 0) {
10333                        Slog.w(TAG, "Couldn't remove dex file for package: "
10334                                + " at location " + codePath + ", retcode=" + retCode);
10335                        // we don't consider this to be a failure of the core package deletion
10336                    }
10337                }
10338            }
10339        }
10340    }
10341
10342    /**
10343     * Logic to handle installation of non-ASEC applications, including copying
10344     * and renaming logic.
10345     */
10346    class FileInstallArgs extends InstallArgs {
10347        private File codeFile;
10348        private File resourceFile;
10349
10350        // Example topology:
10351        // /data/app/com.example/base.apk
10352        // /data/app/com.example/split_foo.apk
10353        // /data/app/com.example/lib/arm/libfoo.so
10354        // /data/app/com.example/lib/arm64/libfoo.so
10355        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10356
10357        /** New install */
10358        FileInstallArgs(InstallParams params) {
10359            super(params.origin, params.move, params.observer, params.installFlags,
10360                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10361                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10362            if (isFwdLocked()) {
10363                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10364            }
10365        }
10366
10367        /** Existing install */
10368        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10369            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10370                    null);
10371            this.codeFile = (codePath != null) ? new File(codePath) : null;
10372            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10373        }
10374
10375        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10376            if (origin.staged) {
10377                Slog.d(TAG, origin.file + " already staged; skipping copy");
10378                codeFile = origin.file;
10379                resourceFile = origin.file;
10380                return PackageManager.INSTALL_SUCCEEDED;
10381            }
10382
10383            try {
10384                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10385                codeFile = tempDir;
10386                resourceFile = tempDir;
10387            } catch (IOException e) {
10388                Slog.w(TAG, "Failed to create copy file: " + e);
10389                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10390            }
10391
10392            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10393                @Override
10394                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10395                    if (!FileUtils.isValidExtFilename(name)) {
10396                        throw new IllegalArgumentException("Invalid filename: " + name);
10397                    }
10398                    try {
10399                        final File file = new File(codeFile, name);
10400                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10401                                O_RDWR | O_CREAT, 0644);
10402                        Os.chmod(file.getAbsolutePath(), 0644);
10403                        return new ParcelFileDescriptor(fd);
10404                    } catch (ErrnoException e) {
10405                        throw new RemoteException("Failed to open: " + e.getMessage());
10406                    }
10407                }
10408            };
10409
10410            int ret = PackageManager.INSTALL_SUCCEEDED;
10411            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10412            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10413                Slog.e(TAG, "Failed to copy package");
10414                return ret;
10415            }
10416
10417            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10418            NativeLibraryHelper.Handle handle = null;
10419            try {
10420                handle = NativeLibraryHelper.Handle.create(codeFile);
10421                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10422                        abiOverride);
10423            } catch (IOException e) {
10424                Slog.e(TAG, "Copying native libraries failed", e);
10425                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10426            } finally {
10427                IoUtils.closeQuietly(handle);
10428            }
10429
10430            return ret;
10431        }
10432
10433        int doPreInstall(int status) {
10434            if (status != PackageManager.INSTALL_SUCCEEDED) {
10435                cleanUp();
10436            }
10437            return status;
10438        }
10439
10440        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10441            if (status != PackageManager.INSTALL_SUCCEEDED) {
10442                cleanUp();
10443                return false;
10444            }
10445
10446            final File targetDir = codeFile.getParentFile();
10447            final File beforeCodeFile = codeFile;
10448            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10449
10450            Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10451            try {
10452                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10453            } catch (ErrnoException e) {
10454                Slog.d(TAG, "Failed to rename", e);
10455                return false;
10456            }
10457
10458            if (!SELinux.restoreconRecursive(afterCodeFile)) {
10459                Slog.d(TAG, "Failed to restorecon");
10460                return false;
10461            }
10462
10463            // Reflect the rename internally
10464            codeFile = afterCodeFile;
10465            resourceFile = afterCodeFile;
10466
10467            // Reflect the rename in scanned details
10468            pkg.codePath = afterCodeFile.getAbsolutePath();
10469            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10470                    pkg.baseCodePath);
10471            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10472                    pkg.splitCodePaths);
10473
10474            // Reflect the rename in app info
10475            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10476            pkg.applicationInfo.setCodePath(pkg.codePath);
10477            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10478            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10479            pkg.applicationInfo.setResourcePath(pkg.codePath);
10480            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10481            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10482
10483            return true;
10484        }
10485
10486        int doPostInstall(int status, int uid) {
10487            if (status != PackageManager.INSTALL_SUCCEEDED) {
10488                cleanUp();
10489            }
10490            return status;
10491        }
10492
10493        @Override
10494        String getCodePath() {
10495            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10496        }
10497
10498        @Override
10499        String getResourcePath() {
10500            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10501        }
10502
10503        private boolean cleanUp() {
10504            if (codeFile == null || !codeFile.exists()) {
10505                return false;
10506            }
10507
10508            if (codeFile.isDirectory()) {
10509                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10510            } else {
10511                codeFile.delete();
10512            }
10513
10514            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10515                resourceFile.delete();
10516            }
10517
10518            return true;
10519        }
10520
10521        void cleanUpResourcesLI() {
10522            // Try enumerating all code paths before deleting
10523            List<String> allCodePaths = Collections.EMPTY_LIST;
10524            if (codeFile != null && codeFile.exists()) {
10525                try {
10526                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10527                    allCodePaths = pkg.getAllCodePaths();
10528                } catch (PackageParserException e) {
10529                    // Ignored; we tried our best
10530                }
10531            }
10532
10533            cleanUp();
10534            removeDexFiles(allCodePaths, instructionSets);
10535        }
10536
10537        boolean doPostDeleteLI(boolean delete) {
10538            // XXX err, shouldn't we respect the delete flag?
10539            cleanUpResourcesLI();
10540            return true;
10541        }
10542    }
10543
10544    private boolean isAsecExternal(String cid) {
10545        final String asecPath = PackageHelper.getSdFilesystem(cid);
10546        return !asecPath.startsWith(mAsecInternalPath);
10547    }
10548
10549    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
10550            PackageManagerException {
10551        if (copyRet < 0) {
10552            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
10553                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
10554                throw new PackageManagerException(copyRet, message);
10555            }
10556        }
10557    }
10558
10559    /**
10560     * Extract the MountService "container ID" from the full code path of an
10561     * .apk.
10562     */
10563    static String cidFromCodePath(String fullCodePath) {
10564        int eidx = fullCodePath.lastIndexOf("/");
10565        String subStr1 = fullCodePath.substring(0, eidx);
10566        int sidx = subStr1.lastIndexOf("/");
10567        return subStr1.substring(sidx+1, eidx);
10568    }
10569
10570    /**
10571     * Logic to handle installation of ASEC applications, including copying and
10572     * renaming logic.
10573     */
10574    class AsecInstallArgs extends InstallArgs {
10575        static final String RES_FILE_NAME = "pkg.apk";
10576        static final String PUBLIC_RES_FILE_NAME = "res.zip";
10577
10578        String cid;
10579        String packagePath;
10580        String resourcePath;
10581
10582        /** New install */
10583        AsecInstallArgs(InstallParams params) {
10584            super(params.origin, params.move, params.observer, params.installFlags,
10585                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10586                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10587        }
10588
10589        /** Existing install */
10590        AsecInstallArgs(String fullCodePath, String[] instructionSets,
10591                        boolean isExternal, boolean isForwardLocked) {
10592            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
10593                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10594                    instructionSets, null);
10595            // Hackily pretend we're still looking at a full code path
10596            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
10597                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
10598            }
10599
10600            // Extract cid from fullCodePath
10601            int eidx = fullCodePath.lastIndexOf("/");
10602            String subStr1 = fullCodePath.substring(0, eidx);
10603            int sidx = subStr1.lastIndexOf("/");
10604            cid = subStr1.substring(sidx+1, eidx);
10605            setMountPath(subStr1);
10606        }
10607
10608        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
10609            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
10610                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10611                    instructionSets, null);
10612            this.cid = cid;
10613            setMountPath(PackageHelper.getSdDir(cid));
10614        }
10615
10616        void createCopyFile() {
10617            cid = mInstallerService.allocateExternalStageCidLegacy();
10618        }
10619
10620        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10621            if (origin.staged) {
10622                Slog.d(TAG, origin.cid + " already staged; skipping copy");
10623                cid = origin.cid;
10624                setMountPath(PackageHelper.getSdDir(cid));
10625                return PackageManager.INSTALL_SUCCEEDED;
10626            }
10627
10628            if (temp) {
10629                createCopyFile();
10630            } else {
10631                /*
10632                 * Pre-emptively destroy the container since it's destroyed if
10633                 * copying fails due to it existing anyway.
10634                 */
10635                PackageHelper.destroySdDir(cid);
10636            }
10637
10638            final String newMountPath = imcs.copyPackageToContainer(
10639                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
10640                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
10641
10642            if (newMountPath != null) {
10643                setMountPath(newMountPath);
10644                return PackageManager.INSTALL_SUCCEEDED;
10645            } else {
10646                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10647            }
10648        }
10649
10650        @Override
10651        String getCodePath() {
10652            return packagePath;
10653        }
10654
10655        @Override
10656        String getResourcePath() {
10657            return resourcePath;
10658        }
10659
10660        int doPreInstall(int status) {
10661            if (status != PackageManager.INSTALL_SUCCEEDED) {
10662                // Destroy container
10663                PackageHelper.destroySdDir(cid);
10664            } else {
10665                boolean mounted = PackageHelper.isContainerMounted(cid);
10666                if (!mounted) {
10667                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
10668                            Process.SYSTEM_UID);
10669                    if (newMountPath != null) {
10670                        setMountPath(newMountPath);
10671                    } else {
10672                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10673                    }
10674                }
10675            }
10676            return status;
10677        }
10678
10679        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10680            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
10681            String newMountPath = null;
10682            if (PackageHelper.isContainerMounted(cid)) {
10683                // Unmount the container
10684                if (!PackageHelper.unMountSdDir(cid)) {
10685                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
10686                    return false;
10687                }
10688            }
10689            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10690                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
10691                        " which might be stale. Will try to clean up.");
10692                // Clean up the stale container and proceed to recreate.
10693                if (!PackageHelper.destroySdDir(newCacheId)) {
10694                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
10695                    return false;
10696                }
10697                // Successfully cleaned up stale container. Try to rename again.
10698                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10699                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
10700                            + " inspite of cleaning it up.");
10701                    return false;
10702                }
10703            }
10704            if (!PackageHelper.isContainerMounted(newCacheId)) {
10705                Slog.w(TAG, "Mounting container " + newCacheId);
10706                newMountPath = PackageHelper.mountSdDir(newCacheId,
10707                        getEncryptKey(), Process.SYSTEM_UID);
10708            } else {
10709                newMountPath = PackageHelper.getSdDir(newCacheId);
10710            }
10711            if (newMountPath == null) {
10712                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
10713                return false;
10714            }
10715            Log.i(TAG, "Succesfully renamed " + cid +
10716                    " to " + newCacheId +
10717                    " at new path: " + newMountPath);
10718            cid = newCacheId;
10719
10720            final File beforeCodeFile = new File(packagePath);
10721            setMountPath(newMountPath);
10722            final File afterCodeFile = new File(packagePath);
10723
10724            // Reflect the rename in scanned details
10725            pkg.codePath = afterCodeFile.getAbsolutePath();
10726            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10727                    pkg.baseCodePath);
10728            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10729                    pkg.splitCodePaths);
10730
10731            // Reflect the rename in app info
10732            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10733            pkg.applicationInfo.setCodePath(pkg.codePath);
10734            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10735            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10736            pkg.applicationInfo.setResourcePath(pkg.codePath);
10737            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10738            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10739
10740            return true;
10741        }
10742
10743        private void setMountPath(String mountPath) {
10744            final File mountFile = new File(mountPath);
10745
10746            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
10747            if (monolithicFile.exists()) {
10748                packagePath = monolithicFile.getAbsolutePath();
10749                if (isFwdLocked()) {
10750                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
10751                } else {
10752                    resourcePath = packagePath;
10753                }
10754            } else {
10755                packagePath = mountFile.getAbsolutePath();
10756                resourcePath = packagePath;
10757            }
10758        }
10759
10760        int doPostInstall(int status, int uid) {
10761            if (status != PackageManager.INSTALL_SUCCEEDED) {
10762                cleanUp();
10763            } else {
10764                final int groupOwner;
10765                final String protectedFile;
10766                if (isFwdLocked()) {
10767                    groupOwner = UserHandle.getSharedAppGid(uid);
10768                    protectedFile = RES_FILE_NAME;
10769                } else {
10770                    groupOwner = -1;
10771                    protectedFile = null;
10772                }
10773
10774                if (uid < Process.FIRST_APPLICATION_UID
10775                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
10776                    Slog.e(TAG, "Failed to finalize " + cid);
10777                    PackageHelper.destroySdDir(cid);
10778                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10779                }
10780
10781                boolean mounted = PackageHelper.isContainerMounted(cid);
10782                if (!mounted) {
10783                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
10784                }
10785            }
10786            return status;
10787        }
10788
10789        private void cleanUp() {
10790            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
10791
10792            // Destroy secure container
10793            PackageHelper.destroySdDir(cid);
10794        }
10795
10796        private List<String> getAllCodePaths() {
10797            final File codeFile = new File(getCodePath());
10798            if (codeFile != null && codeFile.exists()) {
10799                try {
10800                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10801                    return pkg.getAllCodePaths();
10802                } catch (PackageParserException e) {
10803                    // Ignored; we tried our best
10804                }
10805            }
10806            return Collections.EMPTY_LIST;
10807        }
10808
10809        void cleanUpResourcesLI() {
10810            // Enumerate all code paths before deleting
10811            cleanUpResourcesLI(getAllCodePaths());
10812        }
10813
10814        private void cleanUpResourcesLI(List<String> allCodePaths) {
10815            cleanUp();
10816            removeDexFiles(allCodePaths, instructionSets);
10817        }
10818
10819        String getPackageName() {
10820            return getAsecPackageName(cid);
10821        }
10822
10823        boolean doPostDeleteLI(boolean delete) {
10824            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
10825            final List<String> allCodePaths = getAllCodePaths();
10826            boolean mounted = PackageHelper.isContainerMounted(cid);
10827            if (mounted) {
10828                // Unmount first
10829                if (PackageHelper.unMountSdDir(cid)) {
10830                    mounted = false;
10831                }
10832            }
10833            if (!mounted && delete) {
10834                cleanUpResourcesLI(allCodePaths);
10835            }
10836            return !mounted;
10837        }
10838
10839        @Override
10840        int doPreCopy() {
10841            if (isFwdLocked()) {
10842                if (!PackageHelper.fixSdPermissions(cid,
10843                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
10844                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10845                }
10846            }
10847
10848            return PackageManager.INSTALL_SUCCEEDED;
10849        }
10850
10851        @Override
10852        int doPostCopy(int uid) {
10853            if (isFwdLocked()) {
10854                if (uid < Process.FIRST_APPLICATION_UID
10855                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
10856                                RES_FILE_NAME)) {
10857                    Slog.e(TAG, "Failed to finalize " + cid);
10858                    PackageHelper.destroySdDir(cid);
10859                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10860                }
10861            }
10862
10863            return PackageManager.INSTALL_SUCCEEDED;
10864        }
10865    }
10866
10867    /**
10868     * Logic to handle movement of existing installed applications.
10869     */
10870    class MoveInstallArgs extends InstallArgs {
10871        private File codeFile;
10872        private File resourceFile;
10873
10874        /** New install */
10875        MoveInstallArgs(InstallParams params) {
10876            super(params.origin, params.move, params.observer, params.installFlags,
10877                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10878                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10879        }
10880
10881        int copyApk(IMediaContainerService imcs, boolean temp) {
10882            Slog.d(TAG, "Moving " + move.packageName + " from " + move.fromUuid + " to "
10883                    + move.toUuid);
10884            synchronized (mInstaller) {
10885                if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
10886                        move.dataAppName, move.appId, move.seinfo) != 0) {
10887                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10888                }
10889            }
10890
10891            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
10892            resourceFile = codeFile;
10893            Slog.d(TAG, "codeFile after move is " + codeFile);
10894
10895            return PackageManager.INSTALL_SUCCEEDED;
10896        }
10897
10898        int doPreInstall(int status) {
10899            if (status != PackageManager.INSTALL_SUCCEEDED) {
10900                cleanUp();
10901            }
10902            return status;
10903        }
10904
10905        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10906            if (status != PackageManager.INSTALL_SUCCEEDED) {
10907                cleanUp();
10908                return false;
10909            }
10910
10911            // Reflect the move in app info
10912            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10913            pkg.applicationInfo.setCodePath(pkg.codePath);
10914            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10915            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10916            pkg.applicationInfo.setResourcePath(pkg.codePath);
10917            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10918            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10919
10920            return true;
10921        }
10922
10923        int doPostInstall(int status, int uid) {
10924            if (status != PackageManager.INSTALL_SUCCEEDED) {
10925                cleanUp();
10926            }
10927            return status;
10928        }
10929
10930        @Override
10931        String getCodePath() {
10932            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10933        }
10934
10935        @Override
10936        String getResourcePath() {
10937            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10938        }
10939
10940        private boolean cleanUp() {
10941            if (codeFile == null || !codeFile.exists()) {
10942                return false;
10943            }
10944
10945            if (codeFile.isDirectory()) {
10946                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10947            } else {
10948                codeFile.delete();
10949            }
10950
10951            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10952                resourceFile.delete();
10953            }
10954
10955            return true;
10956        }
10957
10958        void cleanUpResourcesLI() {
10959            cleanUp();
10960        }
10961
10962        boolean doPostDeleteLI(boolean delete) {
10963            // XXX err, shouldn't we respect the delete flag?
10964            cleanUpResourcesLI();
10965            return true;
10966        }
10967    }
10968
10969    static String getAsecPackageName(String packageCid) {
10970        int idx = packageCid.lastIndexOf("-");
10971        if (idx == -1) {
10972            return packageCid;
10973        }
10974        return packageCid.substring(0, idx);
10975    }
10976
10977    // Utility method used to create code paths based on package name and available index.
10978    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
10979        String idxStr = "";
10980        int idx = 1;
10981        // Fall back to default value of idx=1 if prefix is not
10982        // part of oldCodePath
10983        if (oldCodePath != null) {
10984            String subStr = oldCodePath;
10985            // Drop the suffix right away
10986            if (suffix != null && subStr.endsWith(suffix)) {
10987                subStr = subStr.substring(0, subStr.length() - suffix.length());
10988            }
10989            // If oldCodePath already contains prefix find out the
10990            // ending index to either increment or decrement.
10991            int sidx = subStr.lastIndexOf(prefix);
10992            if (sidx != -1) {
10993                subStr = subStr.substring(sidx + prefix.length());
10994                if (subStr != null) {
10995                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
10996                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
10997                    }
10998                    try {
10999                        idx = Integer.parseInt(subStr);
11000                        if (idx <= 1) {
11001                            idx++;
11002                        } else {
11003                            idx--;
11004                        }
11005                    } catch(NumberFormatException e) {
11006                    }
11007                }
11008            }
11009        }
11010        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11011        return prefix + idxStr;
11012    }
11013
11014    private File getNextCodePath(File targetDir, String packageName) {
11015        int suffix = 1;
11016        File result;
11017        do {
11018            result = new File(targetDir, packageName + "-" + suffix);
11019            suffix++;
11020        } while (result.exists());
11021        return result;
11022    }
11023
11024    // Utility method that returns the relative package path with respect
11025    // to the installation directory. Like say for /data/data/com.test-1.apk
11026    // string com.test-1 is returned.
11027    static String deriveCodePathName(String codePath) {
11028        if (codePath == null) {
11029            return null;
11030        }
11031        final File codeFile = new File(codePath);
11032        final String name = codeFile.getName();
11033        if (codeFile.isDirectory()) {
11034            return name;
11035        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11036            final int lastDot = name.lastIndexOf('.');
11037            return name.substring(0, lastDot);
11038        } else {
11039            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11040            return null;
11041        }
11042    }
11043
11044    class PackageInstalledInfo {
11045        String name;
11046        int uid;
11047        // The set of users that originally had this package installed.
11048        int[] origUsers;
11049        // The set of users that now have this package installed.
11050        int[] newUsers;
11051        PackageParser.Package pkg;
11052        int returnCode;
11053        String returnMsg;
11054        PackageRemovedInfo removedInfo;
11055
11056        public void setError(int code, String msg) {
11057            returnCode = code;
11058            returnMsg = msg;
11059            Slog.w(TAG, msg);
11060        }
11061
11062        public void setError(String msg, PackageParserException e) {
11063            returnCode = e.error;
11064            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11065            Slog.w(TAG, msg, e);
11066        }
11067
11068        public void setError(String msg, PackageManagerException e) {
11069            returnCode = e.error;
11070            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11071            Slog.w(TAG, msg, e);
11072        }
11073
11074        // In some error cases we want to convey more info back to the observer
11075        String origPackage;
11076        String origPermission;
11077    }
11078
11079    /*
11080     * Install a non-existing package.
11081     */
11082    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11083            UserHandle user, String installerPackageName, String volumeUuid,
11084            PackageInstalledInfo res) {
11085        // Remember this for later, in case we need to rollback this install
11086        String pkgName = pkg.packageName;
11087
11088        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11089        final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName,
11090                UserHandle.USER_OWNER).exists();
11091        synchronized(mPackages) {
11092            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11093                // A package with the same name is already installed, though
11094                // it has been renamed to an older name.  The package we
11095                // are trying to install should be installed as an update to
11096                // the existing one, but that has not been requested, so bail.
11097                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11098                        + " without first uninstalling package running as "
11099                        + mSettings.mRenamedPackages.get(pkgName));
11100                return;
11101            }
11102            if (mPackages.containsKey(pkgName)) {
11103                // Don't allow installation over an existing package with the same name.
11104                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11105                        + " without first uninstalling.");
11106                return;
11107            }
11108        }
11109
11110        try {
11111            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11112                    System.currentTimeMillis(), user);
11113
11114            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11115            // delete the partially installed application. the data directory will have to be
11116            // restored if it was already existing
11117            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11118                // remove package from internal structures.  Note that we want deletePackageX to
11119                // delete the package data and cache directories that it created in
11120                // scanPackageLocked, unless those directories existed before we even tried to
11121                // install.
11122                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11123                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11124                                res.removedInfo, true);
11125            }
11126
11127        } catch (PackageManagerException e) {
11128            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11129        }
11130    }
11131
11132    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11133        // Upgrade keysets are being used.  Determine if new package has a superset of the
11134        // required keys.
11135        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11136        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11137        for (int i = 0; i < upgradeKeySets.length; i++) {
11138            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11139            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
11140                return true;
11141            }
11142        }
11143        return false;
11144    }
11145
11146    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11147            UserHandle user, String installerPackageName, String volumeUuid,
11148            PackageInstalledInfo res) {
11149        final PackageParser.Package oldPackage;
11150        final String pkgName = pkg.packageName;
11151        final int[] allUsers;
11152        final boolean[] perUserInstalled;
11153        final boolean weFroze;
11154
11155        // First find the old package info and check signatures
11156        synchronized(mPackages) {
11157            oldPackage = mPackages.get(pkgName);
11158            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11159            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11160            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
11161                // default to original signature matching
11162                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11163                    != PackageManager.SIGNATURE_MATCH) {
11164                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11165                            "New package has a different signature: " + pkgName);
11166                    return;
11167                }
11168            } else {
11169                if(!checkUpgradeKeySetLP(ps, pkg)) {
11170                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11171                            "New package not signed by keys specified by upgrade-keysets: "
11172                            + pkgName);
11173                    return;
11174                }
11175            }
11176
11177            // In case of rollback, remember per-user/profile install state
11178            allUsers = sUserManager.getUserIds();
11179            perUserInstalled = new boolean[allUsers.length];
11180            for (int i = 0; i < allUsers.length; i++) {
11181                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11182            }
11183
11184            // Mark the app as frozen to prevent launching during the upgrade
11185            // process, and then kill all running instances
11186            if (!ps.frozen) {
11187                ps.frozen = true;
11188                weFroze = true;
11189            } else {
11190                weFroze = false;
11191            }
11192        }
11193
11194        // Now that we're guarded by frozen state, kill app during upgrade
11195        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11196
11197        try {
11198            boolean sysPkg = (isSystemApp(oldPackage));
11199            if (sysPkg) {
11200                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11201                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11202            } else {
11203                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11204                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11205            }
11206        } finally {
11207            // Regardless of success or failure of upgrade steps above, always
11208            // unfreeze the package if we froze it
11209            if (weFroze) {
11210                unfreezePackage(pkgName);
11211            }
11212        }
11213    }
11214
11215    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11216            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11217            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11218            String volumeUuid, PackageInstalledInfo res) {
11219        String pkgName = deletedPackage.packageName;
11220        boolean deletedPkg = true;
11221        boolean updatedSettings = false;
11222
11223        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11224                + deletedPackage);
11225        long origUpdateTime;
11226        if (pkg.mExtras != null) {
11227            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11228        } else {
11229            origUpdateTime = 0;
11230        }
11231
11232        // First delete the existing package while retaining the data directory
11233        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11234                res.removedInfo, true)) {
11235            // If the existing package wasn't successfully deleted
11236            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11237            deletedPkg = false;
11238        } else {
11239            // Successfully deleted the old package; proceed with replace.
11240
11241            // If deleted package lived in a container, give users a chance to
11242            // relinquish resources before killing.
11243            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11244                if (DEBUG_INSTALL) {
11245                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11246                }
11247                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11248                final ArrayList<String> pkgList = new ArrayList<String>(1);
11249                pkgList.add(deletedPackage.applicationInfo.packageName);
11250                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11251            }
11252
11253            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11254            try {
11255                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11256                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11257                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11258                        perUserInstalled, res, user);
11259                updatedSettings = true;
11260            } catch (PackageManagerException e) {
11261                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11262            }
11263        }
11264
11265        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11266            // remove package from internal structures.  Note that we want deletePackageX to
11267            // delete the package data and cache directories that it created in
11268            // scanPackageLocked, unless those directories existed before we even tried to
11269            // install.
11270            if(updatedSettings) {
11271                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11272                deletePackageLI(
11273                        pkgName, null, true, allUsers, perUserInstalled,
11274                        PackageManager.DELETE_KEEP_DATA,
11275                                res.removedInfo, true);
11276            }
11277            // Since we failed to install the new package we need to restore the old
11278            // package that we deleted.
11279            if (deletedPkg) {
11280                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11281                File restoreFile = new File(deletedPackage.codePath);
11282                // Parse old package
11283                boolean oldExternal = isExternal(deletedPackage);
11284                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11285                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11286                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11287                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11288                try {
11289                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11290                } catch (PackageManagerException e) {
11291                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11292                            + e.getMessage());
11293                    return;
11294                }
11295                // Restore of old package succeeded. Update permissions.
11296                // writer
11297                synchronized (mPackages) {
11298                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11299                            UPDATE_PERMISSIONS_ALL);
11300                    // can downgrade to reader
11301                    mSettings.writeLPr();
11302                }
11303                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11304            }
11305        }
11306    }
11307
11308    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11309            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11310            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11311            String volumeUuid, PackageInstalledInfo res) {
11312        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11313                + ", old=" + deletedPackage);
11314        boolean disabledSystem = false;
11315        boolean updatedSettings = false;
11316        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11317        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11318                != 0) {
11319            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11320        }
11321        String packageName = deletedPackage.packageName;
11322        if (packageName == null) {
11323            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11324                    "Attempt to delete null packageName.");
11325            return;
11326        }
11327        PackageParser.Package oldPkg;
11328        PackageSetting oldPkgSetting;
11329        // reader
11330        synchronized (mPackages) {
11331            oldPkg = mPackages.get(packageName);
11332            oldPkgSetting = mSettings.mPackages.get(packageName);
11333            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11334                    (oldPkgSetting == null)) {
11335                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11336                        "Couldn't find package:" + packageName + " information");
11337                return;
11338            }
11339        }
11340
11341        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11342        res.removedInfo.removedPackage = packageName;
11343        // Remove existing system package
11344        removePackageLI(oldPkgSetting, true);
11345        // writer
11346        synchronized (mPackages) {
11347            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11348            if (!disabledSystem && deletedPackage != null) {
11349                // We didn't need to disable the .apk as a current system package,
11350                // which means we are replacing another update that is already
11351                // installed.  We need to make sure to delete the older one's .apk.
11352                res.removedInfo.args = createInstallArgsForExisting(0,
11353                        deletedPackage.applicationInfo.getCodePath(),
11354                        deletedPackage.applicationInfo.getResourcePath(),
11355                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11356            } else {
11357                res.removedInfo.args = null;
11358            }
11359        }
11360
11361        // Successfully disabled the old package. Now proceed with re-installation
11362        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11363
11364        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11365        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11366
11367        PackageParser.Package newPackage = null;
11368        try {
11369            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11370            if (newPackage.mExtras != null) {
11371                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11372                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11373                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11374
11375                // is the update attempting to change shared user? that isn't going to work...
11376                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11377                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11378                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11379                            + " to " + newPkgSetting.sharedUser);
11380                    updatedSettings = true;
11381                }
11382            }
11383
11384            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11385                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11386                        perUserInstalled, res, user);
11387                updatedSettings = true;
11388            }
11389
11390        } catch (PackageManagerException e) {
11391            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11392        }
11393
11394        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11395            // Re installation failed. Restore old information
11396            // Remove new pkg information
11397            if (newPackage != null) {
11398                removeInstalledPackageLI(newPackage, true);
11399            }
11400            // Add back the old system package
11401            try {
11402                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11403            } catch (PackageManagerException e) {
11404                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11405            }
11406            // Restore the old system information in Settings
11407            synchronized (mPackages) {
11408                if (disabledSystem) {
11409                    mSettings.enableSystemPackageLPw(packageName);
11410                }
11411                if (updatedSettings) {
11412                    mSettings.setInstallerPackageName(packageName,
11413                            oldPkgSetting.installerPackageName);
11414                }
11415                mSettings.writeLPr();
11416            }
11417        }
11418    }
11419
11420    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
11421            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
11422            UserHandle user) {
11423        String pkgName = newPackage.packageName;
11424        synchronized (mPackages) {
11425            //write settings. the installStatus will be incomplete at this stage.
11426            //note that the new package setting would have already been
11427            //added to mPackages. It hasn't been persisted yet.
11428            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11429            mSettings.writeLPr();
11430        }
11431
11432        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11433
11434        synchronized (mPackages) {
11435            updatePermissionsLPw(newPackage.packageName, newPackage,
11436                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11437                            ? UPDATE_PERMISSIONS_ALL : 0));
11438            // For system-bundled packages, we assume that installing an upgraded version
11439            // of the package implies that the user actually wants to run that new code,
11440            // so we enable the package.
11441            PackageSetting ps = mSettings.mPackages.get(pkgName);
11442            if (ps != null) {
11443                if (isSystemApp(newPackage)) {
11444                    // NB: implicit assumption that system package upgrades apply to all users
11445                    if (DEBUG_INSTALL) {
11446                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
11447                    }
11448                    if (res.origUsers != null) {
11449                        for (int userHandle : res.origUsers) {
11450                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
11451                                    userHandle, installerPackageName);
11452                        }
11453                    }
11454                    // Also convey the prior install/uninstall state
11455                    if (allUsers != null && perUserInstalled != null) {
11456                        for (int i = 0; i < allUsers.length; i++) {
11457                            if (DEBUG_INSTALL) {
11458                                Slog.d(TAG, "    user " + allUsers[i]
11459                                        + " => " + perUserInstalled[i]);
11460                            }
11461                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
11462                        }
11463                        // these install state changes will be persisted in the
11464                        // upcoming call to mSettings.writeLPr().
11465                    }
11466                }
11467                // It's implied that when a user requests installation, they want the app to be
11468                // installed and enabled.
11469                int userId = user.getIdentifier();
11470                if (userId != UserHandle.USER_ALL) {
11471                    ps.setInstalled(true, userId);
11472                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
11473                }
11474            }
11475            res.name = pkgName;
11476            res.uid = newPackage.applicationInfo.uid;
11477            res.pkg = newPackage;
11478            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
11479            mSettings.setInstallerPackageName(pkgName, installerPackageName);
11480            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11481            //to update install status
11482            mSettings.writeLPr();
11483        }
11484    }
11485
11486    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
11487        final int installFlags = args.installFlags;
11488        final String installerPackageName = args.installerPackageName;
11489        final String volumeUuid = args.volumeUuid;
11490        final File tmpPackageFile = new File(args.getCodePath());
11491        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
11492        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
11493                || (args.volumeUuid != null));
11494        boolean replace = false;
11495        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
11496        // Result object to be returned
11497        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11498
11499        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
11500        // Retrieve PackageSettings and parse package
11501        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
11502                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
11503                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11504        PackageParser pp = new PackageParser();
11505        pp.setSeparateProcesses(mSeparateProcesses);
11506        pp.setDisplayMetrics(mMetrics);
11507
11508        final PackageParser.Package pkg;
11509        try {
11510            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
11511        } catch (PackageParserException e) {
11512            res.setError("Failed parse during installPackageLI", e);
11513            return;
11514        }
11515
11516        // Mark that we have an install time CPU ABI override.
11517        pkg.cpuAbiOverride = args.abiOverride;
11518
11519        String pkgName = res.name = pkg.packageName;
11520        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
11521            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
11522                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
11523                return;
11524            }
11525        }
11526
11527        try {
11528            pp.collectCertificates(pkg, parseFlags);
11529            pp.collectManifestDigest(pkg);
11530        } catch (PackageParserException e) {
11531            res.setError("Failed collect during installPackageLI", e);
11532            return;
11533        }
11534
11535        /* If the installer passed in a manifest digest, compare it now. */
11536        if (args.manifestDigest != null) {
11537            if (DEBUG_INSTALL) {
11538                final String parsedManifest = pkg.manifestDigest == null ? "null"
11539                        : pkg.manifestDigest.toString();
11540                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
11541                        + parsedManifest);
11542            }
11543
11544            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
11545                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
11546                return;
11547            }
11548        } else if (DEBUG_INSTALL) {
11549            final String parsedManifest = pkg.manifestDigest == null
11550                    ? "null" : pkg.manifestDigest.toString();
11551            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
11552        }
11553
11554        // Get rid of all references to package scan path via parser.
11555        pp = null;
11556        String oldCodePath = null;
11557        boolean systemApp = false;
11558        synchronized (mPackages) {
11559            // Check if installing already existing package
11560            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11561                String oldName = mSettings.mRenamedPackages.get(pkgName);
11562                if (pkg.mOriginalPackages != null
11563                        && pkg.mOriginalPackages.contains(oldName)
11564                        && mPackages.containsKey(oldName)) {
11565                    // This package is derived from an original package,
11566                    // and this device has been updating from that original
11567                    // name.  We must continue using the original name, so
11568                    // rename the new package here.
11569                    pkg.setPackageName(oldName);
11570                    pkgName = pkg.packageName;
11571                    replace = true;
11572                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
11573                            + oldName + " pkgName=" + pkgName);
11574                } else if (mPackages.containsKey(pkgName)) {
11575                    // This package, under its official name, already exists
11576                    // on the device; we should replace it.
11577                    replace = true;
11578                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
11579                }
11580
11581                // Prevent apps opting out from runtime permissions
11582                if (replace) {
11583                    PackageParser.Package oldPackage = mPackages.get(pkgName);
11584                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
11585                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
11586                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
11587                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
11588                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
11589                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
11590                                        + " doesn't support runtime permissions but the old"
11591                                        + " target SDK " + oldTargetSdk + " does.");
11592                        return;
11593                    }
11594                }
11595            }
11596
11597            PackageSetting ps = mSettings.mPackages.get(pkgName);
11598            if (ps != null) {
11599                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
11600
11601                // Quick sanity check that we're signed correctly if updating;
11602                // we'll check this again later when scanning, but we want to
11603                // bail early here before tripping over redefined permissions.
11604                if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
11605                    try {
11606                        verifySignaturesLP(ps, pkg);
11607                    } catch (PackageManagerException e) {
11608                        res.setError(e.error, e.getMessage());
11609                        return;
11610                    }
11611                } else {
11612                    if (!checkUpgradeKeySetLP(ps, pkg)) {
11613                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
11614                                + pkg.packageName + " upgrade keys do not match the "
11615                                + "previously installed version");
11616                        return;
11617                    }
11618                }
11619
11620                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
11621                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
11622                    systemApp = (ps.pkg.applicationInfo.flags &
11623                            ApplicationInfo.FLAG_SYSTEM) != 0;
11624                }
11625                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11626            }
11627
11628            // Check whether the newly-scanned package wants to define an already-defined perm
11629            int N = pkg.permissions.size();
11630            for (int i = N-1; i >= 0; i--) {
11631                PackageParser.Permission perm = pkg.permissions.get(i);
11632                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
11633                if (bp != null) {
11634                    // If the defining package is signed with our cert, it's okay.  This
11635                    // also includes the "updating the same package" case, of course.
11636                    // "updating same package" could also involve key-rotation.
11637                    final boolean sigsOk;
11638                    if (!bp.sourcePackage.equals(pkg.packageName)
11639                            || !(bp.packageSetting instanceof PackageSetting)
11640                            || !bp.packageSetting.keySetData.isUsingUpgradeKeySets()
11641                            || ((PackageSetting) bp.packageSetting).sharedUser != null) {
11642                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
11643                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
11644                    } else {
11645                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
11646                    }
11647                    if (!sigsOk) {
11648                        // If the owning package is the system itself, we log but allow
11649                        // install to proceed; we fail the install on all other permission
11650                        // redefinitions.
11651                        if (!bp.sourcePackage.equals("android")) {
11652                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
11653                                    + pkg.packageName + " attempting to redeclare permission "
11654                                    + perm.info.name + " already owned by " + bp.sourcePackage);
11655                            res.origPermission = perm.info.name;
11656                            res.origPackage = bp.sourcePackage;
11657                            return;
11658                        } else {
11659                            Slog.w(TAG, "Package " + pkg.packageName
11660                                    + " attempting to redeclare system permission "
11661                                    + perm.info.name + "; ignoring new declaration");
11662                            pkg.permissions.remove(i);
11663                        }
11664                    }
11665                }
11666            }
11667
11668        }
11669
11670        if (systemApp && onExternal) {
11671            // Disable updates to system apps on sdcard
11672            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11673                    "Cannot install updates to system apps on sdcard");
11674            return;
11675        }
11676
11677        if (args.move != null) {
11678            // We did an in-place move, so dex is ready to roll
11679            scanFlags |= SCAN_NO_DEX;
11680            scanFlags |= SCAN_MOVE;
11681        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
11682            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
11683            scanFlags |= SCAN_NO_DEX;
11684
11685            try {
11686                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
11687                        true /* extract libs */);
11688            } catch (PackageManagerException pme) {
11689                Slog.e(TAG, "Error deriving application ABI", pme);
11690                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
11691                return;
11692            }
11693
11694            // Run dexopt before old package gets removed, to minimize time when app is unavailable
11695            int result = mPackageDexOptimizer
11696                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
11697                            false /* defer */, false /* inclDependencies */);
11698            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
11699                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
11700                return;
11701            }
11702        }
11703
11704        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
11705            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
11706            return;
11707        }
11708
11709        startIntentFilterVerifications(args.user.getIdentifier(), pkg);
11710
11711        if (replace) {
11712            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
11713                    installerPackageName, volumeUuid, res);
11714        } else {
11715            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
11716                    args.user, installerPackageName, volumeUuid, res);
11717        }
11718        synchronized (mPackages) {
11719            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11720            if (ps != null) {
11721                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11722            }
11723        }
11724    }
11725
11726    private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) {
11727        if (mIntentFilterVerifierComponent == null) {
11728            Slog.d(TAG, "No IntentFilter verification will not be done as "
11729                    + "there is no IntentFilterVerifier available!");
11730            return;
11731        }
11732
11733        final int verifierUid = getPackageUid(
11734                mIntentFilterVerifierComponent.getPackageName(),
11735                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
11736
11737        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
11738        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
11739        msg.obj = pkg;
11740        msg.arg1 = userId;
11741        msg.arg2 = verifierUid;
11742
11743        mHandler.sendMessage(msg);
11744    }
11745
11746    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid,
11747            PackageParser.Package pkg) {
11748        int size = pkg.activities.size();
11749        if (size == 0) {
11750            Slog.d(TAG, "No activity, so no need to verify any IntentFilter!");
11751            return;
11752        }
11753
11754        final boolean hasDomainURLs = hasDomainURLs(pkg);
11755        if (!hasDomainURLs) {
11756            Slog.d(TAG, "No domain URLs, so no need to verify any IntentFilter!");
11757            return;
11758        }
11759
11760        Slog.d(TAG, "Checking for userId:" + userId + " if any IntentFilter from the " + size
11761                + " Activities needs verification ...");
11762
11763        final int verificationId = mIntentFilterVerificationToken++;
11764        int count = 0;
11765        final String packageName = pkg.packageName;
11766        ArrayList<String> allHosts = new ArrayList<>();
11767
11768        synchronized (mPackages) {
11769            for (PackageParser.Activity a : pkg.activities) {
11770                for (ActivityIntentInfo filter : a.intents) {
11771                    boolean needsFilterVerification = filter.needsVerification();
11772                    if (needsFilterVerification && needsNetworkVerificationLPr(filter)) {
11773                        Slog.d(TAG, "Verification needed for IntentFilter:" + filter.toString());
11774                        mIntentFilterVerifier.addOneIntentFilterVerification(
11775                                verifierUid, userId, verificationId, filter, packageName);
11776                        count++;
11777                    } else if (!needsFilterVerification) {
11778                        Slog.d(TAG, "No verification needed for IntentFilter:" + filter.toString());
11779                        if (hasValidDomains(filter)) {
11780                            ArrayList<String> hosts = filter.getHostsList();
11781                            if (hosts.size() > 0) {
11782                                allHosts.addAll(hosts);
11783                            } else {
11784                                if (allHosts.isEmpty()) {
11785                                    allHosts.add("*");
11786                                }
11787                            }
11788                        }
11789                    } else {
11790                        Slog.d(TAG, "Verification already done for IntentFilter:"
11791                                + filter.toString());
11792                    }
11793                }
11794            }
11795        }
11796
11797        if (count > 0) {
11798            mIntentFilterVerifier.startVerifications(userId);
11799            Slog.d(TAG, "Started " + count + " IntentFilter verification"
11800                    + (count > 1 ? "s" : "") +  " for userId:" + userId + "!");
11801        } else {
11802            Slog.d(TAG, "No need to start any IntentFilter verification!");
11803            if (allHosts.size() > 0 && mSettings.createIntentFilterVerificationIfNeededLPw(
11804                    packageName, allHosts) != null) {
11805                scheduleWriteSettingsLocked();
11806            }
11807        }
11808    }
11809
11810    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
11811        final ComponentName cn  = filter.activity.getComponentName();
11812        final String packageName = cn.getPackageName();
11813
11814        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
11815                packageName);
11816        if (ivi == null) {
11817            return true;
11818        }
11819        int status = ivi.getStatus();
11820        switch (status) {
11821            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
11822            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
11823                return true;
11824
11825            default:
11826                // Nothing to do
11827                return false;
11828        }
11829    }
11830
11831    private boolean isSystemComponentOrPersistentPrivApp(PackageParser.Package pkg) {
11832        return UserHandle.getAppId(pkg.applicationInfo.uid) < FIRST_APPLICATION_UID
11833                || ((pkg.applicationInfo.privateFlags
11834                        & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0
11835                && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0);
11836    }
11837
11838    private static boolean isMultiArch(PackageSetting ps) {
11839        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
11840    }
11841
11842    private static boolean isMultiArch(ApplicationInfo info) {
11843        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
11844    }
11845
11846    private static boolean isExternal(PackageParser.Package pkg) {
11847        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11848    }
11849
11850    private static boolean isExternal(PackageSetting ps) {
11851        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11852    }
11853
11854    private static boolean isExternal(ApplicationInfo info) {
11855        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11856    }
11857
11858    private static boolean isSystemApp(PackageParser.Package pkg) {
11859        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
11860    }
11861
11862    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
11863        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
11864    }
11865
11866    private static boolean hasDomainURLs(PackageParser.Package pkg) {
11867        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
11868    }
11869
11870    private static boolean isSystemApp(PackageSetting ps) {
11871        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
11872    }
11873
11874    private static boolean isUpdatedSystemApp(PackageSetting ps) {
11875        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
11876    }
11877
11878    private int packageFlagsToInstallFlags(PackageSetting ps) {
11879        int installFlags = 0;
11880        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
11881            // This existing package was an external ASEC install when we have
11882            // the external flag without a UUID
11883            installFlags |= PackageManager.INSTALL_EXTERNAL;
11884        }
11885        if (ps.isForwardLocked()) {
11886            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
11887        }
11888        return installFlags;
11889    }
11890
11891    private void deleteTempPackageFiles() {
11892        final FilenameFilter filter = new FilenameFilter() {
11893            public boolean accept(File dir, String name) {
11894                return name.startsWith("vmdl") && name.endsWith(".tmp");
11895            }
11896        };
11897        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
11898            file.delete();
11899        }
11900    }
11901
11902    @Override
11903    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
11904            int flags) {
11905        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
11906                flags);
11907    }
11908
11909    @Override
11910    public void deletePackage(final String packageName,
11911            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
11912        mContext.enforceCallingOrSelfPermission(
11913                android.Manifest.permission.DELETE_PACKAGES, null);
11914        final int uid = Binder.getCallingUid();
11915        if (UserHandle.getUserId(uid) != userId) {
11916            mContext.enforceCallingPermission(
11917                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
11918                    "deletePackage for user " + userId);
11919        }
11920        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
11921            try {
11922                observer.onPackageDeleted(packageName,
11923                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
11924            } catch (RemoteException re) {
11925            }
11926            return;
11927        }
11928
11929        boolean uninstallBlocked = false;
11930        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
11931            int[] users = sUserManager.getUserIds();
11932            for (int i = 0; i < users.length; ++i) {
11933                if (getBlockUninstallForUser(packageName, users[i])) {
11934                    uninstallBlocked = true;
11935                    break;
11936                }
11937            }
11938        } else {
11939            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
11940        }
11941        if (uninstallBlocked) {
11942            try {
11943                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
11944                        null);
11945            } catch (RemoteException re) {
11946            }
11947            return;
11948        }
11949
11950        if (DEBUG_REMOVE) {
11951            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
11952        }
11953        // Queue up an async operation since the package deletion may take a little while.
11954        mHandler.post(new Runnable() {
11955            public void run() {
11956                mHandler.removeCallbacks(this);
11957                final int returnCode = deletePackageX(packageName, userId, flags);
11958                if (observer != null) {
11959                    try {
11960                        observer.onPackageDeleted(packageName, returnCode, null);
11961                    } catch (RemoteException e) {
11962                        Log.i(TAG, "Observer no longer exists.");
11963                    } //end catch
11964                } //end if
11965            } //end run
11966        });
11967    }
11968
11969    private boolean isPackageDeviceAdmin(String packageName, int userId) {
11970        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
11971                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
11972        try {
11973            if (dpm != null) {
11974                if (dpm.isDeviceOwner(packageName)) {
11975                    return true;
11976                }
11977                int[] users;
11978                if (userId == UserHandle.USER_ALL) {
11979                    users = sUserManager.getUserIds();
11980                } else {
11981                    users = new int[]{userId};
11982                }
11983                for (int i = 0; i < users.length; ++i) {
11984                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
11985                        return true;
11986                    }
11987                }
11988            }
11989        } catch (RemoteException e) {
11990        }
11991        return false;
11992    }
11993
11994    /**
11995     *  This method is an internal method that could be get invoked either
11996     *  to delete an installed package or to clean up a failed installation.
11997     *  After deleting an installed package, a broadcast is sent to notify any
11998     *  listeners that the package has been installed. For cleaning up a failed
11999     *  installation, the broadcast is not necessary since the package's
12000     *  installation wouldn't have sent the initial broadcast either
12001     *  The key steps in deleting a package are
12002     *  deleting the package information in internal structures like mPackages,
12003     *  deleting the packages base directories through installd
12004     *  updating mSettings to reflect current status
12005     *  persisting settings for later use
12006     *  sending a broadcast if necessary
12007     */
12008    private int deletePackageX(String packageName, int userId, int flags) {
12009        final PackageRemovedInfo info = new PackageRemovedInfo();
12010        final boolean res;
12011
12012        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12013                ? UserHandle.ALL : new UserHandle(userId);
12014
12015        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12016            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12017            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12018        }
12019
12020        boolean removedForAllUsers = false;
12021        boolean systemUpdate = false;
12022
12023        // for the uninstall-updates case and restricted profiles, remember the per-
12024        // userhandle installed state
12025        int[] allUsers;
12026        boolean[] perUserInstalled;
12027        synchronized (mPackages) {
12028            PackageSetting ps = mSettings.mPackages.get(packageName);
12029            allUsers = sUserManager.getUserIds();
12030            perUserInstalled = new boolean[allUsers.length];
12031            for (int i = 0; i < allUsers.length; i++) {
12032                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12033            }
12034        }
12035
12036        synchronized (mInstallLock) {
12037            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12038            res = deletePackageLI(packageName, removeForUser,
12039                    true, allUsers, perUserInstalled,
12040                    flags | REMOVE_CHATTY, info, true);
12041            systemUpdate = info.isRemovedPackageSystemUpdate;
12042            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12043                removedForAllUsers = true;
12044            }
12045            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12046                    + " removedForAllUsers=" + removedForAllUsers);
12047        }
12048
12049        if (res) {
12050            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12051
12052            // If the removed package was a system update, the old system package
12053            // was re-enabled; we need to broadcast this information
12054            if (systemUpdate) {
12055                Bundle extras = new Bundle(1);
12056                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12057                        ? info.removedAppId : info.uid);
12058                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12059
12060                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12061                        extras, null, null, null);
12062                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12063                        extras, null, null, null);
12064                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12065                        null, packageName, null, null);
12066            }
12067        }
12068        // Force a gc here.
12069        Runtime.getRuntime().gc();
12070        // Delete the resources here after sending the broadcast to let
12071        // other processes clean up before deleting resources.
12072        if (info.args != null) {
12073            synchronized (mInstallLock) {
12074                info.args.doPostDeleteLI(true);
12075            }
12076        }
12077
12078        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12079    }
12080
12081    class PackageRemovedInfo {
12082        String removedPackage;
12083        int uid = -1;
12084        int removedAppId = -1;
12085        int[] removedUsers = null;
12086        boolean isRemovedPackageSystemUpdate = false;
12087        // Clean up resources deleted packages.
12088        InstallArgs args = null;
12089
12090        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12091            Bundle extras = new Bundle(1);
12092            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12093            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12094            if (replacing) {
12095                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12096            }
12097            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12098            if (removedPackage != null) {
12099                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12100                        extras, null, null, removedUsers);
12101                if (fullRemove && !replacing) {
12102                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12103                            extras, null, null, removedUsers);
12104                }
12105            }
12106            if (removedAppId >= 0) {
12107                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12108                        removedUsers);
12109            }
12110        }
12111    }
12112
12113    /*
12114     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12115     * flag is not set, the data directory is removed as well.
12116     * make sure this flag is set for partially installed apps. If not its meaningless to
12117     * delete a partially installed application.
12118     */
12119    private void removePackageDataLI(PackageSetting ps,
12120            int[] allUserHandles, boolean[] perUserInstalled,
12121            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12122        String packageName = ps.name;
12123        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12124        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12125        // Retrieve object to delete permissions for shared user later on
12126        final PackageSetting deletedPs;
12127        // reader
12128        synchronized (mPackages) {
12129            deletedPs = mSettings.mPackages.get(packageName);
12130            if (outInfo != null) {
12131                outInfo.removedPackage = packageName;
12132                outInfo.removedUsers = deletedPs != null
12133                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12134                        : null;
12135            }
12136        }
12137        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12138            removeDataDirsLI(ps.volumeUuid, packageName);
12139            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12140        }
12141        // writer
12142        synchronized (mPackages) {
12143            if (deletedPs != null) {
12144                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12145                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12146                    clearDefaultBrowserIfNeeded(packageName);
12147                    if (outInfo != null) {
12148                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12149                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12150                    }
12151                    updatePermissionsLPw(deletedPs.name, null, 0);
12152                    if (deletedPs.sharedUser != null) {
12153                        // Remove permissions associated with package. Since runtime
12154                        // permissions are per user we have to kill the removed package
12155                        // or packages running under the shared user of the removed
12156                        // package if revoking the permissions requested only by the removed
12157                        // package is successful and this causes a change in gids.
12158                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12159                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12160                                    userId);
12161                            if (userIdToKill == UserHandle.USER_ALL
12162                                    || userIdToKill >= UserHandle.USER_OWNER) {
12163                                // If gids changed for this user, kill all affected packages.
12164                                mHandler.post(new Runnable() {
12165                                    @Override
12166                                    public void run() {
12167                                        // This has to happen with no lock held.
12168                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12169                                                KILL_APP_REASON_GIDS_CHANGED);
12170                                    }
12171                                });
12172                            break;
12173                            }
12174                        }
12175                    }
12176                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12177                }
12178                // make sure to preserve per-user disabled state if this removal was just
12179                // a downgrade of a system app to the factory package
12180                if (allUserHandles != null && perUserInstalled != null) {
12181                    if (DEBUG_REMOVE) {
12182                        Slog.d(TAG, "Propagating install state across downgrade");
12183                    }
12184                    for (int i = 0; i < allUserHandles.length; i++) {
12185                        if (DEBUG_REMOVE) {
12186                            Slog.d(TAG, "    user " + allUserHandles[i]
12187                                    + " => " + perUserInstalled[i]);
12188                        }
12189                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12190                    }
12191                }
12192            }
12193            // can downgrade to reader
12194            if (writeSettings) {
12195                // Save settings now
12196                mSettings.writeLPr();
12197            }
12198        }
12199        if (outInfo != null) {
12200            // A user ID was deleted here. Go through all users and remove it
12201            // from KeyStore.
12202            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12203        }
12204    }
12205
12206    static boolean locationIsPrivileged(File path) {
12207        try {
12208            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12209                    .getCanonicalPath();
12210            return path.getCanonicalPath().startsWith(privilegedAppDir);
12211        } catch (IOException e) {
12212            Slog.e(TAG, "Unable to access code path " + path);
12213        }
12214        return false;
12215    }
12216
12217    /*
12218     * Tries to delete system package.
12219     */
12220    private boolean deleteSystemPackageLI(PackageSetting newPs,
12221            int[] allUserHandles, boolean[] perUserInstalled,
12222            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12223        final boolean applyUserRestrictions
12224                = (allUserHandles != null) && (perUserInstalled != null);
12225        PackageSetting disabledPs = null;
12226        // Confirm if the system package has been updated
12227        // An updated system app can be deleted. This will also have to restore
12228        // the system pkg from system partition
12229        // reader
12230        synchronized (mPackages) {
12231            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12232        }
12233        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12234                + " disabledPs=" + disabledPs);
12235        if (disabledPs == null) {
12236            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12237            return false;
12238        } else if (DEBUG_REMOVE) {
12239            Slog.d(TAG, "Deleting system pkg from data partition");
12240        }
12241        if (DEBUG_REMOVE) {
12242            if (applyUserRestrictions) {
12243                Slog.d(TAG, "Remembering install states:");
12244                for (int i = 0; i < allUserHandles.length; i++) {
12245                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12246                }
12247            }
12248        }
12249        // Delete the updated package
12250        outInfo.isRemovedPackageSystemUpdate = true;
12251        if (disabledPs.versionCode < newPs.versionCode) {
12252            // Delete data for downgrades
12253            flags &= ~PackageManager.DELETE_KEEP_DATA;
12254        } else {
12255            // Preserve data by setting flag
12256            flags |= PackageManager.DELETE_KEEP_DATA;
12257        }
12258        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12259                allUserHandles, perUserInstalled, outInfo, writeSettings);
12260        if (!ret) {
12261            return false;
12262        }
12263        // writer
12264        synchronized (mPackages) {
12265            // Reinstate the old system package
12266            mSettings.enableSystemPackageLPw(newPs.name);
12267            // Remove any native libraries from the upgraded package.
12268            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12269        }
12270        // Install the system package
12271        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12272        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12273        if (locationIsPrivileged(disabledPs.codePath)) {
12274            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12275        }
12276
12277        final PackageParser.Package newPkg;
12278        try {
12279            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12280        } catch (PackageManagerException e) {
12281            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12282            return false;
12283        }
12284
12285        // writer
12286        synchronized (mPackages) {
12287            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12288            updatePermissionsLPw(newPkg.packageName, newPkg,
12289                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12290            if (applyUserRestrictions) {
12291                if (DEBUG_REMOVE) {
12292                    Slog.d(TAG, "Propagating install state across reinstall");
12293                }
12294                for (int i = 0; i < allUserHandles.length; i++) {
12295                    if (DEBUG_REMOVE) {
12296                        Slog.d(TAG, "    user " + allUserHandles[i]
12297                                + " => " + perUserInstalled[i]);
12298                    }
12299                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12300                }
12301                // Regardless of writeSettings we need to ensure that this restriction
12302                // state propagation is persisted
12303                mSettings.writeAllUsersPackageRestrictionsLPr();
12304            }
12305            // can downgrade to reader here
12306            if (writeSettings) {
12307                mSettings.writeLPr();
12308            }
12309        }
12310        return true;
12311    }
12312
12313    private boolean deleteInstalledPackageLI(PackageSetting ps,
12314            boolean deleteCodeAndResources, int flags,
12315            int[] allUserHandles, boolean[] perUserInstalled,
12316            PackageRemovedInfo outInfo, boolean writeSettings) {
12317        if (outInfo != null) {
12318            outInfo.uid = ps.appId;
12319        }
12320
12321        // Delete package data from internal structures and also remove data if flag is set
12322        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12323
12324        // Delete application code and resources
12325        if (deleteCodeAndResources && (outInfo != null)) {
12326            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12327                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12328            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12329        }
12330        return true;
12331    }
12332
12333    @Override
12334    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12335            int userId) {
12336        mContext.enforceCallingOrSelfPermission(
12337                android.Manifest.permission.DELETE_PACKAGES, null);
12338        synchronized (mPackages) {
12339            PackageSetting ps = mSettings.mPackages.get(packageName);
12340            if (ps == null) {
12341                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12342                return false;
12343            }
12344            if (!ps.getInstalled(userId)) {
12345                // Can't block uninstall for an app that is not installed or enabled.
12346                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12347                return false;
12348            }
12349            ps.setBlockUninstall(blockUninstall, userId);
12350            mSettings.writePackageRestrictionsLPr(userId);
12351        }
12352        return true;
12353    }
12354
12355    @Override
12356    public boolean getBlockUninstallForUser(String packageName, int userId) {
12357        synchronized (mPackages) {
12358            PackageSetting ps = mSettings.mPackages.get(packageName);
12359            if (ps == null) {
12360                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
12361                return false;
12362            }
12363            return ps.getBlockUninstall(userId);
12364        }
12365    }
12366
12367    /*
12368     * This method handles package deletion in general
12369     */
12370    private boolean deletePackageLI(String packageName, UserHandle user,
12371            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
12372            int flags, PackageRemovedInfo outInfo,
12373            boolean writeSettings) {
12374        if (packageName == null) {
12375            Slog.w(TAG, "Attempt to delete null packageName.");
12376            return false;
12377        }
12378        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
12379        PackageSetting ps;
12380        boolean dataOnly = false;
12381        int removeUser = -1;
12382        int appId = -1;
12383        synchronized (mPackages) {
12384            ps = mSettings.mPackages.get(packageName);
12385            if (ps == null) {
12386                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12387                return false;
12388            }
12389            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
12390                    && user.getIdentifier() != UserHandle.USER_ALL) {
12391                // The caller is asking that the package only be deleted for a single
12392                // user.  To do this, we just mark its uninstalled state and delete
12393                // its data.  If this is a system app, we only allow this to happen if
12394                // they have set the special DELETE_SYSTEM_APP which requests different
12395                // semantics than normal for uninstalling system apps.
12396                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
12397                ps.setUserState(user.getIdentifier(),
12398                        COMPONENT_ENABLED_STATE_DEFAULT,
12399                        false, //installed
12400                        true,  //stopped
12401                        true,  //notLaunched
12402                        false, //hidden
12403                        null, null, null,
12404                        false, // blockUninstall
12405                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
12406                if (!isSystemApp(ps)) {
12407                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
12408                        // Other user still have this package installed, so all
12409                        // we need to do is clear this user's data and save that
12410                        // it is uninstalled.
12411                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
12412                        removeUser = user.getIdentifier();
12413                        appId = ps.appId;
12414                        scheduleWritePackageRestrictionsLocked(removeUser);
12415                    } else {
12416                        // We need to set it back to 'installed' so the uninstall
12417                        // broadcasts will be sent correctly.
12418                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
12419                        ps.setInstalled(true, user.getIdentifier());
12420                    }
12421                } else {
12422                    // This is a system app, so we assume that the
12423                    // other users still have this package installed, so all
12424                    // we need to do is clear this user's data and save that
12425                    // it is uninstalled.
12426                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
12427                    removeUser = user.getIdentifier();
12428                    appId = ps.appId;
12429                    scheduleWritePackageRestrictionsLocked(removeUser);
12430                }
12431            }
12432        }
12433
12434        if (removeUser >= 0) {
12435            // From above, we determined that we are deleting this only
12436            // for a single user.  Continue the work here.
12437            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
12438            if (outInfo != null) {
12439                outInfo.removedPackage = packageName;
12440                outInfo.removedAppId = appId;
12441                outInfo.removedUsers = new int[] {removeUser};
12442            }
12443            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
12444            removeKeystoreDataIfNeeded(removeUser, appId);
12445            schedulePackageCleaning(packageName, removeUser, false);
12446            synchronized (mPackages) {
12447                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
12448                    scheduleWritePackageRestrictionsLocked(removeUser);
12449                }
12450            }
12451            return true;
12452        }
12453
12454        if (dataOnly) {
12455            // Delete application data first
12456            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
12457            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
12458            return true;
12459        }
12460
12461        boolean ret = false;
12462        if (isSystemApp(ps)) {
12463            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
12464            // When an updated system application is deleted we delete the existing resources as well and
12465            // fall back to existing code in system partition
12466            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
12467                    flags, outInfo, writeSettings);
12468        } else {
12469            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
12470            // Kill application pre-emptively especially for apps on sd.
12471            killApplication(packageName, ps.appId, "uninstall pkg");
12472            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
12473                    allUserHandles, perUserInstalled,
12474                    outInfo, writeSettings);
12475        }
12476
12477        return ret;
12478    }
12479
12480    private final class ClearStorageConnection implements ServiceConnection {
12481        IMediaContainerService mContainerService;
12482
12483        @Override
12484        public void onServiceConnected(ComponentName name, IBinder service) {
12485            synchronized (this) {
12486                mContainerService = IMediaContainerService.Stub.asInterface(service);
12487                notifyAll();
12488            }
12489        }
12490
12491        @Override
12492        public void onServiceDisconnected(ComponentName name) {
12493        }
12494    }
12495
12496    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
12497        final boolean mounted;
12498        if (Environment.isExternalStorageEmulated()) {
12499            mounted = true;
12500        } else {
12501            final String status = Environment.getExternalStorageState();
12502
12503            mounted = status.equals(Environment.MEDIA_MOUNTED)
12504                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
12505        }
12506
12507        if (!mounted) {
12508            return;
12509        }
12510
12511        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
12512        int[] users;
12513        if (userId == UserHandle.USER_ALL) {
12514            users = sUserManager.getUserIds();
12515        } else {
12516            users = new int[] { userId };
12517        }
12518        final ClearStorageConnection conn = new ClearStorageConnection();
12519        if (mContext.bindServiceAsUser(
12520                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
12521            try {
12522                for (int curUser : users) {
12523                    long timeout = SystemClock.uptimeMillis() + 5000;
12524                    synchronized (conn) {
12525                        long now = SystemClock.uptimeMillis();
12526                        while (conn.mContainerService == null && now < timeout) {
12527                            try {
12528                                conn.wait(timeout - now);
12529                            } catch (InterruptedException e) {
12530                            }
12531                        }
12532                    }
12533                    if (conn.mContainerService == null) {
12534                        return;
12535                    }
12536
12537                    final UserEnvironment userEnv = new UserEnvironment(curUser);
12538                    clearDirectory(conn.mContainerService,
12539                            userEnv.buildExternalStorageAppCacheDirs(packageName));
12540                    if (allData) {
12541                        clearDirectory(conn.mContainerService,
12542                                userEnv.buildExternalStorageAppDataDirs(packageName));
12543                        clearDirectory(conn.mContainerService,
12544                                userEnv.buildExternalStorageAppMediaDirs(packageName));
12545                    }
12546                }
12547            } finally {
12548                mContext.unbindService(conn);
12549            }
12550        }
12551    }
12552
12553    @Override
12554    public void clearApplicationUserData(final String packageName,
12555            final IPackageDataObserver observer, final int userId) {
12556        mContext.enforceCallingOrSelfPermission(
12557                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
12558        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
12559        // Queue up an async operation since the package deletion may take a little while.
12560        mHandler.post(new Runnable() {
12561            public void run() {
12562                mHandler.removeCallbacks(this);
12563                final boolean succeeded;
12564                synchronized (mInstallLock) {
12565                    succeeded = clearApplicationUserDataLI(packageName, userId);
12566                }
12567                clearExternalStorageDataSync(packageName, userId, true);
12568                if (succeeded) {
12569                    // invoke DeviceStorageMonitor's update method to clear any notifications
12570                    DeviceStorageMonitorInternal
12571                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
12572                    if (dsm != null) {
12573                        dsm.checkMemory();
12574                    }
12575                }
12576                if(observer != null) {
12577                    try {
12578                        observer.onRemoveCompleted(packageName, succeeded);
12579                    } catch (RemoteException e) {
12580                        Log.i(TAG, "Observer no longer exists.");
12581                    }
12582                } //end if observer
12583            } //end run
12584        });
12585    }
12586
12587    private boolean clearApplicationUserDataLI(String packageName, int userId) {
12588        if (packageName == null) {
12589            Slog.w(TAG, "Attempt to delete null packageName.");
12590            return false;
12591        }
12592
12593        // Try finding details about the requested package
12594        PackageParser.Package pkg;
12595        synchronized (mPackages) {
12596            pkg = mPackages.get(packageName);
12597            if (pkg == null) {
12598                final PackageSetting ps = mSettings.mPackages.get(packageName);
12599                if (ps != null) {
12600                    pkg = ps.pkg;
12601                }
12602            }
12603        }
12604
12605        if (pkg == null) {
12606            Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12607        }
12608
12609        // Always delete data directories for package, even if we found no other
12610        // record of app. This helps users recover from UID mismatches without
12611        // resorting to a full data wipe.
12612        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
12613        if (retCode < 0) {
12614            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
12615            return false;
12616        }
12617
12618        if (pkg == null) {
12619            return false;
12620        }
12621
12622        if (pkg != null && pkg.applicationInfo != null) {
12623            final int appId = pkg.applicationInfo.uid;
12624            removeKeystoreDataIfNeeded(userId, appId);
12625        }
12626
12627        // Create a native library symlink only if we have native libraries
12628        // and if the native libraries are 32 bit libraries. We do not provide
12629        // this symlink for 64 bit libraries.
12630        if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null &&
12631                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
12632            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
12633            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
12634                    nativeLibPath, userId) < 0) {
12635                Slog.w(TAG, "Failed linking native library dir");
12636                return false;
12637            }
12638        }
12639
12640        return true;
12641    }
12642
12643    /**
12644     * Remove entries from the keystore daemon. Will only remove it if the
12645     * {@code appId} is valid.
12646     */
12647    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
12648        if (appId < 0) {
12649            return;
12650        }
12651
12652        final KeyStore keyStore = KeyStore.getInstance();
12653        if (keyStore != null) {
12654            if (userId == UserHandle.USER_ALL) {
12655                for (final int individual : sUserManager.getUserIds()) {
12656                    keyStore.clearUid(UserHandle.getUid(individual, appId));
12657                }
12658            } else {
12659                keyStore.clearUid(UserHandle.getUid(userId, appId));
12660            }
12661        } else {
12662            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
12663        }
12664    }
12665
12666    @Override
12667    public void deleteApplicationCacheFiles(final String packageName,
12668            final IPackageDataObserver observer) {
12669        mContext.enforceCallingOrSelfPermission(
12670                android.Manifest.permission.DELETE_CACHE_FILES, null);
12671        // Queue up an async operation since the package deletion may take a little while.
12672        final int userId = UserHandle.getCallingUserId();
12673        mHandler.post(new Runnable() {
12674            public void run() {
12675                mHandler.removeCallbacks(this);
12676                final boolean succeded;
12677                synchronized (mInstallLock) {
12678                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
12679                }
12680                clearExternalStorageDataSync(packageName, userId, false);
12681                if (observer != null) {
12682                    try {
12683                        observer.onRemoveCompleted(packageName, succeded);
12684                    } catch (RemoteException e) {
12685                        Log.i(TAG, "Observer no longer exists.");
12686                    }
12687                } //end if observer
12688            } //end run
12689        });
12690    }
12691
12692    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
12693        if (packageName == null) {
12694            Slog.w(TAG, "Attempt to delete null packageName.");
12695            return false;
12696        }
12697        PackageParser.Package p;
12698        synchronized (mPackages) {
12699            p = mPackages.get(packageName);
12700        }
12701        if (p == null) {
12702            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12703            return false;
12704        }
12705        final ApplicationInfo applicationInfo = p.applicationInfo;
12706        if (applicationInfo == null) {
12707            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12708            return false;
12709        }
12710        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
12711        if (retCode < 0) {
12712            Slog.w(TAG, "Couldn't remove cache files for package: "
12713                       + packageName + " u" + userId);
12714            return false;
12715        }
12716        return true;
12717    }
12718
12719    @Override
12720    public void getPackageSizeInfo(final String packageName, int userHandle,
12721            final IPackageStatsObserver observer) {
12722        mContext.enforceCallingOrSelfPermission(
12723                android.Manifest.permission.GET_PACKAGE_SIZE, null);
12724        if (packageName == null) {
12725            throw new IllegalArgumentException("Attempt to get size of null packageName");
12726        }
12727
12728        PackageStats stats = new PackageStats(packageName, userHandle);
12729
12730        /*
12731         * Queue up an async operation since the package measurement may take a
12732         * little while.
12733         */
12734        Message msg = mHandler.obtainMessage(INIT_COPY);
12735        msg.obj = new MeasureParams(stats, observer);
12736        mHandler.sendMessage(msg);
12737    }
12738
12739    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
12740            PackageStats pStats) {
12741        if (packageName == null) {
12742            Slog.w(TAG, "Attempt to get size of null packageName.");
12743            return false;
12744        }
12745        PackageParser.Package p;
12746        boolean dataOnly = false;
12747        String libDirRoot = null;
12748        String asecPath = null;
12749        PackageSetting ps = null;
12750        synchronized (mPackages) {
12751            p = mPackages.get(packageName);
12752            ps = mSettings.mPackages.get(packageName);
12753            if(p == null) {
12754                dataOnly = true;
12755                if((ps == null) || (ps.pkg == null)) {
12756                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12757                    return false;
12758                }
12759                p = ps.pkg;
12760            }
12761            if (ps != null) {
12762                libDirRoot = ps.legacyNativeLibraryPathString;
12763            }
12764            if (p != null && (isExternal(p) || p.isForwardLocked())) {
12765                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
12766                if (secureContainerId != null) {
12767                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
12768                }
12769            }
12770        }
12771        String publicSrcDir = null;
12772        if(!dataOnly) {
12773            final ApplicationInfo applicationInfo = p.applicationInfo;
12774            if (applicationInfo == null) {
12775                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12776                return false;
12777            }
12778            if (p.isForwardLocked()) {
12779                publicSrcDir = applicationInfo.getBaseResourcePath();
12780            }
12781        }
12782        // TODO: extend to measure size of split APKs
12783        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
12784        // not just the first level.
12785        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
12786        // just the primary.
12787        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
12788        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
12789                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
12790        if (res < 0) {
12791            return false;
12792        }
12793
12794        // Fix-up for forward-locked applications in ASEC containers.
12795        if (!isExternal(p)) {
12796            pStats.codeSize += pStats.externalCodeSize;
12797            pStats.externalCodeSize = 0L;
12798        }
12799
12800        return true;
12801    }
12802
12803
12804    @Override
12805    public void addPackageToPreferred(String packageName) {
12806        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
12807    }
12808
12809    @Override
12810    public void removePackageFromPreferred(String packageName) {
12811        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
12812    }
12813
12814    @Override
12815    public List<PackageInfo> getPreferredPackages(int flags) {
12816        return new ArrayList<PackageInfo>();
12817    }
12818
12819    private int getUidTargetSdkVersionLockedLPr(int uid) {
12820        Object obj = mSettings.getUserIdLPr(uid);
12821        if (obj instanceof SharedUserSetting) {
12822            final SharedUserSetting sus = (SharedUserSetting) obj;
12823            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
12824            final Iterator<PackageSetting> it = sus.packages.iterator();
12825            while (it.hasNext()) {
12826                final PackageSetting ps = it.next();
12827                if (ps.pkg != null) {
12828                    int v = ps.pkg.applicationInfo.targetSdkVersion;
12829                    if (v < vers) vers = v;
12830                }
12831            }
12832            return vers;
12833        } else if (obj instanceof PackageSetting) {
12834            final PackageSetting ps = (PackageSetting) obj;
12835            if (ps.pkg != null) {
12836                return ps.pkg.applicationInfo.targetSdkVersion;
12837            }
12838        }
12839        return Build.VERSION_CODES.CUR_DEVELOPMENT;
12840    }
12841
12842    @Override
12843    public void addPreferredActivity(IntentFilter filter, int match,
12844            ComponentName[] set, ComponentName activity, int userId) {
12845        addPreferredActivityInternal(filter, match, set, activity, true, userId,
12846                "Adding preferred");
12847    }
12848
12849    private void addPreferredActivityInternal(IntentFilter filter, int match,
12850            ComponentName[] set, ComponentName activity, boolean always, int userId,
12851            String opname) {
12852        // writer
12853        int callingUid = Binder.getCallingUid();
12854        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
12855        if (filter.countActions() == 0) {
12856            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
12857            return;
12858        }
12859        synchronized (mPackages) {
12860            if (mContext.checkCallingOrSelfPermission(
12861                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12862                    != PackageManager.PERMISSION_GRANTED) {
12863                if (getUidTargetSdkVersionLockedLPr(callingUid)
12864                        < Build.VERSION_CODES.FROYO) {
12865                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
12866                            + callingUid);
12867                    return;
12868                }
12869                mContext.enforceCallingOrSelfPermission(
12870                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12871            }
12872
12873            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
12874            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
12875                    + userId + ":");
12876            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12877            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
12878            scheduleWritePackageRestrictionsLocked(userId);
12879        }
12880    }
12881
12882    @Override
12883    public void replacePreferredActivity(IntentFilter filter, int match,
12884            ComponentName[] set, ComponentName activity, int userId) {
12885        if (filter.countActions() != 1) {
12886            throw new IllegalArgumentException(
12887                    "replacePreferredActivity expects filter to have only 1 action.");
12888        }
12889        if (filter.countDataAuthorities() != 0
12890                || filter.countDataPaths() != 0
12891                || filter.countDataSchemes() > 1
12892                || filter.countDataTypes() != 0) {
12893            throw new IllegalArgumentException(
12894                    "replacePreferredActivity expects filter to have no data authorities, " +
12895                    "paths, or types; and at most one scheme.");
12896        }
12897
12898        final int callingUid = Binder.getCallingUid();
12899        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
12900        synchronized (mPackages) {
12901            if (mContext.checkCallingOrSelfPermission(
12902                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12903                    != PackageManager.PERMISSION_GRANTED) {
12904                if (getUidTargetSdkVersionLockedLPr(callingUid)
12905                        < Build.VERSION_CODES.FROYO) {
12906                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
12907                            + Binder.getCallingUid());
12908                    return;
12909                }
12910                mContext.enforceCallingOrSelfPermission(
12911                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12912            }
12913
12914            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
12915            if (pir != null) {
12916                // Get all of the existing entries that exactly match this filter.
12917                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
12918                if (existing != null && existing.size() == 1) {
12919                    PreferredActivity cur = existing.get(0);
12920                    if (DEBUG_PREFERRED) {
12921                        Slog.i(TAG, "Checking replace of preferred:");
12922                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12923                        if (!cur.mPref.mAlways) {
12924                            Slog.i(TAG, "  -- CUR; not mAlways!");
12925                        } else {
12926                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
12927                            Slog.i(TAG, "  -- CUR: mSet="
12928                                    + Arrays.toString(cur.mPref.mSetComponents));
12929                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
12930                            Slog.i(TAG, "  -- NEW: mMatch="
12931                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
12932                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
12933                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
12934                        }
12935                    }
12936                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
12937                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
12938                            && cur.mPref.sameSet(set)) {
12939                        // Setting the preferred activity to what it happens to be already
12940                        if (DEBUG_PREFERRED) {
12941                            Slog.i(TAG, "Replacing with same preferred activity "
12942                                    + cur.mPref.mShortComponent + " for user "
12943                                    + userId + ":");
12944                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12945                        }
12946                        return;
12947                    }
12948                }
12949
12950                if (existing != null) {
12951                    if (DEBUG_PREFERRED) {
12952                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
12953                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12954                    }
12955                    for (int i = 0; i < existing.size(); i++) {
12956                        PreferredActivity pa = existing.get(i);
12957                        if (DEBUG_PREFERRED) {
12958                            Slog.i(TAG, "Removing existing preferred activity "
12959                                    + pa.mPref.mComponent + ":");
12960                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
12961                        }
12962                        pir.removeFilter(pa);
12963                    }
12964                }
12965            }
12966            addPreferredActivityInternal(filter, match, set, activity, true, userId,
12967                    "Replacing preferred");
12968        }
12969    }
12970
12971    @Override
12972    public void clearPackagePreferredActivities(String packageName) {
12973        final int uid = Binder.getCallingUid();
12974        // writer
12975        synchronized (mPackages) {
12976            PackageParser.Package pkg = mPackages.get(packageName);
12977            if (pkg == null || pkg.applicationInfo.uid != uid) {
12978                if (mContext.checkCallingOrSelfPermission(
12979                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12980                        != PackageManager.PERMISSION_GRANTED) {
12981                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
12982                            < Build.VERSION_CODES.FROYO) {
12983                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
12984                                + Binder.getCallingUid());
12985                        return;
12986                    }
12987                    mContext.enforceCallingOrSelfPermission(
12988                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12989                }
12990            }
12991
12992            int user = UserHandle.getCallingUserId();
12993            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
12994                scheduleWritePackageRestrictionsLocked(user);
12995            }
12996        }
12997    }
12998
12999    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13000    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13001        ArrayList<PreferredActivity> removed = null;
13002        boolean changed = false;
13003        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13004            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13005            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13006            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13007                continue;
13008            }
13009            Iterator<PreferredActivity> it = pir.filterIterator();
13010            while (it.hasNext()) {
13011                PreferredActivity pa = it.next();
13012                // Mark entry for removal only if it matches the package name
13013                // and the entry is of type "always".
13014                if (packageName == null ||
13015                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13016                                && pa.mPref.mAlways)) {
13017                    if (removed == null) {
13018                        removed = new ArrayList<PreferredActivity>();
13019                    }
13020                    removed.add(pa);
13021                }
13022            }
13023            if (removed != null) {
13024                for (int j=0; j<removed.size(); j++) {
13025                    PreferredActivity pa = removed.get(j);
13026                    pir.removeFilter(pa);
13027                }
13028                changed = true;
13029            }
13030        }
13031        return changed;
13032    }
13033
13034    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13035    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13036        if (userId == UserHandle.USER_ALL) {
13037            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13038                    sUserManager.getUserIds())) {
13039                for (int oneUserId : sUserManager.getUserIds()) {
13040                    scheduleWritePackageRestrictionsLocked(oneUserId);
13041                }
13042            }
13043        } else {
13044            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13045                scheduleWritePackageRestrictionsLocked(userId);
13046            }
13047        }
13048    }
13049
13050
13051    void clearDefaultBrowserIfNeeded(String packageName) {
13052        for (int oneUserId : sUserManager.getUserIds()) {
13053            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13054            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13055            if (packageName.equals(defaultBrowserPackageName)) {
13056                setDefaultBrowserPackageName(null, oneUserId);
13057            }
13058        }
13059    }
13060
13061    @Override
13062    public void resetPreferredActivities(int userId) {
13063        /* TODO: Actually use userId. Why is it being passed in? */
13064        mContext.enforceCallingOrSelfPermission(
13065                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13066        // writer
13067        synchronized (mPackages) {
13068            int user = UserHandle.getCallingUserId();
13069            clearPackagePreferredActivitiesLPw(null, user);
13070            mSettings.readDefaultPreferredAppsLPw(this, user);
13071            scheduleWritePackageRestrictionsLocked(user);
13072        }
13073    }
13074
13075    @Override
13076    public int getPreferredActivities(List<IntentFilter> outFilters,
13077            List<ComponentName> outActivities, String packageName) {
13078
13079        int num = 0;
13080        final int userId = UserHandle.getCallingUserId();
13081        // reader
13082        synchronized (mPackages) {
13083            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13084            if (pir != null) {
13085                final Iterator<PreferredActivity> it = pir.filterIterator();
13086                while (it.hasNext()) {
13087                    final PreferredActivity pa = it.next();
13088                    if (packageName == null
13089                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13090                                    && pa.mPref.mAlways)) {
13091                        if (outFilters != null) {
13092                            outFilters.add(new IntentFilter(pa));
13093                        }
13094                        if (outActivities != null) {
13095                            outActivities.add(pa.mPref.mComponent);
13096                        }
13097                    }
13098                }
13099            }
13100        }
13101
13102        return num;
13103    }
13104
13105    @Override
13106    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13107            int userId) {
13108        int callingUid = Binder.getCallingUid();
13109        if (callingUid != Process.SYSTEM_UID) {
13110            throw new SecurityException(
13111                    "addPersistentPreferredActivity can only be run by the system");
13112        }
13113        if (filter.countActions() == 0) {
13114            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13115            return;
13116        }
13117        synchronized (mPackages) {
13118            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13119                    " :");
13120            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13121            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13122                    new PersistentPreferredActivity(filter, activity));
13123            scheduleWritePackageRestrictionsLocked(userId);
13124        }
13125    }
13126
13127    @Override
13128    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13129        int callingUid = Binder.getCallingUid();
13130        if (callingUid != Process.SYSTEM_UID) {
13131            throw new SecurityException(
13132                    "clearPackagePersistentPreferredActivities can only be run by the system");
13133        }
13134        ArrayList<PersistentPreferredActivity> removed = null;
13135        boolean changed = false;
13136        synchronized (mPackages) {
13137            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13138                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13139                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13140                        .valueAt(i);
13141                if (userId != thisUserId) {
13142                    continue;
13143                }
13144                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13145                while (it.hasNext()) {
13146                    PersistentPreferredActivity ppa = it.next();
13147                    // Mark entry for removal only if it matches the package name.
13148                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13149                        if (removed == null) {
13150                            removed = new ArrayList<PersistentPreferredActivity>();
13151                        }
13152                        removed.add(ppa);
13153                    }
13154                }
13155                if (removed != null) {
13156                    for (int j=0; j<removed.size(); j++) {
13157                        PersistentPreferredActivity ppa = removed.get(j);
13158                        ppir.removeFilter(ppa);
13159                    }
13160                    changed = true;
13161                }
13162            }
13163
13164            if (changed) {
13165                scheduleWritePackageRestrictionsLocked(userId);
13166            }
13167        }
13168    }
13169
13170    /**
13171     * Non-Binder method, support for the backup/restore mechanism: write the
13172     * full set of preferred activities in its canonical XML format.  Returns true
13173     * on success; false otherwise.
13174     */
13175    @Override
13176    public byte[] getPreferredActivityBackup(int userId) {
13177        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13178            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13179        }
13180
13181        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13182        try {
13183            final XmlSerializer serializer = new FastXmlSerializer();
13184            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13185            serializer.startDocument(null, true);
13186            serializer.startTag(null, TAG_PREFERRED_BACKUP);
13187
13188            synchronized (mPackages) {
13189                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13190            }
13191
13192            serializer.endTag(null, TAG_PREFERRED_BACKUP);
13193            serializer.endDocument();
13194            serializer.flush();
13195        } catch (Exception e) {
13196            if (DEBUG_BACKUP) {
13197                Slog.e(TAG, "Unable to write preferred activities for backup", e);
13198            }
13199            return null;
13200        }
13201
13202        return dataStream.toByteArray();
13203    }
13204
13205    @Override
13206    public void restorePreferredActivities(byte[] backup, int userId) {
13207        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13208            throw new SecurityException("Only the system may call restorePreferredActivities()");
13209        }
13210
13211        try {
13212            final XmlPullParser parser = Xml.newPullParser();
13213            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13214
13215            int type;
13216            while ((type = parser.next()) != XmlPullParser.START_TAG
13217                    && type != XmlPullParser.END_DOCUMENT) {
13218            }
13219            if (type != XmlPullParser.START_TAG) {
13220                // oops didn't find a start tag?!
13221                if (DEBUG_BACKUP) {
13222                    Slog.e(TAG, "Didn't find start tag during restore");
13223                }
13224                return;
13225            }
13226
13227            // this is supposed to be TAG_PREFERRED_BACKUP
13228            if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) {
13229                if (DEBUG_BACKUP) {
13230                    Slog.e(TAG, "Found unexpected tag " + parser.getName());
13231                }
13232                return;
13233            }
13234
13235            // skip interfering stuff, then we're aligned with the backing implementation
13236            while ((type = parser.next()) == XmlPullParser.TEXT) { }
13237            synchronized (mPackages) {
13238                mSettings.readPreferredActivitiesLPw(parser, userId);
13239            }
13240        } catch (Exception e) {
13241            if (DEBUG_BACKUP) {
13242                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13243            }
13244        }
13245    }
13246
13247    @Override
13248    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
13249            int sourceUserId, int targetUserId, int flags) {
13250        mContext.enforceCallingOrSelfPermission(
13251                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13252        int callingUid = Binder.getCallingUid();
13253        enforceOwnerRights(ownerPackage, callingUid);
13254        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13255        if (intentFilter.countActions() == 0) {
13256            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
13257            return;
13258        }
13259        synchronized (mPackages) {
13260            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
13261                    ownerPackage, targetUserId, flags);
13262            CrossProfileIntentResolver resolver =
13263                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13264            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
13265            // We have all those whose filter is equal. Now checking if the rest is equal as well.
13266            if (existing != null) {
13267                int size = existing.size();
13268                for (int i = 0; i < size; i++) {
13269                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
13270                        return;
13271                    }
13272                }
13273            }
13274            resolver.addFilter(newFilter);
13275            scheduleWritePackageRestrictionsLocked(sourceUserId);
13276        }
13277    }
13278
13279    @Override
13280    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
13281        mContext.enforceCallingOrSelfPermission(
13282                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13283        int callingUid = Binder.getCallingUid();
13284        enforceOwnerRights(ownerPackage, callingUid);
13285        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13286        synchronized (mPackages) {
13287            CrossProfileIntentResolver resolver =
13288                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13289            ArraySet<CrossProfileIntentFilter> set =
13290                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
13291            for (CrossProfileIntentFilter filter : set) {
13292                if (filter.getOwnerPackage().equals(ownerPackage)) {
13293                    resolver.removeFilter(filter);
13294                }
13295            }
13296            scheduleWritePackageRestrictionsLocked(sourceUserId);
13297        }
13298    }
13299
13300    // Enforcing that callingUid is owning pkg on userId
13301    private void enforceOwnerRights(String pkg, int callingUid) {
13302        // The system owns everything.
13303        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
13304            return;
13305        }
13306        int callingUserId = UserHandle.getUserId(callingUid);
13307        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
13308        if (pi == null) {
13309            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
13310                    + callingUserId);
13311        }
13312        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
13313            throw new SecurityException("Calling uid " + callingUid
13314                    + " does not own package " + pkg);
13315        }
13316    }
13317
13318    @Override
13319    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
13320        Intent intent = new Intent(Intent.ACTION_MAIN);
13321        intent.addCategory(Intent.CATEGORY_HOME);
13322
13323        final int callingUserId = UserHandle.getCallingUserId();
13324        List<ResolveInfo> list = queryIntentActivities(intent, null,
13325                PackageManager.GET_META_DATA, callingUserId);
13326        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
13327                true, false, false, callingUserId);
13328
13329        allHomeCandidates.clear();
13330        if (list != null) {
13331            for (ResolveInfo ri : list) {
13332                allHomeCandidates.add(ri);
13333            }
13334        }
13335        return (preferred == null || preferred.activityInfo == null)
13336                ? null
13337                : new ComponentName(preferred.activityInfo.packageName,
13338                        preferred.activityInfo.name);
13339    }
13340
13341    @Override
13342    public void setApplicationEnabledSetting(String appPackageName,
13343            int newState, int flags, int userId, String callingPackage) {
13344        if (!sUserManager.exists(userId)) return;
13345        if (callingPackage == null) {
13346            callingPackage = Integer.toString(Binder.getCallingUid());
13347        }
13348        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
13349    }
13350
13351    @Override
13352    public void setComponentEnabledSetting(ComponentName componentName,
13353            int newState, int flags, int userId) {
13354        if (!sUserManager.exists(userId)) return;
13355        setEnabledSetting(componentName.getPackageName(),
13356                componentName.getClassName(), newState, flags, userId, null);
13357    }
13358
13359    private void setEnabledSetting(final String packageName, String className, int newState,
13360            final int flags, int userId, String callingPackage) {
13361        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
13362              || newState == COMPONENT_ENABLED_STATE_ENABLED
13363              || newState == COMPONENT_ENABLED_STATE_DISABLED
13364              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
13365              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
13366            throw new IllegalArgumentException("Invalid new component state: "
13367                    + newState);
13368        }
13369        PackageSetting pkgSetting;
13370        final int uid = Binder.getCallingUid();
13371        final int permission = mContext.checkCallingOrSelfPermission(
13372                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13373        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
13374        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13375        boolean sendNow = false;
13376        boolean isApp = (className == null);
13377        String componentName = isApp ? packageName : className;
13378        int packageUid = -1;
13379        ArrayList<String> components;
13380
13381        // writer
13382        synchronized (mPackages) {
13383            pkgSetting = mSettings.mPackages.get(packageName);
13384            if (pkgSetting == null) {
13385                if (className == null) {
13386                    throw new IllegalArgumentException(
13387                            "Unknown package: " + packageName);
13388                }
13389                throw new IllegalArgumentException(
13390                        "Unknown component: " + packageName
13391                        + "/" + className);
13392            }
13393            // Allow root and verify that userId is not being specified by a different user
13394            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
13395                throw new SecurityException(
13396                        "Permission Denial: attempt to change component state from pid="
13397                        + Binder.getCallingPid()
13398                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
13399            }
13400            if (className == null) {
13401                // We're dealing with an application/package level state change
13402                if (pkgSetting.getEnabled(userId) == newState) {
13403                    // Nothing to do
13404                    return;
13405                }
13406                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
13407                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
13408                    // Don't care about who enables an app.
13409                    callingPackage = null;
13410                }
13411                pkgSetting.setEnabled(newState, userId, callingPackage);
13412                // pkgSetting.pkg.mSetEnabled = newState;
13413            } else {
13414                // We're dealing with a component level state change
13415                // First, verify that this is a valid class name.
13416                PackageParser.Package pkg = pkgSetting.pkg;
13417                if (pkg == null || !pkg.hasComponentClassName(className)) {
13418                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
13419                        throw new IllegalArgumentException("Component class " + className
13420                                + " does not exist in " + packageName);
13421                    } else {
13422                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
13423                                + className + " does not exist in " + packageName);
13424                    }
13425                }
13426                switch (newState) {
13427                case COMPONENT_ENABLED_STATE_ENABLED:
13428                    if (!pkgSetting.enableComponentLPw(className, userId)) {
13429                        return;
13430                    }
13431                    break;
13432                case COMPONENT_ENABLED_STATE_DISABLED:
13433                    if (!pkgSetting.disableComponentLPw(className, userId)) {
13434                        return;
13435                    }
13436                    break;
13437                case COMPONENT_ENABLED_STATE_DEFAULT:
13438                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
13439                        return;
13440                    }
13441                    break;
13442                default:
13443                    Slog.e(TAG, "Invalid new component state: " + newState);
13444                    return;
13445                }
13446            }
13447            scheduleWritePackageRestrictionsLocked(userId);
13448            components = mPendingBroadcasts.get(userId, packageName);
13449            final boolean newPackage = components == null;
13450            if (newPackage) {
13451                components = new ArrayList<String>();
13452            }
13453            if (!components.contains(componentName)) {
13454                components.add(componentName);
13455            }
13456            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
13457                sendNow = true;
13458                // Purge entry from pending broadcast list if another one exists already
13459                // since we are sending one right away.
13460                mPendingBroadcasts.remove(userId, packageName);
13461            } else {
13462                if (newPackage) {
13463                    mPendingBroadcasts.put(userId, packageName, components);
13464                }
13465                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
13466                    // Schedule a message
13467                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
13468                }
13469            }
13470        }
13471
13472        long callingId = Binder.clearCallingIdentity();
13473        try {
13474            if (sendNow) {
13475                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
13476                sendPackageChangedBroadcast(packageName,
13477                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
13478            }
13479        } finally {
13480            Binder.restoreCallingIdentity(callingId);
13481        }
13482    }
13483
13484    private void sendPackageChangedBroadcast(String packageName,
13485            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
13486        if (DEBUG_INSTALL)
13487            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
13488                    + componentNames);
13489        Bundle extras = new Bundle(4);
13490        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
13491        String nameList[] = new String[componentNames.size()];
13492        componentNames.toArray(nameList);
13493        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
13494        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
13495        extras.putInt(Intent.EXTRA_UID, packageUid);
13496        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
13497                new int[] {UserHandle.getUserId(packageUid)});
13498    }
13499
13500    @Override
13501    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
13502        if (!sUserManager.exists(userId)) return;
13503        final int uid = Binder.getCallingUid();
13504        final int permission = mContext.checkCallingOrSelfPermission(
13505                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13506        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13507        enforceCrossUserPermission(uid, userId, true, true, "stop package");
13508        // writer
13509        synchronized (mPackages) {
13510            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
13511                    allowedByPermission, uid, userId)) {
13512                scheduleWritePackageRestrictionsLocked(userId);
13513            }
13514        }
13515    }
13516
13517    @Override
13518    public String getInstallerPackageName(String packageName) {
13519        // reader
13520        synchronized (mPackages) {
13521            return mSettings.getInstallerPackageNameLPr(packageName);
13522        }
13523    }
13524
13525    @Override
13526    public int getApplicationEnabledSetting(String packageName, int userId) {
13527        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13528        int uid = Binder.getCallingUid();
13529        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
13530        // reader
13531        synchronized (mPackages) {
13532            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
13533        }
13534    }
13535
13536    @Override
13537    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
13538        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13539        int uid = Binder.getCallingUid();
13540        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
13541        // reader
13542        synchronized (mPackages) {
13543            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
13544        }
13545    }
13546
13547    @Override
13548    public void enterSafeMode() {
13549        enforceSystemOrRoot("Only the system can request entering safe mode");
13550
13551        if (!mSystemReady) {
13552            mSafeMode = true;
13553        }
13554    }
13555
13556    @Override
13557    public void systemReady() {
13558        mSystemReady = true;
13559
13560        // Read the compatibilty setting when the system is ready.
13561        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
13562                mContext.getContentResolver(),
13563                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
13564        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
13565        if (DEBUG_SETTINGS) {
13566            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
13567        }
13568
13569        synchronized (mPackages) {
13570            // Verify that all of the preferred activity components actually
13571            // exist.  It is possible for applications to be updated and at
13572            // that point remove a previously declared activity component that
13573            // had been set as a preferred activity.  We try to clean this up
13574            // the next time we encounter that preferred activity, but it is
13575            // possible for the user flow to never be able to return to that
13576            // situation so here we do a sanity check to make sure we haven't
13577            // left any junk around.
13578            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
13579            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13580                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13581                removed.clear();
13582                for (PreferredActivity pa : pir.filterSet()) {
13583                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
13584                        removed.add(pa);
13585                    }
13586                }
13587                if (removed.size() > 0) {
13588                    for (int r=0; r<removed.size(); r++) {
13589                        PreferredActivity pa = removed.get(r);
13590                        Slog.w(TAG, "Removing dangling preferred activity: "
13591                                + pa.mPref.mComponent);
13592                        pir.removeFilter(pa);
13593                    }
13594                    mSettings.writePackageRestrictionsLPr(
13595                            mSettings.mPreferredActivities.keyAt(i));
13596                }
13597            }
13598        }
13599        sUserManager.systemReady();
13600
13601        // Kick off any messages waiting for system ready
13602        if (mPostSystemReadyMessages != null) {
13603            for (Message msg : mPostSystemReadyMessages) {
13604                msg.sendToTarget();
13605            }
13606            mPostSystemReadyMessages = null;
13607        }
13608
13609        // Watch for external volumes that come and go over time
13610        final StorageManager storage = mContext.getSystemService(StorageManager.class);
13611        storage.registerListener(mStorageListener);
13612
13613        mInstallerService.systemReady();
13614        mPackageDexOptimizer.systemReady();
13615    }
13616
13617    @Override
13618    public boolean isSafeMode() {
13619        return mSafeMode;
13620    }
13621
13622    @Override
13623    public boolean hasSystemUidErrors() {
13624        return mHasSystemUidErrors;
13625    }
13626
13627    static String arrayToString(int[] array) {
13628        StringBuffer buf = new StringBuffer(128);
13629        buf.append('[');
13630        if (array != null) {
13631            for (int i=0; i<array.length; i++) {
13632                if (i > 0) buf.append(", ");
13633                buf.append(array[i]);
13634            }
13635        }
13636        buf.append(']');
13637        return buf.toString();
13638    }
13639
13640    static class DumpState {
13641        public static final int DUMP_LIBS = 1 << 0;
13642        public static final int DUMP_FEATURES = 1 << 1;
13643        public static final int DUMP_RESOLVERS = 1 << 2;
13644        public static final int DUMP_PERMISSIONS = 1 << 3;
13645        public static final int DUMP_PACKAGES = 1 << 4;
13646        public static final int DUMP_SHARED_USERS = 1 << 5;
13647        public static final int DUMP_MESSAGES = 1 << 6;
13648        public static final int DUMP_PROVIDERS = 1 << 7;
13649        public static final int DUMP_VERIFIERS = 1 << 8;
13650        public static final int DUMP_PREFERRED = 1 << 9;
13651        public static final int DUMP_PREFERRED_XML = 1 << 10;
13652        public static final int DUMP_KEYSETS = 1 << 11;
13653        public static final int DUMP_VERSION = 1 << 12;
13654        public static final int DUMP_INSTALLS = 1 << 13;
13655        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
13656        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
13657
13658        public static final int OPTION_SHOW_FILTERS = 1 << 0;
13659
13660        private int mTypes;
13661
13662        private int mOptions;
13663
13664        private boolean mTitlePrinted;
13665
13666        private SharedUserSetting mSharedUser;
13667
13668        public boolean isDumping(int type) {
13669            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
13670                return true;
13671            }
13672
13673            return (mTypes & type) != 0;
13674        }
13675
13676        public void setDump(int type) {
13677            mTypes |= type;
13678        }
13679
13680        public boolean isOptionEnabled(int option) {
13681            return (mOptions & option) != 0;
13682        }
13683
13684        public void setOptionEnabled(int option) {
13685            mOptions |= option;
13686        }
13687
13688        public boolean onTitlePrinted() {
13689            final boolean printed = mTitlePrinted;
13690            mTitlePrinted = true;
13691            return printed;
13692        }
13693
13694        public boolean getTitlePrinted() {
13695            return mTitlePrinted;
13696        }
13697
13698        public void setTitlePrinted(boolean enabled) {
13699            mTitlePrinted = enabled;
13700        }
13701
13702        public SharedUserSetting getSharedUser() {
13703            return mSharedUser;
13704        }
13705
13706        public void setSharedUser(SharedUserSetting user) {
13707            mSharedUser = user;
13708        }
13709    }
13710
13711    @Override
13712    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
13713        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
13714                != PackageManager.PERMISSION_GRANTED) {
13715            pw.println("Permission Denial: can't dump ActivityManager from from pid="
13716                    + Binder.getCallingPid()
13717                    + ", uid=" + Binder.getCallingUid()
13718                    + " without permission "
13719                    + android.Manifest.permission.DUMP);
13720            return;
13721        }
13722
13723        DumpState dumpState = new DumpState();
13724        boolean fullPreferred = false;
13725        boolean checkin = false;
13726
13727        String packageName = null;
13728
13729        int opti = 0;
13730        while (opti < args.length) {
13731            String opt = args[opti];
13732            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
13733                break;
13734            }
13735            opti++;
13736
13737            if ("-a".equals(opt)) {
13738                // Right now we only know how to print all.
13739            } else if ("-h".equals(opt)) {
13740                pw.println("Package manager dump options:");
13741                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
13742                pw.println("    --checkin: dump for a checkin");
13743                pw.println("    -f: print details of intent filters");
13744                pw.println("    -h: print this help");
13745                pw.println("  cmd may be one of:");
13746                pw.println("    l[ibraries]: list known shared libraries");
13747                pw.println("    f[ibraries]: list device features");
13748                pw.println("    k[eysets]: print known keysets");
13749                pw.println("    r[esolvers]: dump intent resolvers");
13750                pw.println("    perm[issions]: dump permissions");
13751                pw.println("    pref[erred]: print preferred package settings");
13752                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
13753                pw.println("    prov[iders]: dump content providers");
13754                pw.println("    p[ackages]: dump installed packages");
13755                pw.println("    s[hared-users]: dump shared user IDs");
13756                pw.println("    m[essages]: print collected runtime messages");
13757                pw.println("    v[erifiers]: print package verifier info");
13758                pw.println("    version: print database version info");
13759                pw.println("    write: write current settings now");
13760                pw.println("    <package.name>: info about given package");
13761                pw.println("    installs: details about install sessions");
13762                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
13763                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
13764                return;
13765            } else if ("--checkin".equals(opt)) {
13766                checkin = true;
13767            } else if ("-f".equals(opt)) {
13768                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
13769            } else {
13770                pw.println("Unknown argument: " + opt + "; use -h for help");
13771            }
13772        }
13773
13774        // Is the caller requesting to dump a particular piece of data?
13775        if (opti < args.length) {
13776            String cmd = args[opti];
13777            opti++;
13778            // Is this a package name?
13779            if ("android".equals(cmd) || cmd.contains(".")) {
13780                packageName = cmd;
13781                // When dumping a single package, we always dump all of its
13782                // filter information since the amount of data will be reasonable.
13783                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
13784            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
13785                dumpState.setDump(DumpState.DUMP_LIBS);
13786            } else if ("f".equals(cmd) || "features".equals(cmd)) {
13787                dumpState.setDump(DumpState.DUMP_FEATURES);
13788            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
13789                dumpState.setDump(DumpState.DUMP_RESOLVERS);
13790            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
13791                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
13792            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
13793                dumpState.setDump(DumpState.DUMP_PREFERRED);
13794            } else if ("preferred-xml".equals(cmd)) {
13795                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
13796                if (opti < args.length && "--full".equals(args[opti])) {
13797                    fullPreferred = true;
13798                    opti++;
13799                }
13800            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
13801                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
13802            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
13803                dumpState.setDump(DumpState.DUMP_PACKAGES);
13804            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
13805                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
13806            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
13807                dumpState.setDump(DumpState.DUMP_PROVIDERS);
13808            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
13809                dumpState.setDump(DumpState.DUMP_MESSAGES);
13810            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
13811                dumpState.setDump(DumpState.DUMP_VERIFIERS);
13812            } else if ("i".equals(cmd) || "ifv".equals(cmd)
13813                    || "intent-filter-verifiers".equals(cmd)) {
13814                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
13815            } else if ("version".equals(cmd)) {
13816                dumpState.setDump(DumpState.DUMP_VERSION);
13817            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
13818                dumpState.setDump(DumpState.DUMP_KEYSETS);
13819            } else if ("installs".equals(cmd)) {
13820                dumpState.setDump(DumpState.DUMP_INSTALLS);
13821            } else if ("write".equals(cmd)) {
13822                synchronized (mPackages) {
13823                    mSettings.writeLPr();
13824                    pw.println("Settings written.");
13825                    return;
13826                }
13827            }
13828        }
13829
13830        if (checkin) {
13831            pw.println("vers,1");
13832        }
13833
13834        // reader
13835        synchronized (mPackages) {
13836            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
13837                if (!checkin) {
13838                    if (dumpState.onTitlePrinted())
13839                        pw.println();
13840                    pw.println("Database versions:");
13841                    pw.print("  SDK Version:");
13842                    pw.print(" internal=");
13843                    pw.print(mSettings.mInternalSdkPlatform);
13844                    pw.print(" external=");
13845                    pw.println(mSettings.mExternalSdkPlatform);
13846                    pw.print("  DB Version:");
13847                    pw.print(" internal=");
13848                    pw.print(mSettings.mInternalDatabaseVersion);
13849                    pw.print(" external=");
13850                    pw.println(mSettings.mExternalDatabaseVersion);
13851                }
13852            }
13853
13854            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
13855                if (!checkin) {
13856                    if (dumpState.onTitlePrinted())
13857                        pw.println();
13858                    pw.println("Verifiers:");
13859                    pw.print("  Required: ");
13860                    pw.print(mRequiredVerifierPackage);
13861                    pw.print(" (uid=");
13862                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
13863                    pw.println(")");
13864                } else if (mRequiredVerifierPackage != null) {
13865                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
13866                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
13867                }
13868            }
13869
13870            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
13871                    packageName == null) {
13872                if (mIntentFilterVerifierComponent != null) {
13873                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
13874                    if (!checkin) {
13875                        if (dumpState.onTitlePrinted())
13876                            pw.println();
13877                        pw.println("Intent Filter Verifier:");
13878                        pw.print("  Using: ");
13879                        pw.print(verifierPackageName);
13880                        pw.print(" (uid=");
13881                        pw.print(getPackageUid(verifierPackageName, 0));
13882                        pw.println(")");
13883                    } else if (verifierPackageName != null) {
13884                        pw.print("ifv,"); pw.print(verifierPackageName);
13885                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
13886                    }
13887                } else {
13888                    pw.println();
13889                    pw.println("No Intent Filter Verifier available!");
13890                }
13891            }
13892
13893            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
13894                boolean printedHeader = false;
13895                final Iterator<String> it = mSharedLibraries.keySet().iterator();
13896                while (it.hasNext()) {
13897                    String name = it.next();
13898                    SharedLibraryEntry ent = mSharedLibraries.get(name);
13899                    if (!checkin) {
13900                        if (!printedHeader) {
13901                            if (dumpState.onTitlePrinted())
13902                                pw.println();
13903                            pw.println("Libraries:");
13904                            printedHeader = true;
13905                        }
13906                        pw.print("  ");
13907                    } else {
13908                        pw.print("lib,");
13909                    }
13910                    pw.print(name);
13911                    if (!checkin) {
13912                        pw.print(" -> ");
13913                    }
13914                    if (ent.path != null) {
13915                        if (!checkin) {
13916                            pw.print("(jar) ");
13917                            pw.print(ent.path);
13918                        } else {
13919                            pw.print(",jar,");
13920                            pw.print(ent.path);
13921                        }
13922                    } else {
13923                        if (!checkin) {
13924                            pw.print("(apk) ");
13925                            pw.print(ent.apk);
13926                        } else {
13927                            pw.print(",apk,");
13928                            pw.print(ent.apk);
13929                        }
13930                    }
13931                    pw.println();
13932                }
13933            }
13934
13935            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
13936                if (dumpState.onTitlePrinted())
13937                    pw.println();
13938                if (!checkin) {
13939                    pw.println("Features:");
13940                }
13941                Iterator<String> it = mAvailableFeatures.keySet().iterator();
13942                while (it.hasNext()) {
13943                    String name = it.next();
13944                    if (!checkin) {
13945                        pw.print("  ");
13946                    } else {
13947                        pw.print("feat,");
13948                    }
13949                    pw.println(name);
13950                }
13951            }
13952
13953            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
13954                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
13955                        : "Activity Resolver Table:", "  ", packageName,
13956                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13957                    dumpState.setTitlePrinted(true);
13958                }
13959                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
13960                        : "Receiver Resolver Table:", "  ", packageName,
13961                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13962                    dumpState.setTitlePrinted(true);
13963                }
13964                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
13965                        : "Service Resolver Table:", "  ", packageName,
13966                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13967                    dumpState.setTitlePrinted(true);
13968                }
13969                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
13970                        : "Provider Resolver Table:", "  ", packageName,
13971                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13972                    dumpState.setTitlePrinted(true);
13973                }
13974            }
13975
13976            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
13977                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13978                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13979                    int user = mSettings.mPreferredActivities.keyAt(i);
13980                    if (pir.dump(pw,
13981                            dumpState.getTitlePrinted()
13982                                ? "\nPreferred Activities User " + user + ":"
13983                                : "Preferred Activities User " + user + ":", "  ",
13984                            packageName, true, false)) {
13985                        dumpState.setTitlePrinted(true);
13986                    }
13987                }
13988            }
13989
13990            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
13991                pw.flush();
13992                FileOutputStream fout = new FileOutputStream(fd);
13993                BufferedOutputStream str = new BufferedOutputStream(fout);
13994                XmlSerializer serializer = new FastXmlSerializer();
13995                try {
13996                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
13997                    serializer.startDocument(null, true);
13998                    serializer.setFeature(
13999                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14000                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14001                    serializer.endDocument();
14002                    serializer.flush();
14003                } catch (IllegalArgumentException e) {
14004                    pw.println("Failed writing: " + e);
14005                } catch (IllegalStateException e) {
14006                    pw.println("Failed writing: " + e);
14007                } catch (IOException e) {
14008                    pw.println("Failed writing: " + e);
14009                }
14010            }
14011
14012            if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) {
14013                pw.println();
14014                int count = mSettings.mPackages.size();
14015                if (count == 0) {
14016                    pw.println("No domain preferred apps!");
14017                    pw.println();
14018                } else {
14019                    final String prefix = "  ";
14020                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
14021                    if (allPackageSettings.size() == 0) {
14022                        pw.println("No domain preferred apps!");
14023                        pw.println();
14024                    } else {
14025                        pw.println("Domain preferred apps status:");
14026                        pw.println();
14027                        count = 0;
14028                        for (PackageSetting ps : allPackageSettings) {
14029                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14030                            if (ivi == null || ivi.getPackageName() == null) continue;
14031                            pw.println(prefix + "Package Name: " + ivi.getPackageName());
14032                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
14033                            pw.println(prefix + "Status: " + ivi.getStatusString());
14034                            pw.println();
14035                            count++;
14036                        }
14037                        if (count == 0) {
14038                            pw.println(prefix + "No domain preferred app status!");
14039                            pw.println();
14040                        }
14041                        for (int userId : sUserManager.getUserIds()) {
14042                            pw.println("Domain preferred apps for User " + userId + ":");
14043                            pw.println();
14044                            count = 0;
14045                            for (PackageSetting ps : allPackageSettings) {
14046                                IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14047                                if (ivi == null || ivi.getPackageName() == null) {
14048                                    continue;
14049                                }
14050                                final int status = ps.getDomainVerificationStatusForUser(userId);
14051                                if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
14052                                    continue;
14053                                }
14054                                pw.println(prefix + "Package Name: " + ivi.getPackageName());
14055                                pw.println(prefix + "Domains: " + ivi.getDomainsString());
14056                                String statusStr = IntentFilterVerificationInfo.
14057                                        getStatusStringFromValue(status);
14058                                pw.println(prefix + "Status: " + statusStr);
14059                                pw.println();
14060                                count++;
14061                            }
14062                            if (count == 0) {
14063                                pw.println(prefix + "No domain preferred apps!");
14064                                pw.println();
14065                            }
14066                        }
14067                    }
14068                }
14069            }
14070
14071            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
14072                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
14073                if (packageName == null) {
14074                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
14075                        if (iperm == 0) {
14076                            if (dumpState.onTitlePrinted())
14077                                pw.println();
14078                            pw.println("AppOp Permissions:");
14079                        }
14080                        pw.print("  AppOp Permission ");
14081                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
14082                        pw.println(":");
14083                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
14084                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
14085                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
14086                        }
14087                    }
14088                }
14089            }
14090
14091            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
14092                boolean printedSomething = false;
14093                for (PackageParser.Provider p : mProviders.mProviders.values()) {
14094                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14095                        continue;
14096                    }
14097                    if (!printedSomething) {
14098                        if (dumpState.onTitlePrinted())
14099                            pw.println();
14100                        pw.println("Registered ContentProviders:");
14101                        printedSomething = true;
14102                    }
14103                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
14104                    pw.print("    "); pw.println(p.toString());
14105                }
14106                printedSomething = false;
14107                for (Map.Entry<String, PackageParser.Provider> entry :
14108                        mProvidersByAuthority.entrySet()) {
14109                    PackageParser.Provider p = entry.getValue();
14110                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14111                        continue;
14112                    }
14113                    if (!printedSomething) {
14114                        if (dumpState.onTitlePrinted())
14115                            pw.println();
14116                        pw.println("ContentProvider Authorities:");
14117                        printedSomething = true;
14118                    }
14119                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
14120                    pw.print("    "); pw.println(p.toString());
14121                    if (p.info != null && p.info.applicationInfo != null) {
14122                        final String appInfo = p.info.applicationInfo.toString();
14123                        pw.print("      applicationInfo="); pw.println(appInfo);
14124                    }
14125                }
14126            }
14127
14128            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
14129                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
14130            }
14131
14132            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
14133                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
14134            }
14135
14136            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
14137                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin);
14138            }
14139
14140            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
14141                // XXX should handle packageName != null by dumping only install data that
14142                // the given package is involved with.
14143                if (dumpState.onTitlePrinted()) pw.println();
14144                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
14145            }
14146
14147            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
14148                if (dumpState.onTitlePrinted()) pw.println();
14149                mSettings.dumpReadMessagesLPr(pw, dumpState);
14150
14151                pw.println();
14152                pw.println("Package warning messages:");
14153                BufferedReader in = null;
14154                String line = null;
14155                try {
14156                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14157                    while ((line = in.readLine()) != null) {
14158                        if (line.contains("ignored: updated version")) continue;
14159                        pw.println(line);
14160                    }
14161                } catch (IOException ignored) {
14162                } finally {
14163                    IoUtils.closeQuietly(in);
14164                }
14165            }
14166
14167            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
14168                BufferedReader in = null;
14169                String line = null;
14170                try {
14171                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14172                    while ((line = in.readLine()) != null) {
14173                        if (line.contains("ignored: updated version")) continue;
14174                        pw.print("msg,");
14175                        pw.println(line);
14176                    }
14177                } catch (IOException ignored) {
14178                } finally {
14179                    IoUtils.closeQuietly(in);
14180                }
14181            }
14182        }
14183    }
14184
14185    // ------- apps on sdcard specific code -------
14186    static final boolean DEBUG_SD_INSTALL = false;
14187
14188    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
14189
14190    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
14191
14192    private boolean mMediaMounted = false;
14193
14194    static String getEncryptKey() {
14195        try {
14196            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
14197                    SD_ENCRYPTION_KEYSTORE_NAME);
14198            if (sdEncKey == null) {
14199                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
14200                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
14201                if (sdEncKey == null) {
14202                    Slog.e(TAG, "Failed to create encryption keys");
14203                    return null;
14204                }
14205            }
14206            return sdEncKey;
14207        } catch (NoSuchAlgorithmException nsae) {
14208            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
14209            return null;
14210        } catch (IOException ioe) {
14211            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
14212            return null;
14213        }
14214    }
14215
14216    /*
14217     * Update media status on PackageManager.
14218     */
14219    @Override
14220    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
14221        int callingUid = Binder.getCallingUid();
14222        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
14223            throw new SecurityException("Media status can only be updated by the system");
14224        }
14225        // reader; this apparently protects mMediaMounted, but should probably
14226        // be a different lock in that case.
14227        synchronized (mPackages) {
14228            Log.i(TAG, "Updating external media status from "
14229                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
14230                    + (mediaStatus ? "mounted" : "unmounted"));
14231            if (DEBUG_SD_INSTALL)
14232                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
14233                        + ", mMediaMounted=" + mMediaMounted);
14234            if (mediaStatus == mMediaMounted) {
14235                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
14236                        : 0, -1);
14237                mHandler.sendMessage(msg);
14238                return;
14239            }
14240            mMediaMounted = mediaStatus;
14241        }
14242        // Queue up an async operation since the package installation may take a
14243        // little while.
14244        mHandler.post(new Runnable() {
14245            public void run() {
14246                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
14247            }
14248        });
14249    }
14250
14251    /**
14252     * Called by MountService when the initial ASECs to scan are available.
14253     * Should block until all the ASEC containers are finished being scanned.
14254     */
14255    public void scanAvailableAsecs() {
14256        updateExternalMediaStatusInner(true, false, false);
14257        if (mShouldRestoreconData) {
14258            SELinuxMMAC.setRestoreconDone();
14259            mShouldRestoreconData = false;
14260        }
14261    }
14262
14263    /*
14264     * Collect information of applications on external media, map them against
14265     * existing containers and update information based on current mount status.
14266     * Please note that we always have to report status if reportStatus has been
14267     * set to true especially when unloading packages.
14268     */
14269    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
14270            boolean externalStorage) {
14271        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
14272        int[] uidArr = EmptyArray.INT;
14273
14274        final String[] list = PackageHelper.getSecureContainerList();
14275        if (ArrayUtils.isEmpty(list)) {
14276            Log.i(TAG, "No secure containers found");
14277        } else {
14278            // Process list of secure containers and categorize them
14279            // as active or stale based on their package internal state.
14280
14281            // reader
14282            synchronized (mPackages) {
14283                for (String cid : list) {
14284                    // Leave stages untouched for now; installer service owns them
14285                    if (PackageInstallerService.isStageName(cid)) continue;
14286
14287                    if (DEBUG_SD_INSTALL)
14288                        Log.i(TAG, "Processing container " + cid);
14289                    String pkgName = getAsecPackageName(cid);
14290                    if (pkgName == null) {
14291                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
14292                        continue;
14293                    }
14294                    if (DEBUG_SD_INSTALL)
14295                        Log.i(TAG, "Looking for pkg : " + pkgName);
14296
14297                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
14298                    if (ps == null) {
14299                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
14300                        continue;
14301                    }
14302
14303                    /*
14304                     * Skip packages that are not external if we're unmounting
14305                     * external storage.
14306                     */
14307                    if (externalStorage && !isMounted && !isExternal(ps)) {
14308                        continue;
14309                    }
14310
14311                    final AsecInstallArgs args = new AsecInstallArgs(cid,
14312                            getAppDexInstructionSets(ps), ps.isForwardLocked());
14313                    // The package status is changed only if the code path
14314                    // matches between settings and the container id.
14315                    if (ps.codePathString != null
14316                            && ps.codePathString.startsWith(args.getCodePath())) {
14317                        if (DEBUG_SD_INSTALL) {
14318                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
14319                                    + " at code path: " + ps.codePathString);
14320                        }
14321
14322                        // We do have a valid package installed on sdcard
14323                        processCids.put(args, ps.codePathString);
14324                        final int uid = ps.appId;
14325                        if (uid != -1) {
14326                            uidArr = ArrayUtils.appendInt(uidArr, uid);
14327                        }
14328                    } else {
14329                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
14330                                + ps.codePathString);
14331                    }
14332                }
14333            }
14334
14335            Arrays.sort(uidArr);
14336        }
14337
14338        // Process packages with valid entries.
14339        if (isMounted) {
14340            if (DEBUG_SD_INSTALL)
14341                Log.i(TAG, "Loading packages");
14342            loadMediaPackages(processCids, uidArr);
14343            startCleaningPackages();
14344            mInstallerService.onSecureContainersAvailable();
14345        } else {
14346            if (DEBUG_SD_INSTALL)
14347                Log.i(TAG, "Unloading packages");
14348            unloadMediaPackages(processCids, uidArr, reportStatus);
14349        }
14350    }
14351
14352    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14353            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
14354        final int size = infos.size();
14355        final String[] packageNames = new String[size];
14356        final int[] packageUids = new int[size];
14357        for (int i = 0; i < size; i++) {
14358            final ApplicationInfo info = infos.get(i);
14359            packageNames[i] = info.packageName;
14360            packageUids[i] = info.uid;
14361        }
14362        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
14363                finishedReceiver);
14364    }
14365
14366    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14367            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14368        sendResourcesChangedBroadcast(mediaStatus, replacing,
14369                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
14370    }
14371
14372    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14373            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14374        int size = pkgList.length;
14375        if (size > 0) {
14376            // Send broadcasts here
14377            Bundle extras = new Bundle();
14378            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14379            if (uidArr != null) {
14380                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
14381            }
14382            if (replacing) {
14383                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
14384            }
14385            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
14386                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
14387            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
14388        }
14389    }
14390
14391   /*
14392     * Look at potentially valid container ids from processCids If package
14393     * information doesn't match the one on record or package scanning fails,
14394     * the cid is added to list of removeCids. We currently don't delete stale
14395     * containers.
14396     */
14397    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
14398        ArrayList<String> pkgList = new ArrayList<String>();
14399        Set<AsecInstallArgs> keys = processCids.keySet();
14400
14401        for (AsecInstallArgs args : keys) {
14402            String codePath = processCids.get(args);
14403            if (DEBUG_SD_INSTALL)
14404                Log.i(TAG, "Loading container : " + args.cid);
14405            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14406            try {
14407                // Make sure there are no container errors first.
14408                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
14409                    Slog.e(TAG, "Failed to mount cid : " + args.cid
14410                            + " when installing from sdcard");
14411                    continue;
14412                }
14413                // Check code path here.
14414                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
14415                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
14416                            + " does not match one in settings " + codePath);
14417                    continue;
14418                }
14419                // Parse package
14420                int parseFlags = mDefParseFlags;
14421                if (args.isExternalAsec()) {
14422                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
14423                }
14424                if (args.isFwdLocked()) {
14425                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
14426                }
14427
14428                synchronized (mInstallLock) {
14429                    PackageParser.Package pkg = null;
14430                    try {
14431                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
14432                    } catch (PackageManagerException e) {
14433                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
14434                    }
14435                    // Scan the package
14436                    if (pkg != null) {
14437                        /*
14438                         * TODO why is the lock being held? doPostInstall is
14439                         * called in other places without the lock. This needs
14440                         * to be straightened out.
14441                         */
14442                        // writer
14443                        synchronized (mPackages) {
14444                            retCode = PackageManager.INSTALL_SUCCEEDED;
14445                            pkgList.add(pkg.packageName);
14446                            // Post process args
14447                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
14448                                    pkg.applicationInfo.uid);
14449                        }
14450                    } else {
14451                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
14452                    }
14453                }
14454
14455            } finally {
14456                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
14457                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
14458                }
14459            }
14460        }
14461        // writer
14462        synchronized (mPackages) {
14463            // If the platform SDK has changed since the last time we booted,
14464            // we need to re-grant app permission to catch any new ones that
14465            // appear. This is really a hack, and means that apps can in some
14466            // cases get permissions that the user didn't initially explicitly
14467            // allow... it would be nice to have some better way to handle
14468            // this situation.
14469            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
14470            if (regrantPermissions)
14471                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
14472                        + mSdkVersion + "; regranting permissions for external storage");
14473            mSettings.mExternalSdkPlatform = mSdkVersion;
14474
14475            // Make sure group IDs have been assigned, and any permission
14476            // changes in other apps are accounted for
14477            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
14478                    | (regrantPermissions
14479                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
14480                            : 0));
14481
14482            mSettings.updateExternalDatabaseVersion();
14483
14484            // can downgrade to reader
14485            // Persist settings
14486            mSettings.writeLPr();
14487        }
14488        // Send a broadcast to let everyone know we are done processing
14489        if (pkgList.size() > 0) {
14490            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
14491        }
14492    }
14493
14494   /*
14495     * Utility method to unload a list of specified containers
14496     */
14497    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
14498        // Just unmount all valid containers.
14499        for (AsecInstallArgs arg : cidArgs) {
14500            synchronized (mInstallLock) {
14501                arg.doPostDeleteLI(false);
14502           }
14503       }
14504   }
14505
14506    /*
14507     * Unload packages mounted on external media. This involves deleting package
14508     * data from internal structures, sending broadcasts about diabled packages,
14509     * gc'ing to free up references, unmounting all secure containers
14510     * corresponding to packages on external media, and posting a
14511     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
14512     * that we always have to post this message if status has been requested no
14513     * matter what.
14514     */
14515    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
14516            final boolean reportStatus) {
14517        if (DEBUG_SD_INSTALL)
14518            Log.i(TAG, "unloading media packages");
14519        ArrayList<String> pkgList = new ArrayList<String>();
14520        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
14521        final Set<AsecInstallArgs> keys = processCids.keySet();
14522        for (AsecInstallArgs args : keys) {
14523            String pkgName = args.getPackageName();
14524            if (DEBUG_SD_INSTALL)
14525                Log.i(TAG, "Trying to unload pkg : " + pkgName);
14526            // Delete package internally
14527            PackageRemovedInfo outInfo = new PackageRemovedInfo();
14528            synchronized (mInstallLock) {
14529                boolean res = deletePackageLI(pkgName, null, false, null, null,
14530                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
14531                if (res) {
14532                    pkgList.add(pkgName);
14533                } else {
14534                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
14535                    failedList.add(args);
14536                }
14537            }
14538        }
14539
14540        // reader
14541        synchronized (mPackages) {
14542            // We didn't update the settings after removing each package;
14543            // write them now for all packages.
14544            mSettings.writeLPr();
14545        }
14546
14547        // We have to absolutely send UPDATED_MEDIA_STATUS only
14548        // after confirming that all the receivers processed the ordered
14549        // broadcast when packages get disabled, force a gc to clean things up.
14550        // and unload all the containers.
14551        if (pkgList.size() > 0) {
14552            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
14553                    new IIntentReceiver.Stub() {
14554                public void performReceive(Intent intent, int resultCode, String data,
14555                        Bundle extras, boolean ordered, boolean sticky,
14556                        int sendingUser) throws RemoteException {
14557                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
14558                            reportStatus ? 1 : 0, 1, keys);
14559                    mHandler.sendMessage(msg);
14560                }
14561            });
14562        } else {
14563            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
14564                    keys);
14565            mHandler.sendMessage(msg);
14566        }
14567    }
14568
14569    private void loadPrivatePackages(VolumeInfo vol) {
14570        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
14571        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
14572        synchronized (mInstallLock) {
14573        synchronized (mPackages) {
14574            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14575            for (PackageSetting ps : packages) {
14576                final PackageParser.Package pkg;
14577                try {
14578                    pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null);
14579                    loaded.add(pkg.applicationInfo);
14580                } catch (PackageManagerException e) {
14581                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
14582                }
14583            }
14584
14585            // TODO: regrant any permissions that changed based since original install
14586
14587            mSettings.writeLPr();
14588        }
14589        }
14590
14591        Slog.d(TAG, "Loaded packages " + loaded);
14592        sendResourcesChangedBroadcast(true, false, loaded, null);
14593    }
14594
14595    private void unloadPrivatePackages(VolumeInfo vol) {
14596        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
14597        synchronized (mInstallLock) {
14598        synchronized (mPackages) {
14599            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14600            for (PackageSetting ps : packages) {
14601                if (ps.pkg == null) continue;
14602
14603                final ApplicationInfo info = ps.pkg.applicationInfo;
14604                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
14605                if (deletePackageLI(ps.name, null, false, null, null,
14606                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
14607                    unloaded.add(info);
14608                } else {
14609                    Slog.w(TAG, "Failed to unload " + ps.codePath);
14610                }
14611            }
14612
14613            mSettings.writeLPr();
14614        }
14615        }
14616
14617        Slog.d(TAG, "Unloaded packages " + unloaded);
14618        sendResourcesChangedBroadcast(false, false, unloaded, null);
14619    }
14620
14621    private void unfreezePackage(String packageName) {
14622        synchronized (mPackages) {
14623            final PackageSetting ps = mSettings.mPackages.get(packageName);
14624            if (ps != null) {
14625                ps.frozen = false;
14626            }
14627        }
14628    }
14629
14630    @Override
14631    public int movePackage(final String packageName, final String volumeUuid) {
14632        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
14633
14634        final int moveId = mNextMoveId.getAndIncrement();
14635        try {
14636            movePackageInternal(packageName, volumeUuid, moveId);
14637        } catch (PackageManagerException e) {
14638            Slog.d(TAG, "Failed to move " + packageName, e);
14639            mMoveCallbacks.notifyStatusChanged(moveId,
14640                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
14641        }
14642        return moveId;
14643    }
14644
14645    private void movePackageInternal(final String packageName, final String volumeUuid,
14646            final int moveId) throws PackageManagerException {
14647        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
14648        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14649        final PackageManager pm = mContext.getPackageManager();
14650
14651        final boolean currentAsec;
14652        final String currentVolumeUuid;
14653        final File codeFile;
14654        final String installerPackageName;
14655        final String packageAbiOverride;
14656        final int appId;
14657        final String seinfo;
14658        final String label;
14659
14660        // reader
14661        synchronized (mPackages) {
14662            final PackageParser.Package pkg = mPackages.get(packageName);
14663            final PackageSetting ps = mSettings.mPackages.get(packageName);
14664            if (pkg == null || ps == null) {
14665                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
14666            }
14667
14668            if (pkg.applicationInfo.isSystemApp()) {
14669                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
14670                        "Cannot move system application");
14671            }
14672
14673            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
14674                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14675                        "Package already moved to " + volumeUuid);
14676            }
14677
14678            final File probe = new File(pkg.codePath);
14679            final File probeOat = new File(probe, "oat");
14680            if (!probe.isDirectory() || !probeOat.isDirectory()) {
14681                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14682                        "Move only supported for modern cluster style installs");
14683            }
14684
14685            if (ps.frozen) {
14686                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
14687                        "Failed to move already frozen package");
14688            }
14689            ps.frozen = true;
14690
14691            currentAsec = pkg.applicationInfo.isForwardLocked()
14692                    || pkg.applicationInfo.isExternalAsec();
14693            currentVolumeUuid = ps.volumeUuid;
14694            codeFile = new File(pkg.codePath);
14695            installerPackageName = ps.installerPackageName;
14696            packageAbiOverride = ps.cpuAbiOverrideString;
14697            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
14698            seinfo = pkg.applicationInfo.seinfo;
14699            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
14700        }
14701
14702        // Now that we're guarded by frozen state, kill app during move
14703        killApplication(packageName, appId, "move pkg");
14704
14705        final Bundle extras = new Bundle();
14706        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
14707        extras.putString(Intent.EXTRA_TITLE, label);
14708        mMoveCallbacks.notifyCreated(moveId, extras);
14709
14710        int installFlags;
14711        final boolean moveCompleteApp;
14712        final File measurePath;
14713
14714        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
14715            installFlags = INSTALL_INTERNAL;
14716            moveCompleteApp = !currentAsec;
14717            measurePath = Environment.getDataAppDirectory(volumeUuid);
14718        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
14719            installFlags = INSTALL_EXTERNAL;
14720            moveCompleteApp = false;
14721            measurePath = storage.getPrimaryPhysicalVolume().getPath();
14722        } else {
14723            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
14724            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
14725                    || !volume.isMountedWritable()) {
14726                unfreezePackage(packageName);
14727                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14728                        "Move location not mounted private volume");
14729            }
14730
14731            Preconditions.checkState(!currentAsec);
14732
14733            installFlags = INSTALL_INTERNAL;
14734            moveCompleteApp = true;
14735            measurePath = Environment.getDataAppDirectory(volumeUuid);
14736        }
14737
14738        final PackageStats stats = new PackageStats(null, -1);
14739        synchronized (mInstaller) {
14740            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
14741                unfreezePackage(packageName);
14742                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14743                        "Failed to measure package size");
14744            }
14745        }
14746
14747        Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " + stats.dataSize);
14748
14749        final long startFreeBytes = measurePath.getFreeSpace();
14750        final long sizeBytes;
14751        if (moveCompleteApp) {
14752            sizeBytes = stats.codeSize + stats.dataSize;
14753        } else {
14754            sizeBytes = stats.codeSize;
14755        }
14756
14757        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
14758            unfreezePackage(packageName);
14759            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14760                    "Not enough free space to move");
14761        }
14762
14763        mMoveCallbacks.notifyStatusChanged(moveId, 10);
14764
14765        final CountDownLatch installedLatch = new CountDownLatch(1);
14766        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
14767            @Override
14768            public void onUserActionRequired(Intent intent) throws RemoteException {
14769                throw new IllegalStateException();
14770            }
14771
14772            @Override
14773            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
14774                    Bundle extras) throws RemoteException {
14775                Slog.d(TAG, "Install result for move: "
14776                        + PackageManager.installStatusToString(returnCode, msg));
14777
14778                installedLatch.countDown();
14779
14780                // Regardless of success or failure of the move operation,
14781                // always unfreeze the package
14782                unfreezePackage(packageName);
14783
14784                final int status = PackageManager.installStatusToPublicStatus(returnCode);
14785                switch (status) {
14786                    case PackageInstaller.STATUS_SUCCESS:
14787                        mMoveCallbacks.notifyStatusChanged(moveId,
14788                                PackageManager.MOVE_SUCCEEDED);
14789                        break;
14790                    case PackageInstaller.STATUS_FAILURE_STORAGE:
14791                        mMoveCallbacks.notifyStatusChanged(moveId,
14792                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
14793                        break;
14794                    default:
14795                        mMoveCallbacks.notifyStatusChanged(moveId,
14796                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
14797                        break;
14798                }
14799            }
14800        };
14801
14802        final MoveInfo move;
14803        if (moveCompleteApp) {
14804            // Kick off a thread to report progress estimates
14805            new Thread() {
14806                @Override
14807                public void run() {
14808                    while (true) {
14809                        try {
14810                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
14811                                break;
14812                            }
14813                        } catch (InterruptedException ignored) {
14814                        }
14815
14816                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
14817                        final int progress = 10 + (int) MathUtils.constrain(
14818                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
14819                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
14820                    }
14821                }
14822            }.start();
14823
14824            final String dataAppName = codeFile.getName();
14825            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
14826                    dataAppName, appId, seinfo);
14827        } else {
14828            move = null;
14829        }
14830
14831        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
14832
14833        final Message msg = mHandler.obtainMessage(INIT_COPY);
14834        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
14835        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
14836                installerPackageName, volumeUuid, null, user, packageAbiOverride);
14837        mHandler.sendMessage(msg);
14838    }
14839
14840    @Override
14841    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
14842        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
14843
14844        final int realMoveId = mNextMoveId.getAndIncrement();
14845        final Bundle extras = new Bundle();
14846        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
14847        mMoveCallbacks.notifyCreated(realMoveId, extras);
14848
14849        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
14850            @Override
14851            public void onCreated(int moveId, Bundle extras) {
14852                // Ignored
14853            }
14854
14855            @Override
14856            public void onStatusChanged(int moveId, int status, long estMillis) {
14857                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
14858            }
14859        };
14860
14861        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14862        storage.setPrimaryStorageUuid(volumeUuid, callback);
14863        return realMoveId;
14864    }
14865
14866    @Override
14867    public int getMoveStatus(int moveId) {
14868        mContext.enforceCallingOrSelfPermission(
14869                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
14870        return mMoveCallbacks.mLastStatus.get(moveId);
14871    }
14872
14873    @Override
14874    public void registerMoveCallback(IPackageMoveObserver callback) {
14875        mContext.enforceCallingOrSelfPermission(
14876                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
14877        mMoveCallbacks.register(callback);
14878    }
14879
14880    @Override
14881    public void unregisterMoveCallback(IPackageMoveObserver callback) {
14882        mContext.enforceCallingOrSelfPermission(
14883                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
14884        mMoveCallbacks.unregister(callback);
14885    }
14886
14887    @Override
14888    public boolean setInstallLocation(int loc) {
14889        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
14890                null);
14891        if (getInstallLocation() == loc) {
14892            return true;
14893        }
14894        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
14895                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
14896            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
14897                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
14898            return true;
14899        }
14900        return false;
14901   }
14902
14903    @Override
14904    public int getInstallLocation() {
14905        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14906                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
14907                PackageHelper.APP_INSTALL_AUTO);
14908    }
14909
14910    /** Called by UserManagerService */
14911    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
14912        mDirtyUsers.remove(userHandle);
14913        mSettings.removeUserLPw(userHandle);
14914        mPendingBroadcasts.remove(userHandle);
14915        if (mInstaller != null) {
14916            // Technically, we shouldn't be doing this with the package lock
14917            // held.  However, this is very rare, and there is already so much
14918            // other disk I/O going on, that we'll let it slide for now.
14919            final StorageManager storage = StorageManager.from(mContext);
14920            final List<VolumeInfo> vols = storage.getVolumes();
14921            for (VolumeInfo vol : vols) {
14922                if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) {
14923                    final String volumeUuid = vol.getFsUuid();
14924                    Slog.d(TAG, "Removing user data on volume " + volumeUuid);
14925                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
14926                }
14927            }
14928        }
14929        mUserNeedsBadging.delete(userHandle);
14930        removeUnusedPackagesLILPw(userManager, userHandle);
14931    }
14932
14933    /**
14934     * We're removing userHandle and would like to remove any downloaded packages
14935     * that are no longer in use by any other user.
14936     * @param userHandle the user being removed
14937     */
14938    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
14939        final boolean DEBUG_CLEAN_APKS = false;
14940        int [] users = userManager.getUserIdsLPr();
14941        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
14942        while (psit.hasNext()) {
14943            PackageSetting ps = psit.next();
14944            if (ps.pkg == null) {
14945                continue;
14946            }
14947            final String packageName = ps.pkg.packageName;
14948            // Skip over if system app
14949            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14950                continue;
14951            }
14952            if (DEBUG_CLEAN_APKS) {
14953                Slog.i(TAG, "Checking package " + packageName);
14954            }
14955            boolean keep = false;
14956            for (int i = 0; i < users.length; i++) {
14957                if (users[i] != userHandle && ps.getInstalled(users[i])) {
14958                    keep = true;
14959                    if (DEBUG_CLEAN_APKS) {
14960                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
14961                                + users[i]);
14962                    }
14963                    break;
14964                }
14965            }
14966            if (!keep) {
14967                if (DEBUG_CLEAN_APKS) {
14968                    Slog.i(TAG, "  Removing package " + packageName);
14969                }
14970                mHandler.post(new Runnable() {
14971                    public void run() {
14972                        deletePackageX(packageName, userHandle, 0);
14973                    } //end run
14974                });
14975            }
14976        }
14977    }
14978
14979    /** Called by UserManagerService */
14980    void createNewUserLILPw(int userHandle, File path) {
14981        if (mInstaller != null) {
14982            mInstaller.createUserConfig(userHandle);
14983            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
14984        }
14985    }
14986
14987    void newUserCreatedLILPw(int userHandle) {
14988        // Adding a user requires updating runtime permissions for system apps.
14989        updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
14990    }
14991
14992    @Override
14993    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
14994        mContext.enforceCallingOrSelfPermission(
14995                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14996                "Only package verification agents can read the verifier device identity");
14997
14998        synchronized (mPackages) {
14999            return mSettings.getVerifierDeviceIdentityLPw();
15000        }
15001    }
15002
15003    @Override
15004    public void setPermissionEnforced(String permission, boolean enforced) {
15005        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
15006        if (READ_EXTERNAL_STORAGE.equals(permission)) {
15007            synchronized (mPackages) {
15008                if (mSettings.mReadExternalStorageEnforced == null
15009                        || mSettings.mReadExternalStorageEnforced != enforced) {
15010                    mSettings.mReadExternalStorageEnforced = enforced;
15011                    mSettings.writeLPr();
15012                }
15013            }
15014            // kill any non-foreground processes so we restart them and
15015            // grant/revoke the GID.
15016            final IActivityManager am = ActivityManagerNative.getDefault();
15017            if (am != null) {
15018                final long token = Binder.clearCallingIdentity();
15019                try {
15020                    am.killProcessesBelowForeground("setPermissionEnforcement");
15021                } catch (RemoteException e) {
15022                } finally {
15023                    Binder.restoreCallingIdentity(token);
15024                }
15025            }
15026        } else {
15027            throw new IllegalArgumentException("No selective enforcement for " + permission);
15028        }
15029    }
15030
15031    @Override
15032    @Deprecated
15033    public boolean isPermissionEnforced(String permission) {
15034        return true;
15035    }
15036
15037    @Override
15038    public boolean isStorageLow() {
15039        final long token = Binder.clearCallingIdentity();
15040        try {
15041            final DeviceStorageMonitorInternal
15042                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
15043            if (dsm != null) {
15044                return dsm.isMemoryLow();
15045            } else {
15046                return false;
15047            }
15048        } finally {
15049            Binder.restoreCallingIdentity(token);
15050        }
15051    }
15052
15053    @Override
15054    public IPackageInstaller getPackageInstaller() {
15055        return mInstallerService;
15056    }
15057
15058    private boolean userNeedsBadging(int userId) {
15059        int index = mUserNeedsBadging.indexOfKey(userId);
15060        if (index < 0) {
15061            final UserInfo userInfo;
15062            final long token = Binder.clearCallingIdentity();
15063            try {
15064                userInfo = sUserManager.getUserInfo(userId);
15065            } finally {
15066                Binder.restoreCallingIdentity(token);
15067            }
15068            final boolean b;
15069            if (userInfo != null && userInfo.isManagedProfile()) {
15070                b = true;
15071            } else {
15072                b = false;
15073            }
15074            mUserNeedsBadging.put(userId, b);
15075            return b;
15076        }
15077        return mUserNeedsBadging.valueAt(index);
15078    }
15079
15080    @Override
15081    public KeySet getKeySetByAlias(String packageName, String alias) {
15082        if (packageName == null || alias == null) {
15083            return null;
15084        }
15085        synchronized(mPackages) {
15086            final PackageParser.Package pkg = mPackages.get(packageName);
15087            if (pkg == null) {
15088                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15089                throw new IllegalArgumentException("Unknown package: " + packageName);
15090            }
15091            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15092            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
15093        }
15094    }
15095
15096    @Override
15097    public KeySet getSigningKeySet(String packageName) {
15098        if (packageName == null) {
15099            return null;
15100        }
15101        synchronized(mPackages) {
15102            final PackageParser.Package pkg = mPackages.get(packageName);
15103            if (pkg == null) {
15104                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15105                throw new IllegalArgumentException("Unknown package: " + packageName);
15106            }
15107            if (pkg.applicationInfo.uid != Binder.getCallingUid()
15108                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
15109                throw new SecurityException("May not access signing KeySet of other apps.");
15110            }
15111            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15112            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
15113        }
15114    }
15115
15116    @Override
15117    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
15118        if (packageName == null || ks == null) {
15119            return false;
15120        }
15121        synchronized(mPackages) {
15122            final PackageParser.Package pkg = mPackages.get(packageName);
15123            if (pkg == null) {
15124                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15125                throw new IllegalArgumentException("Unknown package: " + packageName);
15126            }
15127            IBinder ksh = ks.getToken();
15128            if (ksh instanceof KeySetHandle) {
15129                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15130                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
15131            }
15132            return false;
15133        }
15134    }
15135
15136    @Override
15137    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
15138        if (packageName == null || ks == null) {
15139            return false;
15140        }
15141        synchronized(mPackages) {
15142            final PackageParser.Package pkg = mPackages.get(packageName);
15143            if (pkg == null) {
15144                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15145                throw new IllegalArgumentException("Unknown package: " + packageName);
15146            }
15147            IBinder ksh = ks.getToken();
15148            if (ksh instanceof KeySetHandle) {
15149                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15150                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
15151            }
15152            return false;
15153        }
15154    }
15155
15156    public void getUsageStatsIfNoPackageUsageInfo() {
15157        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
15158            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
15159            if (usm == null) {
15160                throw new IllegalStateException("UsageStatsManager must be initialized");
15161            }
15162            long now = System.currentTimeMillis();
15163            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
15164            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
15165                String packageName = entry.getKey();
15166                PackageParser.Package pkg = mPackages.get(packageName);
15167                if (pkg == null) {
15168                    continue;
15169                }
15170                UsageStats usage = entry.getValue();
15171                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
15172                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
15173            }
15174        }
15175    }
15176
15177    /**
15178     * Check and throw if the given before/after packages would be considered a
15179     * downgrade.
15180     */
15181    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
15182            throws PackageManagerException {
15183        if (after.versionCode < before.mVersionCode) {
15184            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15185                    "Update version code " + after.versionCode + " is older than current "
15186                    + before.mVersionCode);
15187        } else if (after.versionCode == before.mVersionCode) {
15188            if (after.baseRevisionCode < before.baseRevisionCode) {
15189                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15190                        "Update base revision code " + after.baseRevisionCode
15191                        + " is older than current " + before.baseRevisionCode);
15192            }
15193
15194            if (!ArrayUtils.isEmpty(after.splitNames)) {
15195                for (int i = 0; i < after.splitNames.length; i++) {
15196                    final String splitName = after.splitNames[i];
15197                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
15198                    if (j != -1) {
15199                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
15200                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15201                                    "Update split " + splitName + " revision code "
15202                                    + after.splitRevisionCodes[i] + " is older than current "
15203                                    + before.splitRevisionCodes[j]);
15204                        }
15205                    }
15206                }
15207            }
15208        }
15209    }
15210
15211    private static class MoveCallbacks extends Handler {
15212        private static final int MSG_CREATED = 1;
15213        private static final int MSG_STATUS_CHANGED = 2;
15214
15215        private final RemoteCallbackList<IPackageMoveObserver>
15216                mCallbacks = new RemoteCallbackList<>();
15217
15218        private final SparseIntArray mLastStatus = new SparseIntArray();
15219
15220        public MoveCallbacks(Looper looper) {
15221            super(looper);
15222        }
15223
15224        public void register(IPackageMoveObserver callback) {
15225            mCallbacks.register(callback);
15226        }
15227
15228        public void unregister(IPackageMoveObserver callback) {
15229            mCallbacks.unregister(callback);
15230        }
15231
15232        @Override
15233        public void handleMessage(Message msg) {
15234            final SomeArgs args = (SomeArgs) msg.obj;
15235            final int n = mCallbacks.beginBroadcast();
15236            for (int i = 0; i < n; i++) {
15237                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
15238                try {
15239                    invokeCallback(callback, msg.what, args);
15240                } catch (RemoteException ignored) {
15241                }
15242            }
15243            mCallbacks.finishBroadcast();
15244            args.recycle();
15245        }
15246
15247        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
15248                throws RemoteException {
15249            switch (what) {
15250                case MSG_CREATED: {
15251                    callback.onCreated(args.argi1, (Bundle) args.arg2);
15252                    break;
15253                }
15254                case MSG_STATUS_CHANGED: {
15255                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
15256                    break;
15257                }
15258            }
15259        }
15260
15261        private void notifyCreated(int moveId, Bundle extras) {
15262            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
15263
15264            final SomeArgs args = SomeArgs.obtain();
15265            args.argi1 = moveId;
15266            args.arg2 = extras;
15267            obtainMessage(MSG_CREATED, args).sendToTarget();
15268        }
15269
15270        private void notifyStatusChanged(int moveId, int status) {
15271            notifyStatusChanged(moveId, status, -1);
15272        }
15273
15274        private void notifyStatusChanged(int moveId, int status, long estMillis) {
15275            Slog.v(TAG, "Move " + moveId + " status " + status);
15276
15277            final SomeArgs args = SomeArgs.obtain();
15278            args.argi1 = moveId;
15279            args.argi2 = status;
15280            args.arg3 = estMillis;
15281            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
15282
15283            synchronized (mLastStatus) {
15284                mLastStatus.put(moveId, status);
15285            }
15286        }
15287    }
15288}
15289