PackageManagerService.java revision 9c896ab226c53020b8495e9d2d6f520a0eb887cb
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS;
20import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
26import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
27import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
28import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
29import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
30import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
32import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
33import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
34import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
36import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
37import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
38import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
39import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
41import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
42import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
44import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
45import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
46import static android.content.pm.PackageManager.INSTALL_INTERNAL;
47import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
48import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
49import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
50import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
51import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
52import static android.content.pm.PackageManager.MATCH_ALL;
53import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
54import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
55import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
56import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
57import static android.content.pm.PackageParser.isApkFile;
58import static android.os.Process.FIRST_APPLICATION_UID;
59import static android.os.Process.PACKAGE_INFO_GID;
60import static android.os.Process.SYSTEM_UID;
61import static android.system.OsConstants.O_CREAT;
62import static android.system.OsConstants.O_RDWR;
63import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
64import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
65import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
66import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
67import static com.android.internal.util.ArrayUtils.appendInt;
68import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
69import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
70import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
71import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
72import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
73
74import android.Manifest;
75import android.app.ActivityManager;
76import android.app.ActivityManagerNative;
77import android.app.AppGlobals;
78import android.app.IActivityManager;
79import android.app.admin.IDevicePolicyManager;
80import android.app.backup.IBackupManager;
81import android.app.usage.UsageStats;
82import android.app.usage.UsageStatsManager;
83import android.content.BroadcastReceiver;
84import android.content.ComponentName;
85import android.content.Context;
86import android.content.IIntentReceiver;
87import android.content.Intent;
88import android.content.IntentFilter;
89import android.content.IntentSender;
90import android.content.IntentSender.SendIntentException;
91import android.content.ServiceConnection;
92import android.content.pm.ActivityInfo;
93import android.content.pm.ApplicationInfo;
94import android.content.pm.FeatureInfo;
95import android.content.pm.IOnPermissionsChangeListener;
96import android.content.pm.IPackageDataObserver;
97import android.content.pm.IPackageDeleteObserver;
98import android.content.pm.IPackageDeleteObserver2;
99import android.content.pm.IPackageInstallObserver2;
100import android.content.pm.IPackageInstaller;
101import android.content.pm.IPackageManager;
102import android.content.pm.IPackageMoveObserver;
103import android.content.pm.IPackageStatsObserver;
104import android.content.pm.InstrumentationInfo;
105import android.content.pm.IntentFilterVerificationInfo;
106import android.content.pm.KeySet;
107import android.content.pm.ManifestDigest;
108import android.content.pm.PackageCleanItem;
109import android.content.pm.PackageInfo;
110import android.content.pm.PackageInfoLite;
111import android.content.pm.PackageInstaller;
112import android.content.pm.PackageManager;
113import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
114import android.content.pm.PackageParser;
115import android.content.pm.PackageParser.ActivityIntentInfo;
116import android.content.pm.PackageParser.PackageLite;
117import android.content.pm.PackageParser.PackageParserException;
118import android.content.pm.PackageStats;
119import android.content.pm.PackageUserState;
120import android.content.pm.ParceledListSlice;
121import android.content.pm.PermissionGroupInfo;
122import android.content.pm.PermissionInfo;
123import android.content.pm.ProviderInfo;
124import android.content.pm.ResolveInfo;
125import android.content.pm.ServiceInfo;
126import android.content.pm.Signature;
127import android.content.pm.UserInfo;
128import android.content.pm.VerificationParams;
129import android.content.pm.VerifierDeviceIdentity;
130import android.content.pm.VerifierInfo;
131import android.content.res.Resources;
132import android.hardware.display.DisplayManager;
133import android.net.Uri;
134import android.os.Binder;
135import android.os.Build;
136import android.os.Bundle;
137import android.os.Debug;
138import android.os.Environment;
139import android.os.Environment.UserEnvironment;
140import android.os.FileUtils;
141import android.os.Handler;
142import android.os.IBinder;
143import android.os.Looper;
144import android.os.Message;
145import android.os.Parcel;
146import android.os.ParcelFileDescriptor;
147import android.os.Process;
148import android.os.RemoteCallbackList;
149import android.os.RemoteException;
150import android.os.SELinux;
151import android.os.ServiceManager;
152import android.os.SystemClock;
153import android.os.SystemProperties;
154import android.os.UserHandle;
155import android.os.UserManager;
156import android.os.storage.IMountService;
157import android.os.storage.StorageEventListener;
158import android.os.storage.StorageManager;
159import android.os.storage.VolumeInfo;
160import android.os.storage.VolumeRecord;
161import android.security.KeyStore;
162import android.security.SystemKeyStore;
163import android.system.ErrnoException;
164import android.system.Os;
165import android.system.StructStat;
166import android.text.TextUtils;
167import android.text.format.DateUtils;
168import android.util.ArrayMap;
169import android.util.ArraySet;
170import android.util.AtomicFile;
171import android.util.DisplayMetrics;
172import android.util.EventLog;
173import android.util.ExceptionUtils;
174import android.util.Log;
175import android.util.LogPrinter;
176import android.util.MathUtils;
177import android.util.PrintStreamPrinter;
178import android.util.Slog;
179import android.util.SparseArray;
180import android.util.SparseBooleanArray;
181import android.util.SparseIntArray;
182import android.util.Xml;
183import android.view.Display;
184
185import dalvik.system.DexFile;
186import dalvik.system.VMRuntime;
187
188import libcore.io.IoUtils;
189import libcore.util.EmptyArray;
190
191import com.android.internal.R;
192import com.android.internal.app.IMediaContainerService;
193import com.android.internal.app.ResolverActivity;
194import com.android.internal.content.NativeLibraryHelper;
195import com.android.internal.content.PackageHelper;
196import com.android.internal.os.IParcelFileDescriptorFactory;
197import com.android.internal.os.SomeArgs;
198import com.android.internal.util.ArrayUtils;
199import com.android.internal.util.FastPrintWriter;
200import com.android.internal.util.FastXmlSerializer;
201import com.android.internal.util.IndentingPrintWriter;
202import com.android.internal.util.Preconditions;
203import com.android.server.EventLogTags;
204import com.android.server.FgThread;
205import com.android.server.IntentResolver;
206import com.android.server.LocalServices;
207import com.android.server.ServiceThread;
208import com.android.server.SystemConfig;
209import com.android.server.Watchdog;
210import com.android.server.pm.Settings.DatabaseVersion;
211import com.android.server.pm.PermissionsState.PermissionState;
212import com.android.server.storage.DeviceStorageMonitorInternal;
213
214import org.xmlpull.v1.XmlPullParser;
215import org.xmlpull.v1.XmlSerializer;
216
217import java.io.BufferedInputStream;
218import java.io.BufferedOutputStream;
219import java.io.BufferedReader;
220import java.io.ByteArrayInputStream;
221import java.io.ByteArrayOutputStream;
222import java.io.File;
223import java.io.FileDescriptor;
224import java.io.FileNotFoundException;
225import java.io.FileOutputStream;
226import java.io.FileReader;
227import java.io.FilenameFilter;
228import java.io.IOException;
229import java.io.InputStream;
230import java.io.PrintWriter;
231import java.nio.charset.StandardCharsets;
232import java.security.NoSuchAlgorithmException;
233import java.security.PublicKey;
234import java.security.cert.CertificateEncodingException;
235import java.security.cert.CertificateException;
236import java.text.SimpleDateFormat;
237import java.util.ArrayList;
238import java.util.Arrays;
239import java.util.Collection;
240import java.util.Collections;
241import java.util.Comparator;
242import java.util.Date;
243import java.util.Iterator;
244import java.util.List;
245import java.util.Map;
246import java.util.Objects;
247import java.util.Set;
248import java.util.concurrent.CountDownLatch;
249import java.util.concurrent.TimeUnit;
250import java.util.concurrent.atomic.AtomicBoolean;
251import java.util.concurrent.atomic.AtomicInteger;
252import java.util.concurrent.atomic.AtomicLong;
253
254/**
255 * Keep track of all those .apks everywhere.
256 *
257 * This is very central to the platform's security; please run the unit
258 * tests whenever making modifications here:
259 *
260mmm frameworks/base/tests/AndroidTests
261adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
262adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
263 *
264 * {@hide}
265 */
266public class PackageManagerService extends IPackageManager.Stub {
267    static final String TAG = "PackageManager";
268    static final boolean DEBUG_SETTINGS = false;
269    static final boolean DEBUG_PREFERRED = false;
270    static final boolean DEBUG_UPGRADE = false;
271    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
272    private static final boolean DEBUG_BACKUP = true;
273    private static final boolean DEBUG_INSTALL = false;
274    private static final boolean DEBUG_REMOVE = false;
275    private static final boolean DEBUG_BROADCASTS = false;
276    private static final boolean DEBUG_SHOW_INFO = false;
277    private static final boolean DEBUG_PACKAGE_INFO = false;
278    private static final boolean DEBUG_INTENT_MATCHING = false;
279    private static final boolean DEBUG_PACKAGE_SCANNING = false;
280    private static final boolean DEBUG_VERIFY = false;
281    private static final boolean DEBUG_DEXOPT = false;
282    private static final boolean DEBUG_ABI_SELECTION = false;
283
284    private static final int RADIO_UID = Process.PHONE_UID;
285    private static final int LOG_UID = Process.LOG_UID;
286    private static final int NFC_UID = Process.NFC_UID;
287    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
288    private static final int SHELL_UID = Process.SHELL_UID;
289
290    // Cap the size of permission trees that 3rd party apps can define
291    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
292
293    // Suffix used during package installation when copying/moving
294    // package apks to install directory.
295    private static final String INSTALL_PACKAGE_SUFFIX = "-";
296
297    static final int SCAN_NO_DEX = 1<<1;
298    static final int SCAN_FORCE_DEX = 1<<2;
299    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
300    static final int SCAN_NEW_INSTALL = 1<<4;
301    static final int SCAN_NO_PATHS = 1<<5;
302    static final int SCAN_UPDATE_TIME = 1<<6;
303    static final int SCAN_DEFER_DEX = 1<<7;
304    static final int SCAN_BOOTING = 1<<8;
305    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
306    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
307    static final int SCAN_REQUIRE_KNOWN = 1<<12;
308    static final int SCAN_MOVE = 1<<13;
309
310    static final int REMOVE_CHATTY = 1<<16;
311
312    private static final int[] EMPTY_INT_ARRAY = new int[0];
313
314    /**
315     * Timeout (in milliseconds) after which the watchdog should declare that
316     * our handler thread is wedged.  The usual default for such things is one
317     * minute but we sometimes do very lengthy I/O operations on this thread,
318     * such as installing multi-gigabyte applications, so ours needs to be longer.
319     */
320    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
321
322    /**
323     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
324     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
325     * settings entry if available, otherwise we use the hardcoded default.  If it's been
326     * more than this long since the last fstrim, we force one during the boot sequence.
327     *
328     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
329     * one gets run at the next available charging+idle time.  This final mandatory
330     * no-fstrim check kicks in only of the other scheduling criteria is never met.
331     */
332    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
333
334    /**
335     * Whether verification is enabled by default.
336     */
337    private static final boolean DEFAULT_VERIFY_ENABLE = true;
338
339    /**
340     * The default maximum time to wait for the verification agent to return in
341     * milliseconds.
342     */
343    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
344
345    /**
346     * The default response for package verification timeout.
347     *
348     * This can be either PackageManager.VERIFICATION_ALLOW or
349     * PackageManager.VERIFICATION_REJECT.
350     */
351    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
352
353    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
354
355    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
356            DEFAULT_CONTAINER_PACKAGE,
357            "com.android.defcontainer.DefaultContainerService");
358
359    private static final String KILL_APP_REASON_GIDS_CHANGED =
360            "permission grant or revoke changed gids";
361
362    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
363            "permissions revoked";
364
365    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
366
367    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
368
369    /** Permission grant: not grant the permission. */
370    private static final int GRANT_DENIED = 1;
371
372    /** Permission grant: grant the permission as an install permission. */
373    private static final int GRANT_INSTALL = 2;
374
375    /** Permission grant: grant the permission as an install permission for a legacy app. */
376    private static final int GRANT_INSTALL_LEGACY = 3;
377
378    /** Permission grant: grant the permission as a runtime one. */
379    private static final int GRANT_RUNTIME = 4;
380
381    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
382    private static final int GRANT_UPGRADE = 5;
383
384    final ServiceThread mHandlerThread;
385
386    final PackageHandler mHandler;
387
388    /**
389     * Messages for {@link #mHandler} that need to wait for system ready before
390     * being dispatched.
391     */
392    private ArrayList<Message> mPostSystemReadyMessages;
393
394    final int mSdkVersion = Build.VERSION.SDK_INT;
395
396    final Context mContext;
397    final boolean mFactoryTest;
398    final boolean mOnlyCore;
399    final boolean mLazyDexOpt;
400    final long mDexOptLRUThresholdInMills;
401    final DisplayMetrics mMetrics;
402    final int mDefParseFlags;
403    final String[] mSeparateProcesses;
404    final boolean mIsUpgrade;
405
406    // This is where all application persistent data goes.
407    final File mAppDataDir;
408
409    // This is where all application persistent data goes for secondary users.
410    final File mUserAppDataDir;
411
412    /** The location for ASEC container files on internal storage. */
413    final String mAsecInternalPath;
414
415    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
416    // LOCK HELD.  Can be called with mInstallLock held.
417    final Installer mInstaller;
418
419    /** Directory where installed third-party apps stored */
420    final File mAppInstallDir;
421
422    /**
423     * Directory to which applications installed internally have their
424     * 32 bit native libraries copied.
425     */
426    private File mAppLib32InstallDir;
427
428    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
429    // apps.
430    final File mDrmAppPrivateInstallDir;
431
432    // ----------------------------------------------------------------
433
434    // Lock for state used when installing and doing other long running
435    // operations.  Methods that must be called with this lock held have
436    // the suffix "LI".
437    final Object mInstallLock = new Object();
438
439    // ----------------------------------------------------------------
440
441    // Keys are String (package name), values are Package.  This also serves
442    // as the lock for the global state.  Methods that must be called with
443    // this lock held have the prefix "LP".
444    final ArrayMap<String, PackageParser.Package> mPackages =
445            new ArrayMap<String, PackageParser.Package>();
446
447    // Tracks available target package names -> overlay package paths.
448    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
449        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
450
451    final Settings mSettings;
452    boolean mRestoredSettings;
453
454    // System configuration read by SystemConfig.
455    final int[] mGlobalGids;
456    final SparseArray<ArraySet<String>> mSystemPermissions;
457    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
458
459    // If mac_permissions.xml was found for seinfo labeling.
460    boolean mFoundPolicyFile;
461
462    // If a recursive restorecon of /data/data/<pkg> is needed.
463    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
464
465    public static final class SharedLibraryEntry {
466        public final String path;
467        public final String apk;
468
469        SharedLibraryEntry(String _path, String _apk) {
470            path = _path;
471            apk = _apk;
472        }
473    }
474
475    // Currently known shared libraries.
476    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
477            new ArrayMap<String, SharedLibraryEntry>();
478
479    // All available activities, for your resolving pleasure.
480    final ActivityIntentResolver mActivities =
481            new ActivityIntentResolver();
482
483    // All available receivers, for your resolving pleasure.
484    final ActivityIntentResolver mReceivers =
485            new ActivityIntentResolver();
486
487    // All available services, for your resolving pleasure.
488    final ServiceIntentResolver mServices = new ServiceIntentResolver();
489
490    // All available providers, for your resolving pleasure.
491    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
492
493    // Mapping from provider base names (first directory in content URI codePath)
494    // to the provider information.
495    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
496            new ArrayMap<String, PackageParser.Provider>();
497
498    // Mapping from instrumentation class names to info about them.
499    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
500            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
501
502    // Mapping from permission names to info about them.
503    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
504            new ArrayMap<String, PackageParser.PermissionGroup>();
505
506    // Packages whose data we have transfered into another package, thus
507    // should no longer exist.
508    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
509
510    // Broadcast actions that are only available to the system.
511    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
512
513    /** List of packages waiting for verification. */
514    final SparseArray<PackageVerificationState> mPendingVerification
515            = new SparseArray<PackageVerificationState>();
516
517    /** Set of packages associated with each app op permission. */
518    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
519
520    final PackageInstallerService mInstallerService;
521
522    private final PackageDexOptimizer mPackageDexOptimizer;
523
524    private AtomicInteger mNextMoveId = new AtomicInteger();
525    private final MoveCallbacks mMoveCallbacks;
526
527    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
528
529    // Cache of users who need badging.
530    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
531
532    /** Token for keys in mPendingVerification. */
533    private int mPendingVerificationToken = 0;
534
535    volatile boolean mSystemReady;
536    volatile boolean mSafeMode;
537    volatile boolean mHasSystemUidErrors;
538
539    ApplicationInfo mAndroidApplication;
540    final ActivityInfo mResolveActivity = new ActivityInfo();
541    final ResolveInfo mResolveInfo = new ResolveInfo();
542    ComponentName mResolveComponentName;
543    PackageParser.Package mPlatformPackage;
544    ComponentName mCustomResolverComponentName;
545
546    boolean mResolverReplaced = false;
547
548    private final ComponentName mIntentFilterVerifierComponent;
549    private int mIntentFilterVerificationToken = 0;
550
551    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
552            = new SparseArray<IntentFilterVerificationState>();
553
554    private interface IntentFilterVerifier<T extends IntentFilter> {
555        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
556                                               T filter, String packageName);
557        void startVerifications(int userId);
558        void receiveVerificationResponse(int verificationId);
559    }
560
561    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
562        private Context mContext;
563        private ComponentName mIntentFilterVerifierComponent;
564        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
565
566        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
567            mContext = context;
568            mIntentFilterVerifierComponent = verifierComponent;
569        }
570
571        private String getDefaultScheme() {
572            return IntentFilter.SCHEME_HTTPS;
573        }
574
575        @Override
576        public void startVerifications(int userId) {
577            // Launch verifications requests
578            int count = mCurrentIntentFilterVerifications.size();
579            for (int n=0; n<count; n++) {
580                int verificationId = mCurrentIntentFilterVerifications.get(n);
581                final IntentFilterVerificationState ivs =
582                        mIntentFilterVerificationStates.get(verificationId);
583
584                String packageName = ivs.getPackageName();
585
586                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
587                final int filterCount = filters.size();
588                ArraySet<String> domainsSet = new ArraySet<>();
589                for (int m=0; m<filterCount; m++) {
590                    PackageParser.ActivityIntentInfo filter = filters.get(m);
591                    domainsSet.addAll(filter.getHostsList());
592                }
593                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
594                synchronized (mPackages) {
595                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
596                            packageName, domainsList) != null) {
597                        scheduleWriteSettingsLocked();
598                    }
599                }
600                sendVerificationRequest(userId, verificationId, ivs);
601            }
602            mCurrentIntentFilterVerifications.clear();
603        }
604
605        private void sendVerificationRequest(int userId, int verificationId,
606                IntentFilterVerificationState ivs) {
607
608            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
609            verificationIntent.putExtra(
610                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
611                    verificationId);
612            verificationIntent.putExtra(
613                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
614                    getDefaultScheme());
615            verificationIntent.putExtra(
616                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
617                    ivs.getHostsString());
618            verificationIntent.putExtra(
619                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
620                    ivs.getPackageName());
621            verificationIntent.setComponent(mIntentFilterVerifierComponent);
622            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
623
624            UserHandle user = new UserHandle(userId);
625            mContext.sendBroadcastAsUser(verificationIntent, user);
626            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
627                    "Sending IntenFilter verification broadcast");
628        }
629
630        public void receiveVerificationResponse(int verificationId) {
631            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
632
633            final boolean verified = ivs.isVerified();
634
635            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
636            final int count = filters.size();
637            for (int n=0; n<count; n++) {
638                PackageParser.ActivityIntentInfo filter = filters.get(n);
639                filter.setVerified(verified);
640
641                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
642                        + " verified with result:" + verified + " and hosts:"
643                        + ivs.getHostsString());
644            }
645
646            mIntentFilterVerificationStates.remove(verificationId);
647
648            final String packageName = ivs.getPackageName();
649            IntentFilterVerificationInfo ivi = null;
650
651            synchronized (mPackages) {
652                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
653            }
654            if (ivi == null) {
655                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
656                        + verificationId + " packageName:" + packageName);
657                return;
658            }
659            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
660                    "Updating IntentFilterVerificationInfo for verificationId:" + verificationId);
661
662            synchronized (mPackages) {
663                if (verified) {
664                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
665                } else {
666                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
667                }
668                scheduleWriteSettingsLocked();
669
670                final int userId = ivs.getUserId();
671                if (userId != UserHandle.USER_ALL) {
672                    final int userStatus =
673                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
674
675                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
676                    boolean needUpdate = false;
677
678                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
679                    // already been set by the User thru the Disambiguation dialog
680                    switch (userStatus) {
681                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
682                            if (verified) {
683                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
684                            } else {
685                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
686                            }
687                            needUpdate = true;
688                            break;
689
690                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
691                            if (verified) {
692                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
693                                needUpdate = true;
694                            }
695                            break;
696
697                        default:
698                            // Nothing to do
699                    }
700
701                    if (needUpdate) {
702                        mSettings.updateIntentFilterVerificationStatusLPw(
703                                packageName, updatedStatus, userId);
704                        scheduleWritePackageRestrictionsLocked(userId);
705                    }
706                }
707            }
708        }
709
710        @Override
711        public boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
712                    ActivityIntentInfo filter, String packageName) {
713            if (!(filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
714                    filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
715                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
716                        "IntentFilter does not contain HTTP nor HTTPS data scheme");
717                return false;
718            }
719            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
720            if (ivs == null) {
721                ivs = createDomainVerificationState(verifierId, userId, verificationId,
722                        packageName);
723            }
724            if (!hasValidDomains(filter)) {
725                return false;
726            }
727            ivs.addFilter(filter);
728            return true;
729        }
730
731        private IntentFilterVerificationState createDomainVerificationState(int verifierId,
732                int userId, int verificationId, String packageName) {
733            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
734                    verifierId, userId, packageName);
735            ivs.setPendingState();
736            synchronized (mPackages) {
737                mIntentFilterVerificationStates.append(verificationId, ivs);
738                mCurrentIntentFilterVerifications.add(verificationId);
739            }
740            return ivs;
741        }
742    }
743
744    private static boolean hasValidDomains(ActivityIntentInfo filter) {
745        boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
746                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS);
747        if (!hasHTTPorHTTPS) {
748            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
749                    "IntentFilter does not contain any HTTP or HTTPS data scheme");
750            return false;
751        }
752        return true;
753    }
754
755    private IntentFilterVerifier mIntentFilterVerifier;
756
757    // Set of pending broadcasts for aggregating enable/disable of components.
758    static class PendingPackageBroadcasts {
759        // for each user id, a map of <package name -> components within that package>
760        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
761
762        public PendingPackageBroadcasts() {
763            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
764        }
765
766        public ArrayList<String> get(int userId, String packageName) {
767            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
768            return packages.get(packageName);
769        }
770
771        public void put(int userId, String packageName, ArrayList<String> components) {
772            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
773            packages.put(packageName, components);
774        }
775
776        public void remove(int userId, String packageName) {
777            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
778            if (packages != null) {
779                packages.remove(packageName);
780            }
781        }
782
783        public void remove(int userId) {
784            mUidMap.remove(userId);
785        }
786
787        public int userIdCount() {
788            return mUidMap.size();
789        }
790
791        public int userIdAt(int n) {
792            return mUidMap.keyAt(n);
793        }
794
795        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
796            return mUidMap.get(userId);
797        }
798
799        public int size() {
800            // total number of pending broadcast entries across all userIds
801            int num = 0;
802            for (int i = 0; i< mUidMap.size(); i++) {
803                num += mUidMap.valueAt(i).size();
804            }
805            return num;
806        }
807
808        public void clear() {
809            mUidMap.clear();
810        }
811
812        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
813            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
814            if (map == null) {
815                map = new ArrayMap<String, ArrayList<String>>();
816                mUidMap.put(userId, map);
817            }
818            return map;
819        }
820    }
821    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
822
823    // Service Connection to remote media container service to copy
824    // package uri's from external media onto secure containers
825    // or internal storage.
826    private IMediaContainerService mContainerService = null;
827
828    static final int SEND_PENDING_BROADCAST = 1;
829    static final int MCS_BOUND = 3;
830    static final int END_COPY = 4;
831    static final int INIT_COPY = 5;
832    static final int MCS_UNBIND = 6;
833    static final int START_CLEANING_PACKAGE = 7;
834    static final int FIND_INSTALL_LOC = 8;
835    static final int POST_INSTALL = 9;
836    static final int MCS_RECONNECT = 10;
837    static final int MCS_GIVE_UP = 11;
838    static final int UPDATED_MEDIA_STATUS = 12;
839    static final int WRITE_SETTINGS = 13;
840    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
841    static final int PACKAGE_VERIFIED = 15;
842    static final int CHECK_PENDING_VERIFICATION = 16;
843    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
844    static final int INTENT_FILTER_VERIFIED = 18;
845
846    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
847
848    // Delay time in millisecs
849    static final int BROADCAST_DELAY = 10 * 1000;
850
851    static UserManagerService sUserManager;
852
853    // Stores a list of users whose package restrictions file needs to be updated
854    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
855
856    final private DefaultContainerConnection mDefContainerConn =
857            new DefaultContainerConnection();
858    class DefaultContainerConnection implements ServiceConnection {
859        public void onServiceConnected(ComponentName name, IBinder service) {
860            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
861            IMediaContainerService imcs =
862                IMediaContainerService.Stub.asInterface(service);
863            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
864        }
865
866        public void onServiceDisconnected(ComponentName name) {
867            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
868        }
869    };
870
871    // Recordkeeping of restore-after-install operations that are currently in flight
872    // between the Package Manager and the Backup Manager
873    class PostInstallData {
874        public InstallArgs args;
875        public PackageInstalledInfo res;
876
877        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
878            args = _a;
879            res = _r;
880        }
881    };
882    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
883    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
884
885    // backup/restore of preferred activity state
886    private static final String TAG_PREFERRED_BACKUP = "pa";
887
888    private final String mRequiredVerifierPackage;
889
890    private final PackageUsage mPackageUsage = new PackageUsage();
891
892    private class PackageUsage {
893        private static final int WRITE_INTERVAL
894            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
895
896        private final Object mFileLock = new Object();
897        private final AtomicLong mLastWritten = new AtomicLong(0);
898        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
899
900        private boolean mIsHistoricalPackageUsageAvailable = true;
901
902        boolean isHistoricalPackageUsageAvailable() {
903            return mIsHistoricalPackageUsageAvailable;
904        }
905
906        void write(boolean force) {
907            if (force) {
908                writeInternal();
909                return;
910            }
911            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
912                && !DEBUG_DEXOPT) {
913                return;
914            }
915            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
916                new Thread("PackageUsage_DiskWriter") {
917                    @Override
918                    public void run() {
919                        try {
920                            writeInternal();
921                        } finally {
922                            mBackgroundWriteRunning.set(false);
923                        }
924                    }
925                }.start();
926            }
927        }
928
929        private void writeInternal() {
930            synchronized (mPackages) {
931                synchronized (mFileLock) {
932                    AtomicFile file = getFile();
933                    FileOutputStream f = null;
934                    try {
935                        f = file.startWrite();
936                        BufferedOutputStream out = new BufferedOutputStream(f);
937                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
938                        StringBuilder sb = new StringBuilder();
939                        for (PackageParser.Package pkg : mPackages.values()) {
940                            if (pkg.mLastPackageUsageTimeInMills == 0) {
941                                continue;
942                            }
943                            sb.setLength(0);
944                            sb.append(pkg.packageName);
945                            sb.append(' ');
946                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
947                            sb.append('\n');
948                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
949                        }
950                        out.flush();
951                        file.finishWrite(f);
952                    } catch (IOException e) {
953                        if (f != null) {
954                            file.failWrite(f);
955                        }
956                        Log.e(TAG, "Failed to write package usage times", e);
957                    }
958                }
959            }
960            mLastWritten.set(SystemClock.elapsedRealtime());
961        }
962
963        void readLP() {
964            synchronized (mFileLock) {
965                AtomicFile file = getFile();
966                BufferedInputStream in = null;
967                try {
968                    in = new BufferedInputStream(file.openRead());
969                    StringBuffer sb = new StringBuffer();
970                    while (true) {
971                        String packageName = readToken(in, sb, ' ');
972                        if (packageName == null) {
973                            break;
974                        }
975                        String timeInMillisString = readToken(in, sb, '\n');
976                        if (timeInMillisString == null) {
977                            throw new IOException("Failed to find last usage time for package "
978                                                  + packageName);
979                        }
980                        PackageParser.Package pkg = mPackages.get(packageName);
981                        if (pkg == null) {
982                            continue;
983                        }
984                        long timeInMillis;
985                        try {
986                            timeInMillis = Long.parseLong(timeInMillisString.toString());
987                        } catch (NumberFormatException e) {
988                            throw new IOException("Failed to parse " + timeInMillisString
989                                                  + " as a long.", e);
990                        }
991                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
992                    }
993                } catch (FileNotFoundException expected) {
994                    mIsHistoricalPackageUsageAvailable = false;
995                } catch (IOException e) {
996                    Log.w(TAG, "Failed to read package usage times", e);
997                } finally {
998                    IoUtils.closeQuietly(in);
999                }
1000            }
1001            mLastWritten.set(SystemClock.elapsedRealtime());
1002        }
1003
1004        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1005                throws IOException {
1006            sb.setLength(0);
1007            while (true) {
1008                int ch = in.read();
1009                if (ch == -1) {
1010                    if (sb.length() == 0) {
1011                        return null;
1012                    }
1013                    throw new IOException("Unexpected EOF");
1014                }
1015                if (ch == endOfToken) {
1016                    return sb.toString();
1017                }
1018                sb.append((char)ch);
1019            }
1020        }
1021
1022        private AtomicFile getFile() {
1023            File dataDir = Environment.getDataDirectory();
1024            File systemDir = new File(dataDir, "system");
1025            File fname = new File(systemDir, "package-usage.list");
1026            return new AtomicFile(fname);
1027        }
1028    }
1029
1030    class PackageHandler extends Handler {
1031        private boolean mBound = false;
1032        final ArrayList<HandlerParams> mPendingInstalls =
1033            new ArrayList<HandlerParams>();
1034
1035        private boolean connectToService() {
1036            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1037                    " DefaultContainerService");
1038            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1039            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1040            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1041                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1042                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1043                mBound = true;
1044                return true;
1045            }
1046            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1047            return false;
1048        }
1049
1050        private void disconnectService() {
1051            mContainerService = null;
1052            mBound = false;
1053            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1054            mContext.unbindService(mDefContainerConn);
1055            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1056        }
1057
1058        PackageHandler(Looper looper) {
1059            super(looper);
1060        }
1061
1062        public void handleMessage(Message msg) {
1063            try {
1064                doHandleMessage(msg);
1065            } finally {
1066                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1067            }
1068        }
1069
1070        void doHandleMessage(Message msg) {
1071            switch (msg.what) {
1072                case INIT_COPY: {
1073                    HandlerParams params = (HandlerParams) msg.obj;
1074                    int idx = mPendingInstalls.size();
1075                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1076                    // If a bind was already initiated we dont really
1077                    // need to do anything. The pending install
1078                    // will be processed later on.
1079                    if (!mBound) {
1080                        // If this is the only one pending we might
1081                        // have to bind to the service again.
1082                        if (!connectToService()) {
1083                            Slog.e(TAG, "Failed to bind to media container service");
1084                            params.serviceError();
1085                            return;
1086                        } else {
1087                            // Once we bind to the service, the first
1088                            // pending request will be processed.
1089                            mPendingInstalls.add(idx, params);
1090                        }
1091                    } else {
1092                        mPendingInstalls.add(idx, params);
1093                        // Already bound to the service. Just make
1094                        // sure we trigger off processing the first request.
1095                        if (idx == 0) {
1096                            mHandler.sendEmptyMessage(MCS_BOUND);
1097                        }
1098                    }
1099                    break;
1100                }
1101                case MCS_BOUND: {
1102                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1103                    if (msg.obj != null) {
1104                        mContainerService = (IMediaContainerService) msg.obj;
1105                    }
1106                    if (mContainerService == null) {
1107                        // Something seriously wrong. Bail out
1108                        Slog.e(TAG, "Cannot bind to media container service");
1109                        for (HandlerParams params : mPendingInstalls) {
1110                            // Indicate service bind error
1111                            params.serviceError();
1112                        }
1113                        mPendingInstalls.clear();
1114                    } else if (mPendingInstalls.size() > 0) {
1115                        HandlerParams params = mPendingInstalls.get(0);
1116                        if (params != null) {
1117                            if (params.startCopy()) {
1118                                // We are done...  look for more work or to
1119                                // go idle.
1120                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1121                                        "Checking for more work or unbind...");
1122                                // Delete pending install
1123                                if (mPendingInstalls.size() > 0) {
1124                                    mPendingInstalls.remove(0);
1125                                }
1126                                if (mPendingInstalls.size() == 0) {
1127                                    if (mBound) {
1128                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1129                                                "Posting delayed MCS_UNBIND");
1130                                        removeMessages(MCS_UNBIND);
1131                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1132                                        // Unbind after a little delay, to avoid
1133                                        // continual thrashing.
1134                                        sendMessageDelayed(ubmsg, 10000);
1135                                    }
1136                                } else {
1137                                    // There are more pending requests in queue.
1138                                    // Just post MCS_BOUND message to trigger processing
1139                                    // of next pending install.
1140                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1141                                            "Posting MCS_BOUND for next work");
1142                                    mHandler.sendEmptyMessage(MCS_BOUND);
1143                                }
1144                            }
1145                        }
1146                    } else {
1147                        // Should never happen ideally.
1148                        Slog.w(TAG, "Empty queue");
1149                    }
1150                    break;
1151                }
1152                case MCS_RECONNECT: {
1153                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1154                    if (mPendingInstalls.size() > 0) {
1155                        if (mBound) {
1156                            disconnectService();
1157                        }
1158                        if (!connectToService()) {
1159                            Slog.e(TAG, "Failed to bind to media container service");
1160                            for (HandlerParams params : mPendingInstalls) {
1161                                // Indicate service bind error
1162                                params.serviceError();
1163                            }
1164                            mPendingInstalls.clear();
1165                        }
1166                    }
1167                    break;
1168                }
1169                case MCS_UNBIND: {
1170                    // If there is no actual work left, then time to unbind.
1171                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1172
1173                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1174                        if (mBound) {
1175                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1176
1177                            disconnectService();
1178                        }
1179                    } else if (mPendingInstalls.size() > 0) {
1180                        // There are more pending requests in queue.
1181                        // Just post MCS_BOUND message to trigger processing
1182                        // of next pending install.
1183                        mHandler.sendEmptyMessage(MCS_BOUND);
1184                    }
1185
1186                    break;
1187                }
1188                case MCS_GIVE_UP: {
1189                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1190                    mPendingInstalls.remove(0);
1191                    break;
1192                }
1193                case SEND_PENDING_BROADCAST: {
1194                    String packages[];
1195                    ArrayList<String> components[];
1196                    int size = 0;
1197                    int uids[];
1198                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1199                    synchronized (mPackages) {
1200                        if (mPendingBroadcasts == null) {
1201                            return;
1202                        }
1203                        size = mPendingBroadcasts.size();
1204                        if (size <= 0) {
1205                            // Nothing to be done. Just return
1206                            return;
1207                        }
1208                        packages = new String[size];
1209                        components = new ArrayList[size];
1210                        uids = new int[size];
1211                        int i = 0;  // filling out the above arrays
1212
1213                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1214                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1215                            Iterator<Map.Entry<String, ArrayList<String>>> it
1216                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1217                                            .entrySet().iterator();
1218                            while (it.hasNext() && i < size) {
1219                                Map.Entry<String, ArrayList<String>> ent = it.next();
1220                                packages[i] = ent.getKey();
1221                                components[i] = ent.getValue();
1222                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1223                                uids[i] = (ps != null)
1224                                        ? UserHandle.getUid(packageUserId, ps.appId)
1225                                        : -1;
1226                                i++;
1227                            }
1228                        }
1229                        size = i;
1230                        mPendingBroadcasts.clear();
1231                    }
1232                    // Send broadcasts
1233                    for (int i = 0; i < size; i++) {
1234                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1235                    }
1236                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1237                    break;
1238                }
1239                case START_CLEANING_PACKAGE: {
1240                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1241                    final String packageName = (String)msg.obj;
1242                    final int userId = msg.arg1;
1243                    final boolean andCode = msg.arg2 != 0;
1244                    synchronized (mPackages) {
1245                        if (userId == UserHandle.USER_ALL) {
1246                            int[] users = sUserManager.getUserIds();
1247                            for (int user : users) {
1248                                mSettings.addPackageToCleanLPw(
1249                                        new PackageCleanItem(user, packageName, andCode));
1250                            }
1251                        } else {
1252                            mSettings.addPackageToCleanLPw(
1253                                    new PackageCleanItem(userId, packageName, andCode));
1254                        }
1255                    }
1256                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1257                    startCleaningPackages();
1258                } break;
1259                case POST_INSTALL: {
1260                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1261                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1262                    mRunningInstalls.delete(msg.arg1);
1263                    boolean deleteOld = false;
1264
1265                    if (data != null) {
1266                        InstallArgs args = data.args;
1267                        PackageInstalledInfo res = data.res;
1268
1269                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1270                            res.removedInfo.sendBroadcast(false, true, false);
1271                            Bundle extras = new Bundle(1);
1272                            extras.putInt(Intent.EXTRA_UID, res.uid);
1273
1274                            // Now that we successfully installed the package, grant runtime
1275                            // permissions if requested before broadcasting the install.
1276                            if ((args.installFlags
1277                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1278                                grantRequestedRuntimePermissions(res.pkg,
1279                                        args.user.getIdentifier());
1280                            }
1281
1282                            // Determine the set of users who are adding this
1283                            // package for the first time vs. those who are seeing
1284                            // an update.
1285                            int[] firstUsers;
1286                            int[] updateUsers = new int[0];
1287                            if (res.origUsers == null || res.origUsers.length == 0) {
1288                                firstUsers = res.newUsers;
1289                            } else {
1290                                firstUsers = new int[0];
1291                                for (int i=0; i<res.newUsers.length; i++) {
1292                                    int user = res.newUsers[i];
1293                                    boolean isNew = true;
1294                                    for (int j=0; j<res.origUsers.length; j++) {
1295                                        if (res.origUsers[j] == user) {
1296                                            isNew = false;
1297                                            break;
1298                                        }
1299                                    }
1300                                    if (isNew) {
1301                                        int[] newFirst = new int[firstUsers.length+1];
1302                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1303                                                firstUsers.length);
1304                                        newFirst[firstUsers.length] = user;
1305                                        firstUsers = newFirst;
1306                                    } else {
1307                                        int[] newUpdate = new int[updateUsers.length+1];
1308                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1309                                                updateUsers.length);
1310                                        newUpdate[updateUsers.length] = user;
1311                                        updateUsers = newUpdate;
1312                                    }
1313                                }
1314                            }
1315                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1316                                    res.pkg.applicationInfo.packageName,
1317                                    extras, null, null, firstUsers);
1318                            final boolean update = res.removedInfo.removedPackage != null;
1319                            if (update) {
1320                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1321                            }
1322                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1323                                    res.pkg.applicationInfo.packageName,
1324                                    extras, null, null, updateUsers);
1325                            if (update) {
1326                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1327                                        res.pkg.applicationInfo.packageName,
1328                                        extras, null, null, updateUsers);
1329                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1330                                        null, null,
1331                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1332
1333                                // treat asec-hosted packages like removable media on upgrade
1334                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1335                                    if (DEBUG_INSTALL) {
1336                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1337                                                + " is ASEC-hosted -> AVAILABLE");
1338                                    }
1339                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1340                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1341                                    pkgList.add(res.pkg.applicationInfo.packageName);
1342                                    sendResourcesChangedBroadcast(true, true,
1343                                            pkgList,uidArray, null);
1344                                }
1345                            }
1346                            if (res.removedInfo.args != null) {
1347                                // Remove the replaced package's older resources safely now
1348                                deleteOld = true;
1349                            }
1350
1351                            // Log current value of "unknown sources" setting
1352                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1353                                getUnknownSourcesSettings());
1354                        }
1355                        // Force a gc to clear up things
1356                        Runtime.getRuntime().gc();
1357                        // We delete after a gc for applications  on sdcard.
1358                        if (deleteOld) {
1359                            synchronized (mInstallLock) {
1360                                res.removedInfo.args.doPostDeleteLI(true);
1361                            }
1362                        }
1363                        if (args.observer != null) {
1364                            try {
1365                                Bundle extras = extrasForInstallResult(res);
1366                                args.observer.onPackageInstalled(res.name, res.returnCode,
1367                                        res.returnMsg, extras);
1368                            } catch (RemoteException e) {
1369                                Slog.i(TAG, "Observer no longer exists.");
1370                            }
1371                        }
1372                    } else {
1373                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1374                    }
1375                } break;
1376                case UPDATED_MEDIA_STATUS: {
1377                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1378                    boolean reportStatus = msg.arg1 == 1;
1379                    boolean doGc = msg.arg2 == 1;
1380                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1381                    if (doGc) {
1382                        // Force a gc to clear up stale containers.
1383                        Runtime.getRuntime().gc();
1384                    }
1385                    if (msg.obj != null) {
1386                        @SuppressWarnings("unchecked")
1387                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1388                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1389                        // Unload containers
1390                        unloadAllContainers(args);
1391                    }
1392                    if (reportStatus) {
1393                        try {
1394                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1395                            PackageHelper.getMountService().finishMediaUpdate();
1396                        } catch (RemoteException e) {
1397                            Log.e(TAG, "MountService not running?");
1398                        }
1399                    }
1400                } break;
1401                case WRITE_SETTINGS: {
1402                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1403                    synchronized (mPackages) {
1404                        removeMessages(WRITE_SETTINGS);
1405                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1406                        mSettings.writeLPr();
1407                        mDirtyUsers.clear();
1408                    }
1409                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1410                } break;
1411                case WRITE_PACKAGE_RESTRICTIONS: {
1412                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1413                    synchronized (mPackages) {
1414                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1415                        for (int userId : mDirtyUsers) {
1416                            mSettings.writePackageRestrictionsLPr(userId);
1417                        }
1418                        mDirtyUsers.clear();
1419                    }
1420                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1421                } break;
1422                case CHECK_PENDING_VERIFICATION: {
1423                    final int verificationId = msg.arg1;
1424                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1425
1426                    if ((state != null) && !state.timeoutExtended()) {
1427                        final InstallArgs args = state.getInstallArgs();
1428                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1429
1430                        Slog.i(TAG, "Verification timed out for " + originUri);
1431                        mPendingVerification.remove(verificationId);
1432
1433                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1434
1435                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1436                            Slog.i(TAG, "Continuing with installation of " + originUri);
1437                            state.setVerifierResponse(Binder.getCallingUid(),
1438                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1439                            broadcastPackageVerified(verificationId, originUri,
1440                                    PackageManager.VERIFICATION_ALLOW,
1441                                    state.getInstallArgs().getUser());
1442                            try {
1443                                ret = args.copyApk(mContainerService, true);
1444                            } catch (RemoteException e) {
1445                                Slog.e(TAG, "Could not contact the ContainerService");
1446                            }
1447                        } else {
1448                            broadcastPackageVerified(verificationId, originUri,
1449                                    PackageManager.VERIFICATION_REJECT,
1450                                    state.getInstallArgs().getUser());
1451                        }
1452
1453                        processPendingInstall(args, ret);
1454                        mHandler.sendEmptyMessage(MCS_UNBIND);
1455                    }
1456                    break;
1457                }
1458                case PACKAGE_VERIFIED: {
1459                    final int verificationId = msg.arg1;
1460
1461                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1462                    if (state == null) {
1463                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1464                        break;
1465                    }
1466
1467                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1468
1469                    state.setVerifierResponse(response.callerUid, response.code);
1470
1471                    if (state.isVerificationComplete()) {
1472                        mPendingVerification.remove(verificationId);
1473
1474                        final InstallArgs args = state.getInstallArgs();
1475                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1476
1477                        int ret;
1478                        if (state.isInstallAllowed()) {
1479                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1480                            broadcastPackageVerified(verificationId, originUri,
1481                                    response.code, state.getInstallArgs().getUser());
1482                            try {
1483                                ret = args.copyApk(mContainerService, true);
1484                            } catch (RemoteException e) {
1485                                Slog.e(TAG, "Could not contact the ContainerService");
1486                            }
1487                        } else {
1488                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1489                        }
1490
1491                        processPendingInstall(args, ret);
1492
1493                        mHandler.sendEmptyMessage(MCS_UNBIND);
1494                    }
1495
1496                    break;
1497                }
1498                case START_INTENT_FILTER_VERIFICATIONS: {
1499                    int userId = msg.arg1;
1500                    int verifierUid = msg.arg2;
1501                    PackageParser.Package pkg = (PackageParser.Package)msg.obj;
1502
1503                    verifyIntentFiltersIfNeeded(userId, verifierUid, pkg);
1504                    break;
1505                }
1506                case INTENT_FILTER_VERIFIED: {
1507                    final int verificationId = msg.arg1;
1508
1509                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1510                            verificationId);
1511                    if (state == null) {
1512                        Slog.w(TAG, "Invalid IntentFilter verification token "
1513                                + verificationId + " received");
1514                        break;
1515                    }
1516
1517                    final int userId = state.getUserId();
1518
1519                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1520                            "Processing IntentFilter verification with token:"
1521                            + verificationId + " and userId:" + userId);
1522
1523                    final IntentFilterVerificationResponse response =
1524                            (IntentFilterVerificationResponse) msg.obj;
1525
1526                    state.setVerifierResponse(response.callerUid, response.code);
1527
1528                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1529                            "IntentFilter verification with token:" + verificationId
1530                            + " and userId:" + userId
1531                            + " is settings verifier response with response code:"
1532                            + response.code);
1533
1534                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1535                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1536                                + response.getFailedDomainsString());
1537                    }
1538
1539                    if (state.isVerificationComplete()) {
1540                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1541                    } else {
1542                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1543                                "IntentFilter verification with token:" + verificationId
1544                                + " was not said to be complete");
1545                    }
1546
1547                    break;
1548                }
1549            }
1550        }
1551    }
1552
1553    private StorageEventListener mStorageListener = new StorageEventListener() {
1554        @Override
1555        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1556            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1557                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1558                    // TODO: ensure that private directories exist for all active users
1559                    // TODO: remove user data whose serial number doesn't match
1560                    loadPrivatePackages(vol);
1561                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1562                    unloadPrivatePackages(vol);
1563                }
1564            }
1565
1566            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1567                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1568                    updateExternalMediaStatus(true, false);
1569                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1570                    updateExternalMediaStatus(false, false);
1571                }
1572            }
1573        }
1574
1575        @Override
1576        public void onVolumeForgotten(String fsUuid) {
1577            // TODO: remove all packages hosted on this uuid
1578        }
1579    };
1580
1581    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) {
1582        if (userId >= UserHandle.USER_OWNER) {
1583            grantRequestedRuntimePermissionsForUser(pkg, userId);
1584        } else if (userId == UserHandle.USER_ALL) {
1585            for (int someUserId : UserManagerService.getInstance().getUserIds()) {
1586                grantRequestedRuntimePermissionsForUser(pkg, someUserId);
1587            }
1588        }
1589    }
1590
1591    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) {
1592        SettingBase sb = (SettingBase) pkg.mExtras;
1593        if (sb == null) {
1594            return;
1595        }
1596
1597        PermissionsState permissionsState = sb.getPermissionsState();
1598
1599        for (String permission : pkg.requestedPermissions) {
1600            BasePermission bp = mSettings.mPermissions.get(permission);
1601            if (bp != null && bp.isRuntime()) {
1602                permissionsState.grantRuntimePermission(bp, userId);
1603            }
1604        }
1605    }
1606
1607    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1608        Bundle extras = null;
1609        switch (res.returnCode) {
1610            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1611                extras = new Bundle();
1612                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1613                        res.origPermission);
1614                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1615                        res.origPackage);
1616                break;
1617            }
1618            case PackageManager.INSTALL_SUCCEEDED: {
1619                extras = new Bundle();
1620                extras.putBoolean(Intent.EXTRA_REPLACING,
1621                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1622                break;
1623            }
1624        }
1625        return extras;
1626    }
1627
1628    void scheduleWriteSettingsLocked() {
1629        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1630            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1631        }
1632    }
1633
1634    void scheduleWritePackageRestrictionsLocked(int userId) {
1635        if (!sUserManager.exists(userId)) return;
1636        mDirtyUsers.add(userId);
1637        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1638            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1639        }
1640    }
1641
1642    public static PackageManagerService main(Context context, Installer installer,
1643            boolean factoryTest, boolean onlyCore) {
1644        PackageManagerService m = new PackageManagerService(context, installer,
1645                factoryTest, onlyCore);
1646        ServiceManager.addService("package", m);
1647        return m;
1648    }
1649
1650    static String[] splitString(String str, char sep) {
1651        int count = 1;
1652        int i = 0;
1653        while ((i=str.indexOf(sep, i)) >= 0) {
1654            count++;
1655            i++;
1656        }
1657
1658        String[] res = new String[count];
1659        i=0;
1660        count = 0;
1661        int lastI=0;
1662        while ((i=str.indexOf(sep, i)) >= 0) {
1663            res[count] = str.substring(lastI, i);
1664            count++;
1665            i++;
1666            lastI = i;
1667        }
1668        res[count] = str.substring(lastI, str.length());
1669        return res;
1670    }
1671
1672    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1673        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1674                Context.DISPLAY_SERVICE);
1675        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1676    }
1677
1678    public PackageManagerService(Context context, Installer installer,
1679            boolean factoryTest, boolean onlyCore) {
1680        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1681                SystemClock.uptimeMillis());
1682
1683        if (mSdkVersion <= 0) {
1684            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1685        }
1686
1687        mContext = context;
1688        mFactoryTest = factoryTest;
1689        mOnlyCore = onlyCore;
1690        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1691        mMetrics = new DisplayMetrics();
1692        mSettings = new Settings(mPackages);
1693        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1694                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1695        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1696                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1697        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1698                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1699        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1700                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1701        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1702                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1703        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1704                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1705
1706        // TODO: add a property to control this?
1707        long dexOptLRUThresholdInMinutes;
1708        if (mLazyDexOpt) {
1709            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1710        } else {
1711            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1712        }
1713        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1714
1715        String separateProcesses = SystemProperties.get("debug.separate_processes");
1716        if (separateProcesses != null && separateProcesses.length() > 0) {
1717            if ("*".equals(separateProcesses)) {
1718                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1719                mSeparateProcesses = null;
1720                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1721            } else {
1722                mDefParseFlags = 0;
1723                mSeparateProcesses = separateProcesses.split(",");
1724                Slog.w(TAG, "Running with debug.separate_processes: "
1725                        + separateProcesses);
1726            }
1727        } else {
1728            mDefParseFlags = 0;
1729            mSeparateProcesses = null;
1730        }
1731
1732        mInstaller = installer;
1733        mPackageDexOptimizer = new PackageDexOptimizer(this);
1734        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1735
1736        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1737                FgThread.get().getLooper());
1738
1739        getDefaultDisplayMetrics(context, mMetrics);
1740
1741        SystemConfig systemConfig = SystemConfig.getInstance();
1742        mGlobalGids = systemConfig.getGlobalGids();
1743        mSystemPermissions = systemConfig.getSystemPermissions();
1744        mAvailableFeatures = systemConfig.getAvailableFeatures();
1745
1746        synchronized (mInstallLock) {
1747        // writer
1748        synchronized (mPackages) {
1749            mHandlerThread = new ServiceThread(TAG,
1750                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1751            mHandlerThread.start();
1752            mHandler = new PackageHandler(mHandlerThread.getLooper());
1753            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1754
1755            File dataDir = Environment.getDataDirectory();
1756            mAppDataDir = new File(dataDir, "data");
1757            mAppInstallDir = new File(dataDir, "app");
1758            mAppLib32InstallDir = new File(dataDir, "app-lib");
1759            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1760            mUserAppDataDir = new File(dataDir, "user");
1761            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1762
1763            sUserManager = new UserManagerService(context, this,
1764                    mInstallLock, mPackages);
1765
1766            // Propagate permission configuration in to package manager.
1767            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1768                    = systemConfig.getPermissions();
1769            for (int i=0; i<permConfig.size(); i++) {
1770                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1771                BasePermission bp = mSettings.mPermissions.get(perm.name);
1772                if (bp == null) {
1773                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1774                    mSettings.mPermissions.put(perm.name, bp);
1775                }
1776                if (perm.gids != null) {
1777                    bp.setGids(perm.gids, perm.perUser);
1778                }
1779            }
1780
1781            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1782            for (int i=0; i<libConfig.size(); i++) {
1783                mSharedLibraries.put(libConfig.keyAt(i),
1784                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1785            }
1786
1787            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1788
1789            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1790                    mSdkVersion, mOnlyCore);
1791
1792            String customResolverActivity = Resources.getSystem().getString(
1793                    R.string.config_customResolverActivity);
1794            if (TextUtils.isEmpty(customResolverActivity)) {
1795                customResolverActivity = null;
1796            } else {
1797                mCustomResolverComponentName = ComponentName.unflattenFromString(
1798                        customResolverActivity);
1799            }
1800
1801            long startTime = SystemClock.uptimeMillis();
1802
1803            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1804                    startTime);
1805
1806            // Set flag to monitor and not change apk file paths when
1807            // scanning install directories.
1808            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1809
1810            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1811
1812            /**
1813             * Add everything in the in the boot class path to the
1814             * list of process files because dexopt will have been run
1815             * if necessary during zygote startup.
1816             */
1817            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1818            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1819
1820            if (bootClassPath != null) {
1821                String[] bootClassPathElements = splitString(bootClassPath, ':');
1822                for (String element : bootClassPathElements) {
1823                    alreadyDexOpted.add(element);
1824                }
1825            } else {
1826                Slog.w(TAG, "No BOOTCLASSPATH found!");
1827            }
1828
1829            if (systemServerClassPath != null) {
1830                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1831                for (String element : systemServerClassPathElements) {
1832                    alreadyDexOpted.add(element);
1833                }
1834            } else {
1835                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1836            }
1837
1838            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1839            final String[] dexCodeInstructionSets =
1840                    getDexCodeInstructionSets(
1841                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1842
1843            /**
1844             * Ensure all external libraries have had dexopt run on them.
1845             */
1846            if (mSharedLibraries.size() > 0) {
1847                // NOTE: For now, we're compiling these system "shared libraries"
1848                // (and framework jars) into all available architectures. It's possible
1849                // to compile them only when we come across an app that uses them (there's
1850                // already logic for that in scanPackageLI) but that adds some complexity.
1851                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1852                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1853                        final String lib = libEntry.path;
1854                        if (lib == null) {
1855                            continue;
1856                        }
1857
1858                        try {
1859                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1860                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1861                                alreadyDexOpted.add(lib);
1862                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1863                            }
1864                        } catch (FileNotFoundException e) {
1865                            Slog.w(TAG, "Library not found: " + lib);
1866                        } catch (IOException e) {
1867                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1868                                    + e.getMessage());
1869                        }
1870                    }
1871                }
1872            }
1873
1874            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1875
1876            // Gross hack for now: we know this file doesn't contain any
1877            // code, so don't dexopt it to avoid the resulting log spew.
1878            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1879
1880            // Gross hack for now: we know this file is only part of
1881            // the boot class path for art, so don't dexopt it to
1882            // avoid the resulting log spew.
1883            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1884
1885            /**
1886             * There are a number of commands implemented in Java, which
1887             * we currently need to do the dexopt on so that they can be
1888             * run from a non-root shell.
1889             */
1890            String[] frameworkFiles = frameworkDir.list();
1891            if (frameworkFiles != null) {
1892                // TODO: We could compile these only for the most preferred ABI. We should
1893                // first double check that the dex files for these commands are not referenced
1894                // by other system apps.
1895                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1896                    for (int i=0; i<frameworkFiles.length; i++) {
1897                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1898                        String path = libPath.getPath();
1899                        // Skip the file if we already did it.
1900                        if (alreadyDexOpted.contains(path)) {
1901                            continue;
1902                        }
1903                        // Skip the file if it is not a type we want to dexopt.
1904                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1905                            continue;
1906                        }
1907                        try {
1908                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
1909                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1910                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1911                            }
1912                        } catch (FileNotFoundException e) {
1913                            Slog.w(TAG, "Jar not found: " + path);
1914                        } catch (IOException e) {
1915                            Slog.w(TAG, "Exception reading jar: " + path, e);
1916                        }
1917                    }
1918                }
1919            }
1920
1921            // Collect vendor overlay packages.
1922            // (Do this before scanning any apps.)
1923            // For security and version matching reason, only consider
1924            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1925            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1926            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1927                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1928
1929            // Find base frameworks (resource packages without code).
1930            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1931                    | PackageParser.PARSE_IS_SYSTEM_DIR
1932                    | PackageParser.PARSE_IS_PRIVILEGED,
1933                    scanFlags | SCAN_NO_DEX, 0);
1934
1935            // Collected privileged system packages.
1936            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1937            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1938                    | PackageParser.PARSE_IS_SYSTEM_DIR
1939                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1940
1941            // Collect ordinary system packages.
1942            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
1943            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1944                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1945
1946            // Collect all vendor packages.
1947            File vendorAppDir = new File("/vendor/app");
1948            try {
1949                vendorAppDir = vendorAppDir.getCanonicalFile();
1950            } catch (IOException e) {
1951                // failed to look up canonical path, continue with original one
1952            }
1953            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1954                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1955
1956            // Collect all OEM packages.
1957            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
1958            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1959                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1960
1961            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1962            mInstaller.moveFiles();
1963
1964            // Prune any system packages that no longer exist.
1965            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1966            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
1967            if (!mOnlyCore) {
1968                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1969                while (psit.hasNext()) {
1970                    PackageSetting ps = psit.next();
1971
1972                    /*
1973                     * If this is not a system app, it can't be a
1974                     * disable system app.
1975                     */
1976                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1977                        continue;
1978                    }
1979
1980                    /*
1981                     * If the package is scanned, it's not erased.
1982                     */
1983                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1984                    if (scannedPkg != null) {
1985                        /*
1986                         * If the system app is both scanned and in the
1987                         * disabled packages list, then it must have been
1988                         * added via OTA. Remove it from the currently
1989                         * scanned package so the previously user-installed
1990                         * application can be scanned.
1991                         */
1992                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1993                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
1994                                    + ps.name + "; removing system app.  Last known codePath="
1995                                    + ps.codePathString + ", installStatus=" + ps.installStatus
1996                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
1997                                    + scannedPkg.mVersionCode);
1998                            removePackageLI(ps, true);
1999                            expectingBetter.put(ps.name, ps.codePath);
2000                        }
2001
2002                        continue;
2003                    }
2004
2005                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2006                        psit.remove();
2007                        logCriticalInfo(Log.WARN, "System package " + ps.name
2008                                + " no longer exists; wiping its data");
2009                        removeDataDirsLI(null, ps.name);
2010                    } else {
2011                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2012                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2013                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2014                        }
2015                    }
2016                }
2017            }
2018
2019            //look for any incomplete package installations
2020            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2021            //clean up list
2022            for(int i = 0; i < deletePkgsList.size(); i++) {
2023                //clean up here
2024                cleanupInstallFailedPackage(deletePkgsList.get(i));
2025            }
2026            //delete tmp files
2027            deleteTempPackageFiles();
2028
2029            // Remove any shared userIDs that have no associated packages
2030            mSettings.pruneSharedUsersLPw();
2031
2032            if (!mOnlyCore) {
2033                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2034                        SystemClock.uptimeMillis());
2035                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2036
2037                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2038                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2039
2040                /**
2041                 * Remove disable package settings for any updated system
2042                 * apps that were removed via an OTA. If they're not a
2043                 * previously-updated app, remove them completely.
2044                 * Otherwise, just revoke their system-level permissions.
2045                 */
2046                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2047                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2048                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2049
2050                    String msg;
2051                    if (deletedPkg == null) {
2052                        msg = "Updated system package " + deletedAppName
2053                                + " no longer exists; wiping its data";
2054                        removeDataDirsLI(null, deletedAppName);
2055                    } else {
2056                        msg = "Updated system app + " + deletedAppName
2057                                + " no longer present; removing system privileges for "
2058                                + deletedAppName;
2059
2060                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2061
2062                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2063                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2064                    }
2065                    logCriticalInfo(Log.WARN, msg);
2066                }
2067
2068                /**
2069                 * Make sure all system apps that we expected to appear on
2070                 * the userdata partition actually showed up. If they never
2071                 * appeared, crawl back and revive the system version.
2072                 */
2073                for (int i = 0; i < expectingBetter.size(); i++) {
2074                    final String packageName = expectingBetter.keyAt(i);
2075                    if (!mPackages.containsKey(packageName)) {
2076                        final File scanFile = expectingBetter.valueAt(i);
2077
2078                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2079                                + " but never showed up; reverting to system");
2080
2081                        final int reparseFlags;
2082                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2083                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2084                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2085                                    | PackageParser.PARSE_IS_PRIVILEGED;
2086                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2087                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2088                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2089                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2090                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2091                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2092                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2093                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2094                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2095                        } else {
2096                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2097                            continue;
2098                        }
2099
2100                        mSettings.enableSystemPackageLPw(packageName);
2101
2102                        try {
2103                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2104                        } catch (PackageManagerException e) {
2105                            Slog.e(TAG, "Failed to parse original system package: "
2106                                    + e.getMessage());
2107                        }
2108                    }
2109                }
2110            }
2111
2112            // Now that we know all of the shared libraries, update all clients to have
2113            // the correct library paths.
2114            updateAllSharedLibrariesLPw();
2115
2116            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2117                // NOTE: We ignore potential failures here during a system scan (like
2118                // the rest of the commands above) because there's precious little we
2119                // can do about it. A settings error is reported, though.
2120                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2121                        false /* force dexopt */, false /* defer dexopt */);
2122            }
2123
2124            // Now that we know all the packages we are keeping,
2125            // read and update their last usage times.
2126            mPackageUsage.readLP();
2127
2128            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2129                    SystemClock.uptimeMillis());
2130            Slog.i(TAG, "Time to scan packages: "
2131                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2132                    + " seconds");
2133
2134            // If the platform SDK has changed since the last time we booted,
2135            // we need to re-grant app permission to catch any new ones that
2136            // appear.  This is really a hack, and means that apps can in some
2137            // cases get permissions that the user didn't initially explicitly
2138            // allow...  it would be nice to have some better way to handle
2139            // this situation.
2140            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
2141                    != mSdkVersion;
2142            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
2143                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
2144                    + "; regranting permissions for internal storage");
2145            mSettings.mInternalSdkPlatform = mSdkVersion;
2146
2147            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
2148                    | (regrantPermissions
2149                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
2150                            : 0));
2151
2152            // If this is the first boot, and it is a normal boot, then
2153            // we need to initialize the default preferred apps.
2154            if (!mRestoredSettings && !onlyCore) {
2155                mSettings.readDefaultPreferredAppsLPw(this, 0);
2156            }
2157
2158            // If this is first boot after an OTA, and a normal boot, then
2159            // we need to clear code cache directories.
2160            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
2161            if (mIsUpgrade && !onlyCore) {
2162                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2163                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2164                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2165                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2166                }
2167                mSettings.mFingerprint = Build.FINGERPRINT;
2168            }
2169
2170            primeDomainVerificationsLPw();
2171            checkDefaultBrowser();
2172
2173            // All the changes are done during package scanning.
2174            mSettings.updateInternalDatabaseVersion();
2175
2176            // can downgrade to reader
2177            mSettings.writeLPr();
2178
2179            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2180                    SystemClock.uptimeMillis());
2181
2182            mRequiredVerifierPackage = getRequiredVerifierLPr();
2183
2184            mInstallerService = new PackageInstallerService(context, this);
2185
2186            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2187            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2188                    mIntentFilterVerifierComponent);
2189
2190        } // synchronized (mPackages)
2191        } // synchronized (mInstallLock)
2192
2193        // Now after opening every single application zip, make sure they
2194        // are all flushed.  Not really needed, but keeps things nice and
2195        // tidy.
2196        Runtime.getRuntime().gc();
2197    }
2198
2199    @Override
2200    public boolean isFirstBoot() {
2201        return !mRestoredSettings;
2202    }
2203
2204    @Override
2205    public boolean isOnlyCoreApps() {
2206        return mOnlyCore;
2207    }
2208
2209    @Override
2210    public boolean isUpgrade() {
2211        return mIsUpgrade;
2212    }
2213
2214    private String getRequiredVerifierLPr() {
2215        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2216        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2217                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2218
2219        String requiredVerifier = null;
2220
2221        final int N = receivers.size();
2222        for (int i = 0; i < N; i++) {
2223            final ResolveInfo info = receivers.get(i);
2224
2225            if (info.activityInfo == null) {
2226                continue;
2227            }
2228
2229            final String packageName = info.activityInfo.packageName;
2230
2231            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2232                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2233                continue;
2234            }
2235
2236            if (requiredVerifier != null) {
2237                throw new RuntimeException("There can be only one required verifier");
2238            }
2239
2240            requiredVerifier = packageName;
2241        }
2242
2243        return requiredVerifier;
2244    }
2245
2246    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2247        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2248        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2249                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2250
2251        ComponentName verifierComponentName = null;
2252
2253        int priority = -1000;
2254        final int N = receivers.size();
2255        for (int i = 0; i < N; i++) {
2256            final ResolveInfo info = receivers.get(i);
2257
2258            if (info.activityInfo == null) {
2259                continue;
2260            }
2261
2262            final String packageName = info.activityInfo.packageName;
2263
2264            final PackageSetting ps = mSettings.mPackages.get(packageName);
2265            if (ps == null) {
2266                continue;
2267            }
2268
2269            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2270                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2271                continue;
2272            }
2273
2274            // Select the IntentFilterVerifier with the highest priority
2275            if (priority < info.priority) {
2276                priority = info.priority;
2277                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2278                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2279                        + verifierComponentName + " with priority: " + info.priority);
2280            }
2281        }
2282
2283        return verifierComponentName;
2284    }
2285
2286    private void primeDomainVerificationsLPw() {
2287        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications");
2288        boolean updated = false;
2289        ArraySet<String> allHostsSet = new ArraySet<>();
2290        for (PackageParser.Package pkg : mPackages.values()) {
2291            final String packageName = pkg.packageName;
2292            if (!hasDomainURLs(pkg)) {
2293                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " +
2294                            "package with no domain URLs: " + packageName);
2295                continue;
2296            }
2297            if (!pkg.isSystemApp()) {
2298                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2299                        "No priming domain verifications for a non system package : " +
2300                                packageName);
2301                continue;
2302            }
2303            for (PackageParser.Activity a : pkg.activities) {
2304                for (ActivityIntentInfo filter : a.intents) {
2305                    if (hasValidDomains(filter)) {
2306                        allHostsSet.addAll(filter.getHostsList());
2307                    }
2308                }
2309            }
2310            if (allHostsSet.size() == 0) {
2311                allHostsSet.add("*");
2312            }
2313            ArrayList<String> allHostsList = new ArrayList<>(allHostsSet);
2314            IntentFilterVerificationInfo ivi =
2315                    mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList);
2316            if (ivi != null) {
2317                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2318                        "Priming domain verifications for package: " + packageName +
2319                        " with hosts:" + ivi.getDomainsString());
2320                ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
2321                updated = true;
2322            }
2323            else {
2324                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2325                        "No priming domain verifications for package: " + packageName);
2326            }
2327            allHostsSet.clear();
2328        }
2329        if (updated) {
2330            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2331                    "Will need to write primed domain verifications");
2332        }
2333        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications");
2334    }
2335
2336    private void checkDefaultBrowser() {
2337        final int myUserId = UserHandle.myUserId();
2338        final String packageName = getDefaultBrowserPackageName(myUserId);
2339        PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2340        if (info == null) {
2341            Slog.w(TAG, "Clearing default Browser as its package is no more installed: " +
2342                    packageName);
2343            setDefaultBrowserPackageName(null, myUserId);
2344        }
2345    }
2346
2347    @Override
2348    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2349            throws RemoteException {
2350        try {
2351            return super.onTransact(code, data, reply, flags);
2352        } catch (RuntimeException e) {
2353            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2354                Slog.wtf(TAG, "Package Manager Crash", e);
2355            }
2356            throw e;
2357        }
2358    }
2359
2360    void cleanupInstallFailedPackage(PackageSetting ps) {
2361        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2362
2363        removeDataDirsLI(ps.volumeUuid, ps.name);
2364        if (ps.codePath != null) {
2365            if (ps.codePath.isDirectory()) {
2366                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2367            } else {
2368                ps.codePath.delete();
2369            }
2370        }
2371        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2372            if (ps.resourcePath.isDirectory()) {
2373                FileUtils.deleteContents(ps.resourcePath);
2374            }
2375            ps.resourcePath.delete();
2376        }
2377        mSettings.removePackageLPw(ps.name);
2378    }
2379
2380    static int[] appendInts(int[] cur, int[] add) {
2381        if (add == null) return cur;
2382        if (cur == null) return add;
2383        final int N = add.length;
2384        for (int i=0; i<N; i++) {
2385            cur = appendInt(cur, add[i]);
2386        }
2387        return cur;
2388    }
2389
2390    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2391        if (!sUserManager.exists(userId)) return null;
2392        final PackageSetting ps = (PackageSetting) p.mExtras;
2393        if (ps == null) {
2394            return null;
2395        }
2396
2397        final PermissionsState permissionsState = ps.getPermissionsState();
2398
2399        final int[] gids = permissionsState.computeGids(userId);
2400        final Set<String> permissions = permissionsState.getPermissions(userId);
2401        final PackageUserState state = ps.readUserState(userId);
2402
2403        return PackageParser.generatePackageInfo(p, gids, flags,
2404                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2405    }
2406
2407    @Override
2408    public boolean isPackageFrozen(String packageName) {
2409        synchronized (mPackages) {
2410            final PackageSetting ps = mSettings.mPackages.get(packageName);
2411            if (ps != null) {
2412                return ps.frozen;
2413            }
2414        }
2415        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2416        return true;
2417    }
2418
2419    @Override
2420    public boolean isPackageAvailable(String packageName, int userId) {
2421        if (!sUserManager.exists(userId)) return false;
2422        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2423        synchronized (mPackages) {
2424            PackageParser.Package p = mPackages.get(packageName);
2425            if (p != null) {
2426                final PackageSetting ps = (PackageSetting) p.mExtras;
2427                if (ps != null) {
2428                    final PackageUserState state = ps.readUserState(userId);
2429                    if (state != null) {
2430                        return PackageParser.isAvailable(state);
2431                    }
2432                }
2433            }
2434        }
2435        return false;
2436    }
2437
2438    @Override
2439    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2440        if (!sUserManager.exists(userId)) return null;
2441        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2442        // reader
2443        synchronized (mPackages) {
2444            PackageParser.Package p = mPackages.get(packageName);
2445            if (DEBUG_PACKAGE_INFO)
2446                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2447            if (p != null) {
2448                return generatePackageInfo(p, flags, userId);
2449            }
2450            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2451                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2452            }
2453        }
2454        return null;
2455    }
2456
2457    @Override
2458    public String[] currentToCanonicalPackageNames(String[] names) {
2459        String[] out = new String[names.length];
2460        // reader
2461        synchronized (mPackages) {
2462            for (int i=names.length-1; i>=0; i--) {
2463                PackageSetting ps = mSettings.mPackages.get(names[i]);
2464                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2465            }
2466        }
2467        return out;
2468    }
2469
2470    @Override
2471    public String[] canonicalToCurrentPackageNames(String[] names) {
2472        String[] out = new String[names.length];
2473        // reader
2474        synchronized (mPackages) {
2475            for (int i=names.length-1; i>=0; i--) {
2476                String cur = mSettings.mRenamedPackages.get(names[i]);
2477                out[i] = cur != null ? cur : names[i];
2478            }
2479        }
2480        return out;
2481    }
2482
2483    @Override
2484    public int getPackageUid(String packageName, int userId) {
2485        if (!sUserManager.exists(userId)) return -1;
2486        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2487
2488        // reader
2489        synchronized (mPackages) {
2490            PackageParser.Package p = mPackages.get(packageName);
2491            if(p != null) {
2492                return UserHandle.getUid(userId, p.applicationInfo.uid);
2493            }
2494            PackageSetting ps = mSettings.mPackages.get(packageName);
2495            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2496                return -1;
2497            }
2498            p = ps.pkg;
2499            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2500        }
2501    }
2502
2503    @Override
2504    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2505        if (!sUserManager.exists(userId)) {
2506            return null;
2507        }
2508
2509        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2510                "getPackageGids");
2511
2512        // reader
2513        synchronized (mPackages) {
2514            PackageParser.Package p = mPackages.get(packageName);
2515            if (DEBUG_PACKAGE_INFO) {
2516                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2517            }
2518            if (p != null) {
2519                PackageSetting ps = (PackageSetting) p.mExtras;
2520                return ps.getPermissionsState().computeGids(userId);
2521            }
2522        }
2523
2524        return null;
2525    }
2526
2527    static PermissionInfo generatePermissionInfo(
2528            BasePermission bp, int flags) {
2529        if (bp.perm != null) {
2530            return PackageParser.generatePermissionInfo(bp.perm, flags);
2531        }
2532        PermissionInfo pi = new PermissionInfo();
2533        pi.name = bp.name;
2534        pi.packageName = bp.sourcePackage;
2535        pi.nonLocalizedLabel = bp.name;
2536        pi.protectionLevel = bp.protectionLevel;
2537        return pi;
2538    }
2539
2540    @Override
2541    public PermissionInfo getPermissionInfo(String name, int flags) {
2542        // reader
2543        synchronized (mPackages) {
2544            final BasePermission p = mSettings.mPermissions.get(name);
2545            if (p != null) {
2546                return generatePermissionInfo(p, flags);
2547            }
2548            return null;
2549        }
2550    }
2551
2552    @Override
2553    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2554        // reader
2555        synchronized (mPackages) {
2556            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2557            for (BasePermission p : mSettings.mPermissions.values()) {
2558                if (group == null) {
2559                    if (p.perm == null || p.perm.info.group == null) {
2560                        out.add(generatePermissionInfo(p, flags));
2561                    }
2562                } else {
2563                    if (p.perm != null && group.equals(p.perm.info.group)) {
2564                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2565                    }
2566                }
2567            }
2568
2569            if (out.size() > 0) {
2570                return out;
2571            }
2572            return mPermissionGroups.containsKey(group) ? out : null;
2573        }
2574    }
2575
2576    @Override
2577    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2578        // reader
2579        synchronized (mPackages) {
2580            return PackageParser.generatePermissionGroupInfo(
2581                    mPermissionGroups.get(name), flags);
2582        }
2583    }
2584
2585    @Override
2586    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2587        // reader
2588        synchronized (mPackages) {
2589            final int N = mPermissionGroups.size();
2590            ArrayList<PermissionGroupInfo> out
2591                    = new ArrayList<PermissionGroupInfo>(N);
2592            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2593                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2594            }
2595            return out;
2596        }
2597    }
2598
2599    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2600            int userId) {
2601        if (!sUserManager.exists(userId)) return null;
2602        PackageSetting ps = mSettings.mPackages.get(packageName);
2603        if (ps != null) {
2604            if (ps.pkg == null) {
2605                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2606                        flags, userId);
2607                if (pInfo != null) {
2608                    return pInfo.applicationInfo;
2609                }
2610                return null;
2611            }
2612            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2613                    ps.readUserState(userId), userId);
2614        }
2615        return null;
2616    }
2617
2618    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2619            int userId) {
2620        if (!sUserManager.exists(userId)) return null;
2621        PackageSetting ps = mSettings.mPackages.get(packageName);
2622        if (ps != null) {
2623            PackageParser.Package pkg = ps.pkg;
2624            if (pkg == null) {
2625                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2626                    return null;
2627                }
2628                // Only data remains, so we aren't worried about code paths
2629                pkg = new PackageParser.Package(packageName);
2630                pkg.applicationInfo.packageName = packageName;
2631                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2632                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2633                pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid,
2634                        packageName, userId).getAbsolutePath();
2635                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2636                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2637            }
2638            return generatePackageInfo(pkg, flags, userId);
2639        }
2640        return null;
2641    }
2642
2643    @Override
2644    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2645        if (!sUserManager.exists(userId)) return null;
2646        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2647        // writer
2648        synchronized (mPackages) {
2649            PackageParser.Package p = mPackages.get(packageName);
2650            if (DEBUG_PACKAGE_INFO) Log.v(
2651                    TAG, "getApplicationInfo " + packageName
2652                    + ": " + p);
2653            if (p != null) {
2654                PackageSetting ps = mSettings.mPackages.get(packageName);
2655                if (ps == null) return null;
2656                // Note: isEnabledLP() does not apply here - always return info
2657                return PackageParser.generateApplicationInfo(
2658                        p, flags, ps.readUserState(userId), userId);
2659            }
2660            if ("android".equals(packageName)||"system".equals(packageName)) {
2661                return mAndroidApplication;
2662            }
2663            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2664                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2665            }
2666        }
2667        return null;
2668    }
2669
2670    @Override
2671    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2672            final IPackageDataObserver observer) {
2673        mContext.enforceCallingOrSelfPermission(
2674                android.Manifest.permission.CLEAR_APP_CACHE, null);
2675        // Queue up an async operation since clearing cache may take a little while.
2676        mHandler.post(new Runnable() {
2677            public void run() {
2678                mHandler.removeCallbacks(this);
2679                int retCode = -1;
2680                synchronized (mInstallLock) {
2681                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2682                    if (retCode < 0) {
2683                        Slog.w(TAG, "Couldn't clear application caches");
2684                    }
2685                }
2686                if (observer != null) {
2687                    try {
2688                        observer.onRemoveCompleted(null, (retCode >= 0));
2689                    } catch (RemoteException e) {
2690                        Slog.w(TAG, "RemoveException when invoking call back");
2691                    }
2692                }
2693            }
2694        });
2695    }
2696
2697    @Override
2698    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2699            final IntentSender pi) {
2700        mContext.enforceCallingOrSelfPermission(
2701                android.Manifest.permission.CLEAR_APP_CACHE, null);
2702        // Queue up an async operation since clearing cache may take a little while.
2703        mHandler.post(new Runnable() {
2704            public void run() {
2705                mHandler.removeCallbacks(this);
2706                int retCode = -1;
2707                synchronized (mInstallLock) {
2708                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2709                    if (retCode < 0) {
2710                        Slog.w(TAG, "Couldn't clear application caches");
2711                    }
2712                }
2713                if(pi != null) {
2714                    try {
2715                        // Callback via pending intent
2716                        int code = (retCode >= 0) ? 1 : 0;
2717                        pi.sendIntent(null, code, null,
2718                                null, null);
2719                    } catch (SendIntentException e1) {
2720                        Slog.i(TAG, "Failed to send pending intent");
2721                    }
2722                }
2723            }
2724        });
2725    }
2726
2727    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2728        synchronized (mInstallLock) {
2729            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2730                throw new IOException("Failed to free enough space");
2731            }
2732        }
2733    }
2734
2735    @Override
2736    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2737        if (!sUserManager.exists(userId)) return null;
2738        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2739        synchronized (mPackages) {
2740            PackageParser.Activity a = mActivities.mActivities.get(component);
2741
2742            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2743            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2744                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2745                if (ps == null) return null;
2746                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2747                        userId);
2748            }
2749            if (mResolveComponentName.equals(component)) {
2750                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2751                        new PackageUserState(), userId);
2752            }
2753        }
2754        return null;
2755    }
2756
2757    @Override
2758    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2759            String resolvedType) {
2760        synchronized (mPackages) {
2761            PackageParser.Activity a = mActivities.mActivities.get(component);
2762            if (a == null) {
2763                return false;
2764            }
2765            for (int i=0; i<a.intents.size(); i++) {
2766                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2767                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2768                    return true;
2769                }
2770            }
2771            return false;
2772        }
2773    }
2774
2775    @Override
2776    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2777        if (!sUserManager.exists(userId)) return null;
2778        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2779        synchronized (mPackages) {
2780            PackageParser.Activity a = mReceivers.mActivities.get(component);
2781            if (DEBUG_PACKAGE_INFO) Log.v(
2782                TAG, "getReceiverInfo " + component + ": " + a);
2783            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2784                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2785                if (ps == null) return null;
2786                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2787                        userId);
2788            }
2789        }
2790        return null;
2791    }
2792
2793    @Override
2794    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2795        if (!sUserManager.exists(userId)) return null;
2796        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2797        synchronized (mPackages) {
2798            PackageParser.Service s = mServices.mServices.get(component);
2799            if (DEBUG_PACKAGE_INFO) Log.v(
2800                TAG, "getServiceInfo " + component + ": " + s);
2801            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2802                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2803                if (ps == null) return null;
2804                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2805                        userId);
2806            }
2807        }
2808        return null;
2809    }
2810
2811    @Override
2812    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2813        if (!sUserManager.exists(userId)) return null;
2814        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2815        synchronized (mPackages) {
2816            PackageParser.Provider p = mProviders.mProviders.get(component);
2817            if (DEBUG_PACKAGE_INFO) Log.v(
2818                TAG, "getProviderInfo " + component + ": " + p);
2819            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2820                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2821                if (ps == null) return null;
2822                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2823                        userId);
2824            }
2825        }
2826        return null;
2827    }
2828
2829    @Override
2830    public String[] getSystemSharedLibraryNames() {
2831        Set<String> libSet;
2832        synchronized (mPackages) {
2833            libSet = mSharedLibraries.keySet();
2834            int size = libSet.size();
2835            if (size > 0) {
2836                String[] libs = new String[size];
2837                libSet.toArray(libs);
2838                return libs;
2839            }
2840        }
2841        return null;
2842    }
2843
2844    /**
2845     * @hide
2846     */
2847    PackageParser.Package findSharedNonSystemLibrary(String libName) {
2848        synchronized (mPackages) {
2849            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
2850            if (lib != null && lib.apk != null) {
2851                return mPackages.get(lib.apk);
2852            }
2853        }
2854        return null;
2855    }
2856
2857    @Override
2858    public FeatureInfo[] getSystemAvailableFeatures() {
2859        Collection<FeatureInfo> featSet;
2860        synchronized (mPackages) {
2861            featSet = mAvailableFeatures.values();
2862            int size = featSet.size();
2863            if (size > 0) {
2864                FeatureInfo[] features = new FeatureInfo[size+1];
2865                featSet.toArray(features);
2866                FeatureInfo fi = new FeatureInfo();
2867                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2868                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2869                features[size] = fi;
2870                return features;
2871            }
2872        }
2873        return null;
2874    }
2875
2876    @Override
2877    public boolean hasSystemFeature(String name) {
2878        synchronized (mPackages) {
2879            return mAvailableFeatures.containsKey(name);
2880        }
2881    }
2882
2883    private void checkValidCaller(int uid, int userId) {
2884        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2885            return;
2886
2887        throw new SecurityException("Caller uid=" + uid
2888                + " is not privileged to communicate with user=" + userId);
2889    }
2890
2891    @Override
2892    public int checkPermission(String permName, String pkgName, int userId) {
2893        if (!sUserManager.exists(userId)) {
2894            return PackageManager.PERMISSION_DENIED;
2895        }
2896
2897        synchronized (mPackages) {
2898            final PackageParser.Package p = mPackages.get(pkgName);
2899            if (p != null && p.mExtras != null) {
2900                final PackageSetting ps = (PackageSetting) p.mExtras;
2901                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2902                    return PackageManager.PERMISSION_GRANTED;
2903                }
2904            }
2905        }
2906
2907        return PackageManager.PERMISSION_DENIED;
2908    }
2909
2910    @Override
2911    public int checkUidPermission(String permName, int uid) {
2912        final int userId = UserHandle.getUserId(uid);
2913
2914        if (!sUserManager.exists(userId)) {
2915            return PackageManager.PERMISSION_DENIED;
2916        }
2917
2918        synchronized (mPackages) {
2919            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2920            if (obj != null) {
2921                final SettingBase ps = (SettingBase) obj;
2922                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2923                    return PackageManager.PERMISSION_GRANTED;
2924                }
2925            } else {
2926                ArraySet<String> perms = mSystemPermissions.get(uid);
2927                if (perms != null && perms.contains(permName)) {
2928                    return PackageManager.PERMISSION_GRANTED;
2929                }
2930            }
2931        }
2932
2933        return PackageManager.PERMISSION_DENIED;
2934    }
2935
2936    /**
2937     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2938     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2939     * @param checkShell TODO(yamasani):
2940     * @param message the message to log on security exception
2941     */
2942    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2943            boolean checkShell, String message) {
2944        if (userId < 0) {
2945            throw new IllegalArgumentException("Invalid userId " + userId);
2946        }
2947        if (checkShell) {
2948            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
2949        }
2950        if (userId == UserHandle.getUserId(callingUid)) return;
2951        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2952            if (requireFullPermission) {
2953                mContext.enforceCallingOrSelfPermission(
2954                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2955            } else {
2956                try {
2957                    mContext.enforceCallingOrSelfPermission(
2958                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2959                } catch (SecurityException se) {
2960                    mContext.enforceCallingOrSelfPermission(
2961                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2962                }
2963            }
2964        }
2965    }
2966
2967    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
2968        if (callingUid == Process.SHELL_UID) {
2969            if (userHandle >= 0
2970                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
2971                throw new SecurityException("Shell does not have permission to access user "
2972                        + userHandle);
2973            } else if (userHandle < 0) {
2974                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
2975                        + Debug.getCallers(3));
2976            }
2977        }
2978    }
2979
2980    private BasePermission findPermissionTreeLP(String permName) {
2981        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2982            if (permName.startsWith(bp.name) &&
2983                    permName.length() > bp.name.length() &&
2984                    permName.charAt(bp.name.length()) == '.') {
2985                return bp;
2986            }
2987        }
2988        return null;
2989    }
2990
2991    private BasePermission checkPermissionTreeLP(String permName) {
2992        if (permName != null) {
2993            BasePermission bp = findPermissionTreeLP(permName);
2994            if (bp != null) {
2995                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2996                    return bp;
2997                }
2998                throw new SecurityException("Calling uid "
2999                        + Binder.getCallingUid()
3000                        + " is not allowed to add to permission tree "
3001                        + bp.name + " owned by uid " + bp.uid);
3002            }
3003        }
3004        throw new SecurityException("No permission tree found for " + permName);
3005    }
3006
3007    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3008        if (s1 == null) {
3009            return s2 == null;
3010        }
3011        if (s2 == null) {
3012            return false;
3013        }
3014        if (s1.getClass() != s2.getClass()) {
3015            return false;
3016        }
3017        return s1.equals(s2);
3018    }
3019
3020    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3021        if (pi1.icon != pi2.icon) return false;
3022        if (pi1.logo != pi2.logo) return false;
3023        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3024        if (!compareStrings(pi1.name, pi2.name)) return false;
3025        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3026        // We'll take care of setting this one.
3027        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3028        // These are not currently stored in settings.
3029        //if (!compareStrings(pi1.group, pi2.group)) return false;
3030        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3031        //if (pi1.labelRes != pi2.labelRes) return false;
3032        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3033        return true;
3034    }
3035
3036    int permissionInfoFootprint(PermissionInfo info) {
3037        int size = info.name.length();
3038        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3039        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3040        return size;
3041    }
3042
3043    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3044        int size = 0;
3045        for (BasePermission perm : mSettings.mPermissions.values()) {
3046            if (perm.uid == tree.uid) {
3047                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3048            }
3049        }
3050        return size;
3051    }
3052
3053    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3054        // We calculate the max size of permissions defined by this uid and throw
3055        // if that plus the size of 'info' would exceed our stated maximum.
3056        if (tree.uid != Process.SYSTEM_UID) {
3057            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3058            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3059                throw new SecurityException("Permission tree size cap exceeded");
3060            }
3061        }
3062    }
3063
3064    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3065        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3066            throw new SecurityException("Label must be specified in permission");
3067        }
3068        BasePermission tree = checkPermissionTreeLP(info.name);
3069        BasePermission bp = mSettings.mPermissions.get(info.name);
3070        boolean added = bp == null;
3071        boolean changed = true;
3072        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3073        if (added) {
3074            enforcePermissionCapLocked(info, tree);
3075            bp = new BasePermission(info.name, tree.sourcePackage,
3076                    BasePermission.TYPE_DYNAMIC);
3077        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3078            throw new SecurityException(
3079                    "Not allowed to modify non-dynamic permission "
3080                    + info.name);
3081        } else {
3082            if (bp.protectionLevel == fixedLevel
3083                    && bp.perm.owner.equals(tree.perm.owner)
3084                    && bp.uid == tree.uid
3085                    && comparePermissionInfos(bp.perm.info, info)) {
3086                changed = false;
3087            }
3088        }
3089        bp.protectionLevel = fixedLevel;
3090        info = new PermissionInfo(info);
3091        info.protectionLevel = fixedLevel;
3092        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3093        bp.perm.info.packageName = tree.perm.info.packageName;
3094        bp.uid = tree.uid;
3095        if (added) {
3096            mSettings.mPermissions.put(info.name, bp);
3097        }
3098        if (changed) {
3099            if (!async) {
3100                mSettings.writeLPr();
3101            } else {
3102                scheduleWriteSettingsLocked();
3103            }
3104        }
3105        return added;
3106    }
3107
3108    @Override
3109    public boolean addPermission(PermissionInfo info) {
3110        synchronized (mPackages) {
3111            return addPermissionLocked(info, false);
3112        }
3113    }
3114
3115    @Override
3116    public boolean addPermissionAsync(PermissionInfo info) {
3117        synchronized (mPackages) {
3118            return addPermissionLocked(info, true);
3119        }
3120    }
3121
3122    @Override
3123    public void removePermission(String name) {
3124        synchronized (mPackages) {
3125            checkPermissionTreeLP(name);
3126            BasePermission bp = mSettings.mPermissions.get(name);
3127            if (bp != null) {
3128                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3129                    throw new SecurityException(
3130                            "Not allowed to modify non-dynamic permission "
3131                            + name);
3132                }
3133                mSettings.mPermissions.remove(name);
3134                mSettings.writeLPr();
3135            }
3136        }
3137    }
3138
3139    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3140            BasePermission bp) {
3141        int index = pkg.requestedPermissions.indexOf(bp.name);
3142        if (index == -1) {
3143            throw new SecurityException("Package " + pkg.packageName
3144                    + " has not requested permission " + bp.name);
3145        }
3146        if (!bp.isRuntime()) {
3147            throw new SecurityException("Permission " + bp.name
3148                    + " is not a changeable permission type");
3149        }
3150    }
3151
3152    @Override
3153    public void grantRuntimePermission(String packageName, String name, int userId) {
3154        if (!sUserManager.exists(userId)) {
3155            Log.e(TAG, "No such user:" + userId);
3156            return;
3157        }
3158
3159        mContext.enforceCallingOrSelfPermission(
3160                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3161                "grantRuntimePermission");
3162
3163        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3164                "grantRuntimePermission");
3165
3166        boolean gidsChanged = false;
3167        final SettingBase sb;
3168
3169        synchronized (mPackages) {
3170            final PackageParser.Package pkg = mPackages.get(packageName);
3171            if (pkg == null) {
3172                throw new IllegalArgumentException("Unknown package: " + packageName);
3173            }
3174
3175            final BasePermission bp = mSettings.mPermissions.get(name);
3176            if (bp == null) {
3177                throw new IllegalArgumentException("Unknown permission: " + name);
3178            }
3179
3180            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3181
3182            sb = (SettingBase) pkg.mExtras;
3183            if (sb == null) {
3184                throw new IllegalArgumentException("Unknown package: " + packageName);
3185            }
3186
3187            final PermissionsState permissionsState = sb.getPermissionsState();
3188
3189            final int flags = permissionsState.getPermissionFlags(name, userId);
3190            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3191                throw new SecurityException("Cannot grant system fixed permission: "
3192                        + name + " for package: " + packageName);
3193            }
3194
3195            final int result = permissionsState.grantRuntimePermission(bp, userId);
3196            switch (result) {
3197                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3198                    return;
3199                }
3200
3201                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3202                    gidsChanged = true;
3203                } break;
3204            }
3205
3206            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3207
3208            // Not critical if that is lost - app has to request again.
3209            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3210        }
3211
3212        if (gidsChanged) {
3213            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3214        }
3215    }
3216
3217    @Override
3218    public void revokeRuntimePermission(String packageName, String name, int userId) {
3219        if (!sUserManager.exists(userId)) {
3220            Log.e(TAG, "No such user:" + userId);
3221            return;
3222        }
3223
3224        mContext.enforceCallingOrSelfPermission(
3225                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3226                "revokeRuntimePermission");
3227
3228        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3229                "revokeRuntimePermission");
3230
3231        final SettingBase sb;
3232
3233        synchronized (mPackages) {
3234            final PackageParser.Package pkg = mPackages.get(packageName);
3235            if (pkg == null) {
3236                throw new IllegalArgumentException("Unknown package: " + packageName);
3237            }
3238
3239            final BasePermission bp = mSettings.mPermissions.get(name);
3240            if (bp == null) {
3241                throw new IllegalArgumentException("Unknown permission: " + name);
3242            }
3243
3244            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3245
3246            sb = (SettingBase) pkg.mExtras;
3247            if (sb == null) {
3248                throw new IllegalArgumentException("Unknown package: " + packageName);
3249            }
3250
3251            final PermissionsState permissionsState = sb.getPermissionsState();
3252
3253            final int flags = permissionsState.getPermissionFlags(name, userId);
3254            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3255                throw new SecurityException("Cannot revoke system fixed permission: "
3256                        + name + " for package: " + packageName);
3257            }
3258
3259            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3260                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3261                return;
3262            }
3263
3264            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3265
3266            // Critical, after this call app should never have the permission.
3267            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3268        }
3269
3270        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3271    }
3272
3273    @Override
3274    public int getPermissionFlags(String name, String packageName, int userId) {
3275        if (!sUserManager.exists(userId)) {
3276            return 0;
3277        }
3278
3279        mContext.enforceCallingOrSelfPermission(
3280                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3281                "getPermissionFlags");
3282
3283        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3284                "getPermissionFlags");
3285
3286        synchronized (mPackages) {
3287            final PackageParser.Package pkg = mPackages.get(packageName);
3288            if (pkg == null) {
3289                throw new IllegalArgumentException("Unknown package: " + packageName);
3290            }
3291
3292            final BasePermission bp = mSettings.mPermissions.get(name);
3293            if (bp == null) {
3294                throw new IllegalArgumentException("Unknown permission: " + name);
3295            }
3296
3297            SettingBase sb = (SettingBase) pkg.mExtras;
3298            if (sb == null) {
3299                throw new IllegalArgumentException("Unknown package: " + packageName);
3300            }
3301
3302            PermissionsState permissionsState = sb.getPermissionsState();
3303            return permissionsState.getPermissionFlags(name, userId);
3304        }
3305    }
3306
3307    @Override
3308    public void updatePermissionFlags(String name, String packageName, int flagMask,
3309            int flagValues, int userId) {
3310        if (!sUserManager.exists(userId)) {
3311            return;
3312        }
3313
3314        mContext.enforceCallingOrSelfPermission(
3315                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3316                "updatePermissionFlags");
3317
3318        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3319                "updatePermissionFlags");
3320
3321        // Only the system can change policy flags.
3322        if (getCallingUid() != Process.SYSTEM_UID) {
3323            flagMask &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED;
3324            flagValues &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED;
3325        }
3326
3327        // Only the package manager can change system flags.
3328        flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3329        flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3330
3331        synchronized (mPackages) {
3332            final PackageParser.Package pkg = mPackages.get(packageName);
3333            if (pkg == null) {
3334                throw new IllegalArgumentException("Unknown package: " + packageName);
3335            }
3336
3337            final BasePermission bp = mSettings.mPermissions.get(name);
3338            if (bp == null) {
3339                throw new IllegalArgumentException("Unknown permission: " + name);
3340            }
3341
3342            SettingBase sb = (SettingBase) pkg.mExtras;
3343            if (sb == null) {
3344                throw new IllegalArgumentException("Unknown package: " + packageName);
3345            }
3346
3347            PermissionsState permissionsState = sb.getPermissionsState();
3348
3349            // Only the package manager can change flags for system component permissions.
3350            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3351            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3352                return;
3353            }
3354
3355            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3356                // Install and runtime permissions are stored in different places,
3357                // so figure out what permission changed and persist the change.
3358                if (permissionsState.getInstallPermissionState(name) != null) {
3359                    scheduleWriteSettingsLocked();
3360                } else if (permissionsState.getRuntimePermissionState(name, userId) != null) {
3361                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3362                }
3363            }
3364        }
3365    }
3366
3367    @Override
3368    public boolean shouldShowRequestPermissionRationale(String permissionName,
3369            String packageName, int userId) {
3370        if (UserHandle.getCallingUserId() != userId) {
3371            mContext.enforceCallingPermission(
3372                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3373                    "canShowRequestPermissionRationale for user " + userId);
3374        }
3375
3376        final int uid = getPackageUid(packageName, userId);
3377        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3378            return false;
3379        }
3380
3381        if (checkPermission(permissionName, packageName, userId)
3382                == PackageManager.PERMISSION_GRANTED) {
3383            return false;
3384        }
3385
3386        final int flags;
3387
3388        final long identity = Binder.clearCallingIdentity();
3389        try {
3390            flags = getPermissionFlags(permissionName,
3391                    packageName, userId);
3392        } finally {
3393            Binder.restoreCallingIdentity(identity);
3394        }
3395
3396        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3397                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3398                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3399
3400        if ((flags & fixedFlags) != 0) {
3401            return false;
3402        }
3403
3404        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3405    }
3406
3407    @Override
3408    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3409        mContext.enforceCallingOrSelfPermission(
3410                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3411                "addOnPermissionsChangeListener");
3412
3413        synchronized (mPackages) {
3414            mOnPermissionChangeListeners.addListenerLocked(listener);
3415        }
3416    }
3417
3418    @Override
3419    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3420        synchronized (mPackages) {
3421            mOnPermissionChangeListeners.removeListenerLocked(listener);
3422        }
3423    }
3424
3425    @Override
3426    public boolean isProtectedBroadcast(String actionName) {
3427        synchronized (mPackages) {
3428            return mProtectedBroadcasts.contains(actionName);
3429        }
3430    }
3431
3432    @Override
3433    public int checkSignatures(String pkg1, String pkg2) {
3434        synchronized (mPackages) {
3435            final PackageParser.Package p1 = mPackages.get(pkg1);
3436            final PackageParser.Package p2 = mPackages.get(pkg2);
3437            if (p1 == null || p1.mExtras == null
3438                    || p2 == null || p2.mExtras == null) {
3439                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3440            }
3441            return compareSignatures(p1.mSignatures, p2.mSignatures);
3442        }
3443    }
3444
3445    @Override
3446    public int checkUidSignatures(int uid1, int uid2) {
3447        // Map to base uids.
3448        uid1 = UserHandle.getAppId(uid1);
3449        uid2 = UserHandle.getAppId(uid2);
3450        // reader
3451        synchronized (mPackages) {
3452            Signature[] s1;
3453            Signature[] s2;
3454            Object obj = mSettings.getUserIdLPr(uid1);
3455            if (obj != null) {
3456                if (obj instanceof SharedUserSetting) {
3457                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3458                } else if (obj instanceof PackageSetting) {
3459                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3460                } else {
3461                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3462                }
3463            } else {
3464                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3465            }
3466            obj = mSettings.getUserIdLPr(uid2);
3467            if (obj != null) {
3468                if (obj instanceof SharedUserSetting) {
3469                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3470                } else if (obj instanceof PackageSetting) {
3471                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3472                } else {
3473                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3474                }
3475            } else {
3476                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3477            }
3478            return compareSignatures(s1, s2);
3479        }
3480    }
3481
3482    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3483        final long identity = Binder.clearCallingIdentity();
3484        try {
3485            if (sb instanceof SharedUserSetting) {
3486                SharedUserSetting sus = (SharedUserSetting) sb;
3487                final int packageCount = sus.packages.size();
3488                for (int i = 0; i < packageCount; i++) {
3489                    PackageSetting susPs = sus.packages.valueAt(i);
3490                    if (userId == UserHandle.USER_ALL) {
3491                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3492                    } else {
3493                        final int uid = UserHandle.getUid(userId, susPs.appId);
3494                        killUid(uid, reason);
3495                    }
3496                }
3497            } else if (sb instanceof PackageSetting) {
3498                PackageSetting ps = (PackageSetting) sb;
3499                if (userId == UserHandle.USER_ALL) {
3500                    killApplication(ps.pkg.packageName, ps.appId, reason);
3501                } else {
3502                    final int uid = UserHandle.getUid(userId, ps.appId);
3503                    killUid(uid, reason);
3504                }
3505            }
3506        } finally {
3507            Binder.restoreCallingIdentity(identity);
3508        }
3509    }
3510
3511    private static void killUid(int uid, String reason) {
3512        IActivityManager am = ActivityManagerNative.getDefault();
3513        if (am != null) {
3514            try {
3515                am.killUid(uid, reason);
3516            } catch (RemoteException e) {
3517                /* ignore - same process */
3518            }
3519        }
3520    }
3521
3522    /**
3523     * Compares two sets of signatures. Returns:
3524     * <br />
3525     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3526     * <br />
3527     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3528     * <br />
3529     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3530     * <br />
3531     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3532     * <br />
3533     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3534     */
3535    static int compareSignatures(Signature[] s1, Signature[] s2) {
3536        if (s1 == null) {
3537            return s2 == null
3538                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3539                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3540        }
3541
3542        if (s2 == null) {
3543            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3544        }
3545
3546        if (s1.length != s2.length) {
3547            return PackageManager.SIGNATURE_NO_MATCH;
3548        }
3549
3550        // Since both signature sets are of size 1, we can compare without HashSets.
3551        if (s1.length == 1) {
3552            return s1[0].equals(s2[0]) ?
3553                    PackageManager.SIGNATURE_MATCH :
3554                    PackageManager.SIGNATURE_NO_MATCH;
3555        }
3556
3557        ArraySet<Signature> set1 = new ArraySet<Signature>();
3558        for (Signature sig : s1) {
3559            set1.add(sig);
3560        }
3561        ArraySet<Signature> set2 = new ArraySet<Signature>();
3562        for (Signature sig : s2) {
3563            set2.add(sig);
3564        }
3565        // Make sure s2 contains all signatures in s1.
3566        if (set1.equals(set2)) {
3567            return PackageManager.SIGNATURE_MATCH;
3568        }
3569        return PackageManager.SIGNATURE_NO_MATCH;
3570    }
3571
3572    /**
3573     * If the database version for this type of package (internal storage or
3574     * external storage) is less than the version where package signatures
3575     * were updated, return true.
3576     */
3577    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3578        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3579                DatabaseVersion.SIGNATURE_END_ENTITY))
3580                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3581                        DatabaseVersion.SIGNATURE_END_ENTITY));
3582    }
3583
3584    /**
3585     * Used for backward compatibility to make sure any packages with
3586     * certificate chains get upgraded to the new style. {@code existingSigs}
3587     * will be in the old format (since they were stored on disk from before the
3588     * system upgrade) and {@code scannedSigs} will be in the newer format.
3589     */
3590    private int compareSignaturesCompat(PackageSignatures existingSigs,
3591            PackageParser.Package scannedPkg) {
3592        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3593            return PackageManager.SIGNATURE_NO_MATCH;
3594        }
3595
3596        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3597        for (Signature sig : existingSigs.mSignatures) {
3598            existingSet.add(sig);
3599        }
3600        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3601        for (Signature sig : scannedPkg.mSignatures) {
3602            try {
3603                Signature[] chainSignatures = sig.getChainSignatures();
3604                for (Signature chainSig : chainSignatures) {
3605                    scannedCompatSet.add(chainSig);
3606                }
3607            } catch (CertificateEncodingException e) {
3608                scannedCompatSet.add(sig);
3609            }
3610        }
3611        /*
3612         * Make sure the expanded scanned set contains all signatures in the
3613         * existing one.
3614         */
3615        if (scannedCompatSet.equals(existingSet)) {
3616            // Migrate the old signatures to the new scheme.
3617            existingSigs.assignSignatures(scannedPkg.mSignatures);
3618            // The new KeySets will be re-added later in the scanning process.
3619            synchronized (mPackages) {
3620                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3621            }
3622            return PackageManager.SIGNATURE_MATCH;
3623        }
3624        return PackageManager.SIGNATURE_NO_MATCH;
3625    }
3626
3627    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3628        if (isExternal(scannedPkg)) {
3629            return mSettings.isExternalDatabaseVersionOlderThan(
3630                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3631        } else {
3632            return mSettings.isInternalDatabaseVersionOlderThan(
3633                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3634        }
3635    }
3636
3637    private int compareSignaturesRecover(PackageSignatures existingSigs,
3638            PackageParser.Package scannedPkg) {
3639        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3640            return PackageManager.SIGNATURE_NO_MATCH;
3641        }
3642
3643        String msg = null;
3644        try {
3645            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3646                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3647                        + scannedPkg.packageName);
3648                return PackageManager.SIGNATURE_MATCH;
3649            }
3650        } catch (CertificateException e) {
3651            msg = e.getMessage();
3652        }
3653
3654        logCriticalInfo(Log.INFO,
3655                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3656        return PackageManager.SIGNATURE_NO_MATCH;
3657    }
3658
3659    @Override
3660    public String[] getPackagesForUid(int uid) {
3661        uid = UserHandle.getAppId(uid);
3662        // reader
3663        synchronized (mPackages) {
3664            Object obj = mSettings.getUserIdLPr(uid);
3665            if (obj instanceof SharedUserSetting) {
3666                final SharedUserSetting sus = (SharedUserSetting) obj;
3667                final int N = sus.packages.size();
3668                final String[] res = new String[N];
3669                final Iterator<PackageSetting> it = sus.packages.iterator();
3670                int i = 0;
3671                while (it.hasNext()) {
3672                    res[i++] = it.next().name;
3673                }
3674                return res;
3675            } else if (obj instanceof PackageSetting) {
3676                final PackageSetting ps = (PackageSetting) obj;
3677                return new String[] { ps.name };
3678            }
3679        }
3680        return null;
3681    }
3682
3683    @Override
3684    public String getNameForUid(int uid) {
3685        // reader
3686        synchronized (mPackages) {
3687            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3688            if (obj instanceof SharedUserSetting) {
3689                final SharedUserSetting sus = (SharedUserSetting) obj;
3690                return sus.name + ":" + sus.userId;
3691            } else if (obj instanceof PackageSetting) {
3692                final PackageSetting ps = (PackageSetting) obj;
3693                return ps.name;
3694            }
3695        }
3696        return null;
3697    }
3698
3699    @Override
3700    public int getUidForSharedUser(String sharedUserName) {
3701        if(sharedUserName == null) {
3702            return -1;
3703        }
3704        // reader
3705        synchronized (mPackages) {
3706            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
3707            if (suid == null) {
3708                return -1;
3709            }
3710            return suid.userId;
3711        }
3712    }
3713
3714    @Override
3715    public int getFlagsForUid(int uid) {
3716        synchronized (mPackages) {
3717            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3718            if (obj instanceof SharedUserSetting) {
3719                final SharedUserSetting sus = (SharedUserSetting) obj;
3720                return sus.pkgFlags;
3721            } else if (obj instanceof PackageSetting) {
3722                final PackageSetting ps = (PackageSetting) obj;
3723                return ps.pkgFlags;
3724            }
3725        }
3726        return 0;
3727    }
3728
3729    @Override
3730    public int getPrivateFlagsForUid(int uid) {
3731        synchronized (mPackages) {
3732            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3733            if (obj instanceof SharedUserSetting) {
3734                final SharedUserSetting sus = (SharedUserSetting) obj;
3735                return sus.pkgPrivateFlags;
3736            } else if (obj instanceof PackageSetting) {
3737                final PackageSetting ps = (PackageSetting) obj;
3738                return ps.pkgPrivateFlags;
3739            }
3740        }
3741        return 0;
3742    }
3743
3744    @Override
3745    public boolean isUidPrivileged(int uid) {
3746        uid = UserHandle.getAppId(uid);
3747        // reader
3748        synchronized (mPackages) {
3749            Object obj = mSettings.getUserIdLPr(uid);
3750            if (obj instanceof SharedUserSetting) {
3751                final SharedUserSetting sus = (SharedUserSetting) obj;
3752                final Iterator<PackageSetting> it = sus.packages.iterator();
3753                while (it.hasNext()) {
3754                    if (it.next().isPrivileged()) {
3755                        return true;
3756                    }
3757                }
3758            } else if (obj instanceof PackageSetting) {
3759                final PackageSetting ps = (PackageSetting) obj;
3760                return ps.isPrivileged();
3761            }
3762        }
3763        return false;
3764    }
3765
3766    @Override
3767    public String[] getAppOpPermissionPackages(String permissionName) {
3768        synchronized (mPackages) {
3769            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
3770            if (pkgs == null) {
3771                return null;
3772            }
3773            return pkgs.toArray(new String[pkgs.size()]);
3774        }
3775    }
3776
3777    @Override
3778    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3779            int flags, int userId) {
3780        if (!sUserManager.exists(userId)) return null;
3781        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
3782        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3783        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3784    }
3785
3786    @Override
3787    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3788            IntentFilter filter, int match, ComponentName activity) {
3789        final int userId = UserHandle.getCallingUserId();
3790        if (DEBUG_PREFERRED) {
3791            Log.v(TAG, "setLastChosenActivity intent=" + intent
3792                + " resolvedType=" + resolvedType
3793                + " flags=" + flags
3794                + " filter=" + filter
3795                + " match=" + match
3796                + " activity=" + activity);
3797            filter.dump(new PrintStreamPrinter(System.out), "    ");
3798        }
3799        intent.setComponent(null);
3800        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3801        // Find any earlier preferred or last chosen entries and nuke them
3802        findPreferredActivity(intent, resolvedType,
3803                flags, query, 0, false, true, false, userId);
3804        // Add the new activity as the last chosen for this filter
3805        addPreferredActivityInternal(filter, match, null, activity, false, userId,
3806                "Setting last chosen");
3807    }
3808
3809    @Override
3810    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
3811        final int userId = UserHandle.getCallingUserId();
3812        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
3813        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3814        return findPreferredActivity(intent, resolvedType, flags, query, 0,
3815                false, false, false, userId);
3816    }
3817
3818    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
3819            int flags, List<ResolveInfo> query, int userId) {
3820        if (query != null) {
3821            final int N = query.size();
3822            if (N == 1) {
3823                return query.get(0);
3824            } else if (N > 1) {
3825                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3826                // If there is more than one activity with the same priority,
3827                // then let the user decide between them.
3828                ResolveInfo r0 = query.get(0);
3829                ResolveInfo r1 = query.get(1);
3830                if (DEBUG_INTENT_MATCHING || debug) {
3831                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
3832                            + r1.activityInfo.name + "=" + r1.priority);
3833                }
3834                // If the first activity has a higher priority, or a different
3835                // default, then it is always desireable to pick it.
3836                if (r0.priority != r1.priority
3837                        || r0.preferredOrder != r1.preferredOrder
3838                        || r0.isDefault != r1.isDefault) {
3839                    return query.get(0);
3840                }
3841                // If we have saved a preference for a preferred activity for
3842                // this Intent, use that.
3843                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3844                        flags, query, r0.priority, true, false, debug, userId);
3845                if (ri != null) {
3846                    return ri;
3847                }
3848                if (userId != 0) {
3849                    ri = new ResolveInfo(mResolveInfo);
3850                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3851                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3852                            ri.activityInfo.applicationInfo);
3853                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3854                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3855                    return ri;
3856                }
3857                return mResolveInfo;
3858            }
3859        }
3860        return null;
3861    }
3862
3863    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3864            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3865        final int N = query.size();
3866        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3867                .get(userId);
3868        // Get the list of persistent preferred activities that handle the intent
3869        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3870        List<PersistentPreferredActivity> pprefs = ppir != null
3871                ? ppir.queryIntent(intent, resolvedType,
3872                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3873                : null;
3874        if (pprefs != null && pprefs.size() > 0) {
3875            final int M = pprefs.size();
3876            for (int i=0; i<M; i++) {
3877                final PersistentPreferredActivity ppa = pprefs.get(i);
3878                if (DEBUG_PREFERRED || debug) {
3879                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3880                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3881                            + "\n  component=" + ppa.mComponent);
3882                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3883                }
3884                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3885                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3886                if (DEBUG_PREFERRED || debug) {
3887                    Slog.v(TAG, "Found persistent preferred activity:");
3888                    if (ai != null) {
3889                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3890                    } else {
3891                        Slog.v(TAG, "  null");
3892                    }
3893                }
3894                if (ai == null) {
3895                    // This previously registered persistent preferred activity
3896                    // component is no longer known. Ignore it and do NOT remove it.
3897                    continue;
3898                }
3899                for (int j=0; j<N; j++) {
3900                    final ResolveInfo ri = query.get(j);
3901                    if (!ri.activityInfo.applicationInfo.packageName
3902                            .equals(ai.applicationInfo.packageName)) {
3903                        continue;
3904                    }
3905                    if (!ri.activityInfo.name.equals(ai.name)) {
3906                        continue;
3907                    }
3908                    //  Found a persistent preference that can handle the intent.
3909                    if (DEBUG_PREFERRED || debug) {
3910                        Slog.v(TAG, "Returning persistent preferred activity: " +
3911                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3912                    }
3913                    return ri;
3914                }
3915            }
3916        }
3917        return null;
3918    }
3919
3920    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3921            List<ResolveInfo> query, int priority, boolean always,
3922            boolean removeMatches, boolean debug, int userId) {
3923        if (!sUserManager.exists(userId)) return null;
3924        // writer
3925        synchronized (mPackages) {
3926            if (intent.getSelector() != null) {
3927                intent = intent.getSelector();
3928            }
3929            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3930
3931            // Try to find a matching persistent preferred activity.
3932            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3933                    debug, userId);
3934
3935            // If a persistent preferred activity matched, use it.
3936            if (pri != null) {
3937                return pri;
3938            }
3939
3940            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3941            // Get the list of preferred activities that handle the intent
3942            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3943            List<PreferredActivity> prefs = pir != null
3944                    ? pir.queryIntent(intent, resolvedType,
3945                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3946                    : null;
3947            if (prefs != null && prefs.size() > 0) {
3948                boolean changed = false;
3949                try {
3950                    // First figure out how good the original match set is.
3951                    // We will only allow preferred activities that came
3952                    // from the same match quality.
3953                    int match = 0;
3954
3955                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3956
3957                    final int N = query.size();
3958                    for (int j=0; j<N; j++) {
3959                        final ResolveInfo ri = query.get(j);
3960                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3961                                + ": 0x" + Integer.toHexString(match));
3962                        if (ri.match > match) {
3963                            match = ri.match;
3964                        }
3965                    }
3966
3967                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3968                            + Integer.toHexString(match));
3969
3970                    match &= IntentFilter.MATCH_CATEGORY_MASK;
3971                    final int M = prefs.size();
3972                    for (int i=0; i<M; i++) {
3973                        final PreferredActivity pa = prefs.get(i);
3974                        if (DEBUG_PREFERRED || debug) {
3975                            Slog.v(TAG, "Checking PreferredActivity ds="
3976                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3977                                    + "\n  component=" + pa.mPref.mComponent);
3978                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3979                        }
3980                        if (pa.mPref.mMatch != match) {
3981                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3982                                    + Integer.toHexString(pa.mPref.mMatch));
3983                            continue;
3984                        }
3985                        // If it's not an "always" type preferred activity and that's what we're
3986                        // looking for, skip it.
3987                        if (always && !pa.mPref.mAlways) {
3988                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3989                            continue;
3990                        }
3991                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3992                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3993                        if (DEBUG_PREFERRED || debug) {
3994                            Slog.v(TAG, "Found preferred activity:");
3995                            if (ai != null) {
3996                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3997                            } else {
3998                                Slog.v(TAG, "  null");
3999                            }
4000                        }
4001                        if (ai == null) {
4002                            // This previously registered preferred activity
4003                            // component is no longer known.  Most likely an update
4004                            // to the app was installed and in the new version this
4005                            // component no longer exists.  Clean it up by removing
4006                            // it from the preferred activities list, and skip it.
4007                            Slog.w(TAG, "Removing dangling preferred activity: "
4008                                    + pa.mPref.mComponent);
4009                            pir.removeFilter(pa);
4010                            changed = true;
4011                            continue;
4012                        }
4013                        for (int j=0; j<N; j++) {
4014                            final ResolveInfo ri = query.get(j);
4015                            if (!ri.activityInfo.applicationInfo.packageName
4016                                    .equals(ai.applicationInfo.packageName)) {
4017                                continue;
4018                            }
4019                            if (!ri.activityInfo.name.equals(ai.name)) {
4020                                continue;
4021                            }
4022
4023                            if (removeMatches) {
4024                                pir.removeFilter(pa);
4025                                changed = true;
4026                                if (DEBUG_PREFERRED) {
4027                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4028                                }
4029                                break;
4030                            }
4031
4032                            // Okay we found a previously set preferred or last chosen app.
4033                            // If the result set is different from when this
4034                            // was created, we need to clear it and re-ask the
4035                            // user their preference, if we're looking for an "always" type entry.
4036                            if (always && !pa.mPref.sameSet(query)) {
4037                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4038                                        + intent + " type " + resolvedType);
4039                                if (DEBUG_PREFERRED) {
4040                                    Slog.v(TAG, "Removing preferred activity since set changed "
4041                                            + pa.mPref.mComponent);
4042                                }
4043                                pir.removeFilter(pa);
4044                                // Re-add the filter as a "last chosen" entry (!always)
4045                                PreferredActivity lastChosen = new PreferredActivity(
4046                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4047                                pir.addFilter(lastChosen);
4048                                changed = true;
4049                                return null;
4050                            }
4051
4052                            // Yay! Either the set matched or we're looking for the last chosen
4053                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4054                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4055                            return ri;
4056                        }
4057                    }
4058                } finally {
4059                    if (changed) {
4060                        if (DEBUG_PREFERRED) {
4061                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4062                        }
4063                        scheduleWritePackageRestrictionsLocked(userId);
4064                    }
4065                }
4066            }
4067        }
4068        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4069        return null;
4070    }
4071
4072    /*
4073     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4074     */
4075    @Override
4076    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4077            int targetUserId) {
4078        mContext.enforceCallingOrSelfPermission(
4079                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4080        List<CrossProfileIntentFilter> matches =
4081                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4082        if (matches != null) {
4083            int size = matches.size();
4084            for (int i = 0; i < size; i++) {
4085                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4086            }
4087        }
4088        return false;
4089    }
4090
4091    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4092            String resolvedType, int userId) {
4093        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4094        if (resolver != null) {
4095            return resolver.queryIntent(intent, resolvedType, false, userId);
4096        }
4097        return null;
4098    }
4099
4100    @Override
4101    public List<ResolveInfo> queryIntentActivities(Intent intent,
4102            String resolvedType, int flags, int userId) {
4103        if (!sUserManager.exists(userId)) return Collections.emptyList();
4104        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4105        ComponentName comp = intent.getComponent();
4106        if (comp == null) {
4107            if (intent.getSelector() != null) {
4108                intent = intent.getSelector();
4109                comp = intent.getComponent();
4110            }
4111        }
4112
4113        if (comp != null) {
4114            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4115            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4116            if (ai != null) {
4117                final ResolveInfo ri = new ResolveInfo();
4118                ri.activityInfo = ai;
4119                list.add(ri);
4120            }
4121            return list;
4122        }
4123
4124        // reader
4125        synchronized (mPackages) {
4126            final String pkgName = intent.getPackage();
4127            if (pkgName == null) {
4128                List<CrossProfileIntentFilter> matchingFilters =
4129                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4130                // Check for results that need to skip the current profile.
4131                ResolveInfo resolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4132                        resolvedType, flags, userId);
4133                if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) {
4134                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4135                    result.add(resolveInfo);
4136                    return filterIfNotPrimaryUser(result, userId);
4137                }
4138
4139                // Check for results in the current profile.
4140                List<ResolveInfo> result = mActivities.queryIntent(
4141                        intent, resolvedType, flags, userId);
4142
4143                // Check for cross profile results.
4144                resolveInfo = queryCrossProfileIntents(
4145                        matchingFilters, intent, resolvedType, flags, userId);
4146                if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) {
4147                    result.add(resolveInfo);
4148                    Collections.sort(result, mResolvePrioritySorter);
4149                }
4150                result = filterIfNotPrimaryUser(result, userId);
4151                if (result.size() > 1 && hasWebURI(intent)) {
4152                    return filterCandidatesWithDomainPreferedActivitiesLPr(flags, result);
4153                }
4154                return result;
4155            }
4156            final PackageParser.Package pkg = mPackages.get(pkgName);
4157            if (pkg != null) {
4158                return filterIfNotPrimaryUser(
4159                        mActivities.queryIntentForPackage(
4160                                intent, resolvedType, flags, pkg.activities, userId),
4161                        userId);
4162            }
4163            return new ArrayList<ResolveInfo>();
4164        }
4165    }
4166
4167    private boolean isUserEnabled(int userId) {
4168        long callingId = Binder.clearCallingIdentity();
4169        try {
4170            UserInfo userInfo = sUserManager.getUserInfo(userId);
4171            return userInfo != null && userInfo.isEnabled();
4172        } finally {
4173            Binder.restoreCallingIdentity(callingId);
4174        }
4175    }
4176
4177    /**
4178     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4179     *
4180     * @return filtered list
4181     */
4182    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4183        if (userId == UserHandle.USER_OWNER) {
4184            return resolveInfos;
4185        }
4186        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4187            ResolveInfo info = resolveInfos.get(i);
4188            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4189                resolveInfos.remove(i);
4190            }
4191        }
4192        return resolveInfos;
4193    }
4194
4195    private static boolean hasWebURI(Intent intent) {
4196        if (intent.getData() == null) {
4197            return false;
4198        }
4199        final String scheme = intent.getScheme();
4200        if (TextUtils.isEmpty(scheme)) {
4201            return false;
4202        }
4203        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4204    }
4205
4206    private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPr(
4207            int flags, List<ResolveInfo> candidates) {
4208        if (DEBUG_PREFERRED) {
4209            Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " +
4210                    candidates.size());
4211        }
4212
4213        final int userId = UserHandle.getCallingUserId();
4214        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4215        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4216        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4217        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4218        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4219
4220        synchronized (mPackages) {
4221            final int count = candidates.size();
4222            // First, try to use the domain prefered App. Partition the candidates into four lists:
4223            // one for the final results, one for the "do not use ever", one for "undefined status"
4224            // and finally one for "Browser App type".
4225            for (int n=0; n<count; n++) {
4226                ResolveInfo info = candidates.get(n);
4227                String packageName = info.activityInfo.packageName;
4228                PackageSetting ps = mSettings.mPackages.get(packageName);
4229                if (ps != null) {
4230                    // Add to the special match all list (Browser use case)
4231                    if (info.handleAllWebDataURI) {
4232                        matchAllList.add(info);
4233                        continue;
4234                    }
4235                    // Try to get the status from User settings first
4236                    int status = getDomainVerificationStatusLPr(ps, userId);
4237                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4238                        alwaysList.add(info);
4239                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4240                        neverList.add(info);
4241                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4242                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4243                        undefinedList.add(info);
4244                    }
4245                }
4246            }
4247            // First try to add the "always" if there is any
4248            if (alwaysList.size() > 0) {
4249                result.addAll(alwaysList);
4250            } else {
4251                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4252                result.addAll(undefinedList);
4253                // Also add Browsers (all of them or only the default one)
4254                if ((flags & MATCH_ALL) != 0) {
4255                    result.addAll(matchAllList);
4256                } else {
4257                    // Try to add the Default Browser if we can
4258                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(
4259                            UserHandle.myUserId());
4260                    if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
4261                        boolean defaultBrowserFound = false;
4262                        final int browserCount = matchAllList.size();
4263                        for (int n=0; n<browserCount; n++) {
4264                            ResolveInfo browser = matchAllList.get(n);
4265                            if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4266                                result.add(browser);
4267                                defaultBrowserFound = true;
4268                                break;
4269                            }
4270                        }
4271                        if (!defaultBrowserFound) {
4272                            result.addAll(matchAllList);
4273                        }
4274                    } else {
4275                        result.addAll(matchAllList);
4276                    }
4277                }
4278
4279                // If there is nothing selected, add all candidates and remove the ones that the User
4280                // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4281                if (result.size() == 0) {
4282                    result.addAll(candidates);
4283                    result.removeAll(neverList);
4284                }
4285            }
4286        }
4287        if (DEBUG_PREFERRED) {
4288            Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " +
4289                    result.size());
4290        }
4291        return result;
4292    }
4293
4294    private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4295        int status = ps.getDomainVerificationStatusForUser(userId);
4296        // if none available, get the master status
4297        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4298            if (ps.getIntentFilterVerificationInfo() != null) {
4299                status = ps.getIntentFilterVerificationInfo().getStatus();
4300            }
4301        }
4302        return status;
4303    }
4304
4305    private ResolveInfo querySkipCurrentProfileIntents(
4306            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4307            int flags, int sourceUserId) {
4308        if (matchingFilters != null) {
4309            int size = matchingFilters.size();
4310            for (int i = 0; i < size; i ++) {
4311                CrossProfileIntentFilter filter = matchingFilters.get(i);
4312                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4313                    // Checking if there are activities in the target user that can handle the
4314                    // intent.
4315                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4316                            flags, sourceUserId);
4317                    if (resolveInfo != null) {
4318                        return resolveInfo;
4319                    }
4320                }
4321            }
4322        }
4323        return null;
4324    }
4325
4326    // Return matching ResolveInfo if any for skip current profile intent filters.
4327    private ResolveInfo queryCrossProfileIntents(
4328            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4329            int flags, int sourceUserId) {
4330        if (matchingFilters != null) {
4331            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4332            // match the same intent. For performance reasons, it is better not to
4333            // run queryIntent twice for the same userId
4334            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4335            int size = matchingFilters.size();
4336            for (int i = 0; i < size; i++) {
4337                CrossProfileIntentFilter filter = matchingFilters.get(i);
4338                int targetUserId = filter.getTargetUserId();
4339                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4340                        && !alreadyTriedUserIds.get(targetUserId)) {
4341                    // Checking if there are activities in the target user that can handle the
4342                    // intent.
4343                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4344                            flags, sourceUserId);
4345                    if (resolveInfo != null) return resolveInfo;
4346                    alreadyTriedUserIds.put(targetUserId, true);
4347                }
4348            }
4349        }
4350        return null;
4351    }
4352
4353    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4354            String resolvedType, int flags, int sourceUserId) {
4355        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4356                resolvedType, flags, filter.getTargetUserId());
4357        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4358            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4359        }
4360        return null;
4361    }
4362
4363    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4364            int sourceUserId, int targetUserId) {
4365        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4366        String className;
4367        if (targetUserId == UserHandle.USER_OWNER) {
4368            className = FORWARD_INTENT_TO_USER_OWNER;
4369        } else {
4370            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4371        }
4372        ComponentName forwardingActivityComponentName = new ComponentName(
4373                mAndroidApplication.packageName, className);
4374        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4375                sourceUserId);
4376        if (targetUserId == UserHandle.USER_OWNER) {
4377            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4378            forwardingResolveInfo.noResourceId = true;
4379        }
4380        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4381        forwardingResolveInfo.priority = 0;
4382        forwardingResolveInfo.preferredOrder = 0;
4383        forwardingResolveInfo.match = 0;
4384        forwardingResolveInfo.isDefault = true;
4385        forwardingResolveInfo.filter = filter;
4386        forwardingResolveInfo.targetUserId = targetUserId;
4387        return forwardingResolveInfo;
4388    }
4389
4390    @Override
4391    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4392            Intent[] specifics, String[] specificTypes, Intent intent,
4393            String resolvedType, int flags, int userId) {
4394        if (!sUserManager.exists(userId)) return Collections.emptyList();
4395        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4396                false, "query intent activity options");
4397        final String resultsAction = intent.getAction();
4398
4399        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4400                | PackageManager.GET_RESOLVED_FILTER, userId);
4401
4402        if (DEBUG_INTENT_MATCHING) {
4403            Log.v(TAG, "Query " + intent + ": " + results);
4404        }
4405
4406        int specificsPos = 0;
4407        int N;
4408
4409        // todo: note that the algorithm used here is O(N^2).  This
4410        // isn't a problem in our current environment, but if we start running
4411        // into situations where we have more than 5 or 10 matches then this
4412        // should probably be changed to something smarter...
4413
4414        // First we go through and resolve each of the specific items
4415        // that were supplied, taking care of removing any corresponding
4416        // duplicate items in the generic resolve list.
4417        if (specifics != null) {
4418            for (int i=0; i<specifics.length; i++) {
4419                final Intent sintent = specifics[i];
4420                if (sintent == null) {
4421                    continue;
4422                }
4423
4424                if (DEBUG_INTENT_MATCHING) {
4425                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4426                }
4427
4428                String action = sintent.getAction();
4429                if (resultsAction != null && resultsAction.equals(action)) {
4430                    // If this action was explicitly requested, then don't
4431                    // remove things that have it.
4432                    action = null;
4433                }
4434
4435                ResolveInfo ri = null;
4436                ActivityInfo ai = null;
4437
4438                ComponentName comp = sintent.getComponent();
4439                if (comp == null) {
4440                    ri = resolveIntent(
4441                        sintent,
4442                        specificTypes != null ? specificTypes[i] : null,
4443                            flags, userId);
4444                    if (ri == null) {
4445                        continue;
4446                    }
4447                    if (ri == mResolveInfo) {
4448                        // ACK!  Must do something better with this.
4449                    }
4450                    ai = ri.activityInfo;
4451                    comp = new ComponentName(ai.applicationInfo.packageName,
4452                            ai.name);
4453                } else {
4454                    ai = getActivityInfo(comp, flags, userId);
4455                    if (ai == null) {
4456                        continue;
4457                    }
4458                }
4459
4460                // Look for any generic query activities that are duplicates
4461                // of this specific one, and remove them from the results.
4462                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4463                N = results.size();
4464                int j;
4465                for (j=specificsPos; j<N; j++) {
4466                    ResolveInfo sri = results.get(j);
4467                    if ((sri.activityInfo.name.equals(comp.getClassName())
4468                            && sri.activityInfo.applicationInfo.packageName.equals(
4469                                    comp.getPackageName()))
4470                        || (action != null && sri.filter.matchAction(action))) {
4471                        results.remove(j);
4472                        if (DEBUG_INTENT_MATCHING) Log.v(
4473                            TAG, "Removing duplicate item from " + j
4474                            + " due to specific " + specificsPos);
4475                        if (ri == null) {
4476                            ri = sri;
4477                        }
4478                        j--;
4479                        N--;
4480                    }
4481                }
4482
4483                // Add this specific item to its proper place.
4484                if (ri == null) {
4485                    ri = new ResolveInfo();
4486                    ri.activityInfo = ai;
4487                }
4488                results.add(specificsPos, ri);
4489                ri.specificIndex = i;
4490                specificsPos++;
4491            }
4492        }
4493
4494        // Now we go through the remaining generic results and remove any
4495        // duplicate actions that are found here.
4496        N = results.size();
4497        for (int i=specificsPos; i<N-1; i++) {
4498            final ResolveInfo rii = results.get(i);
4499            if (rii.filter == null) {
4500                continue;
4501            }
4502
4503            // Iterate over all of the actions of this result's intent
4504            // filter...  typically this should be just one.
4505            final Iterator<String> it = rii.filter.actionsIterator();
4506            if (it == null) {
4507                continue;
4508            }
4509            while (it.hasNext()) {
4510                final String action = it.next();
4511                if (resultsAction != null && resultsAction.equals(action)) {
4512                    // If this action was explicitly requested, then don't
4513                    // remove things that have it.
4514                    continue;
4515                }
4516                for (int j=i+1; j<N; j++) {
4517                    final ResolveInfo rij = results.get(j);
4518                    if (rij.filter != null && rij.filter.hasAction(action)) {
4519                        results.remove(j);
4520                        if (DEBUG_INTENT_MATCHING) Log.v(
4521                            TAG, "Removing duplicate item from " + j
4522                            + " due to action " + action + " at " + i);
4523                        j--;
4524                        N--;
4525                    }
4526                }
4527            }
4528
4529            // If the caller didn't request filter information, drop it now
4530            // so we don't have to marshall/unmarshall it.
4531            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4532                rii.filter = null;
4533            }
4534        }
4535
4536        // Filter out the caller activity if so requested.
4537        if (caller != null) {
4538            N = results.size();
4539            for (int i=0; i<N; i++) {
4540                ActivityInfo ainfo = results.get(i).activityInfo;
4541                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
4542                        && caller.getClassName().equals(ainfo.name)) {
4543                    results.remove(i);
4544                    break;
4545                }
4546            }
4547        }
4548
4549        // If the caller didn't request filter information,
4550        // drop them now so we don't have to
4551        // marshall/unmarshall it.
4552        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4553            N = results.size();
4554            for (int i=0; i<N; i++) {
4555                results.get(i).filter = null;
4556            }
4557        }
4558
4559        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
4560        return results;
4561    }
4562
4563    @Override
4564    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
4565            int userId) {
4566        if (!sUserManager.exists(userId)) return Collections.emptyList();
4567        ComponentName comp = intent.getComponent();
4568        if (comp == null) {
4569            if (intent.getSelector() != null) {
4570                intent = intent.getSelector();
4571                comp = intent.getComponent();
4572            }
4573        }
4574        if (comp != null) {
4575            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4576            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
4577            if (ai != null) {
4578                ResolveInfo ri = new ResolveInfo();
4579                ri.activityInfo = ai;
4580                list.add(ri);
4581            }
4582            return list;
4583        }
4584
4585        // reader
4586        synchronized (mPackages) {
4587            String pkgName = intent.getPackage();
4588            if (pkgName == null) {
4589                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
4590            }
4591            final PackageParser.Package pkg = mPackages.get(pkgName);
4592            if (pkg != null) {
4593                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
4594                        userId);
4595            }
4596            return null;
4597        }
4598    }
4599
4600    @Override
4601    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
4602        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
4603        if (!sUserManager.exists(userId)) return null;
4604        if (query != null) {
4605            if (query.size() >= 1) {
4606                // If there is more than one service with the same priority,
4607                // just arbitrarily pick the first one.
4608                return query.get(0);
4609            }
4610        }
4611        return null;
4612    }
4613
4614    @Override
4615    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
4616            int userId) {
4617        if (!sUserManager.exists(userId)) return Collections.emptyList();
4618        ComponentName comp = intent.getComponent();
4619        if (comp == null) {
4620            if (intent.getSelector() != null) {
4621                intent = intent.getSelector();
4622                comp = intent.getComponent();
4623            }
4624        }
4625        if (comp != null) {
4626            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4627            final ServiceInfo si = getServiceInfo(comp, flags, userId);
4628            if (si != null) {
4629                final ResolveInfo ri = new ResolveInfo();
4630                ri.serviceInfo = si;
4631                list.add(ri);
4632            }
4633            return list;
4634        }
4635
4636        // reader
4637        synchronized (mPackages) {
4638            String pkgName = intent.getPackage();
4639            if (pkgName == null) {
4640                return mServices.queryIntent(intent, resolvedType, flags, userId);
4641            }
4642            final PackageParser.Package pkg = mPackages.get(pkgName);
4643            if (pkg != null) {
4644                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
4645                        userId);
4646            }
4647            return null;
4648        }
4649    }
4650
4651    @Override
4652    public List<ResolveInfo> queryIntentContentProviders(
4653            Intent intent, String resolvedType, int flags, int userId) {
4654        if (!sUserManager.exists(userId)) return Collections.emptyList();
4655        ComponentName comp = intent.getComponent();
4656        if (comp == null) {
4657            if (intent.getSelector() != null) {
4658                intent = intent.getSelector();
4659                comp = intent.getComponent();
4660            }
4661        }
4662        if (comp != null) {
4663            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4664            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
4665            if (pi != null) {
4666                final ResolveInfo ri = new ResolveInfo();
4667                ri.providerInfo = pi;
4668                list.add(ri);
4669            }
4670            return list;
4671        }
4672
4673        // reader
4674        synchronized (mPackages) {
4675            String pkgName = intent.getPackage();
4676            if (pkgName == null) {
4677                return mProviders.queryIntent(intent, resolvedType, flags, userId);
4678            }
4679            final PackageParser.Package pkg = mPackages.get(pkgName);
4680            if (pkg != null) {
4681                return mProviders.queryIntentForPackage(
4682                        intent, resolvedType, flags, pkg.providers, userId);
4683            }
4684            return null;
4685        }
4686    }
4687
4688    @Override
4689    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
4690        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4691
4692        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
4693
4694        // writer
4695        synchronized (mPackages) {
4696            ArrayList<PackageInfo> list;
4697            if (listUninstalled) {
4698                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
4699                for (PackageSetting ps : mSettings.mPackages.values()) {
4700                    PackageInfo pi;
4701                    if (ps.pkg != null) {
4702                        pi = generatePackageInfo(ps.pkg, flags, userId);
4703                    } else {
4704                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4705                    }
4706                    if (pi != null) {
4707                        list.add(pi);
4708                    }
4709                }
4710            } else {
4711                list = new ArrayList<PackageInfo>(mPackages.size());
4712                for (PackageParser.Package p : mPackages.values()) {
4713                    PackageInfo pi = generatePackageInfo(p, flags, userId);
4714                    if (pi != null) {
4715                        list.add(pi);
4716                    }
4717                }
4718            }
4719
4720            return new ParceledListSlice<PackageInfo>(list);
4721        }
4722    }
4723
4724    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
4725            String[] permissions, boolean[] tmp, int flags, int userId) {
4726        int numMatch = 0;
4727        final PermissionsState permissionsState = ps.getPermissionsState();
4728        for (int i=0; i<permissions.length; i++) {
4729            final String permission = permissions[i];
4730            if (permissionsState.hasPermission(permission, userId)) {
4731                tmp[i] = true;
4732                numMatch++;
4733            } else {
4734                tmp[i] = false;
4735            }
4736        }
4737        if (numMatch == 0) {
4738            return;
4739        }
4740        PackageInfo pi;
4741        if (ps.pkg != null) {
4742            pi = generatePackageInfo(ps.pkg, flags, userId);
4743        } else {
4744            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4745        }
4746        // The above might return null in cases of uninstalled apps or install-state
4747        // skew across users/profiles.
4748        if (pi != null) {
4749            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
4750                if (numMatch == permissions.length) {
4751                    pi.requestedPermissions = permissions;
4752                } else {
4753                    pi.requestedPermissions = new String[numMatch];
4754                    numMatch = 0;
4755                    for (int i=0; i<permissions.length; i++) {
4756                        if (tmp[i]) {
4757                            pi.requestedPermissions[numMatch] = permissions[i];
4758                            numMatch++;
4759                        }
4760                    }
4761                }
4762            }
4763            list.add(pi);
4764        }
4765    }
4766
4767    @Override
4768    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
4769            String[] permissions, int flags, int userId) {
4770        if (!sUserManager.exists(userId)) return null;
4771        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4772
4773        // writer
4774        synchronized (mPackages) {
4775            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
4776            boolean[] tmpBools = new boolean[permissions.length];
4777            if (listUninstalled) {
4778                for (PackageSetting ps : mSettings.mPackages.values()) {
4779                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
4780                }
4781            } else {
4782                for (PackageParser.Package pkg : mPackages.values()) {
4783                    PackageSetting ps = (PackageSetting)pkg.mExtras;
4784                    if (ps != null) {
4785                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
4786                                userId);
4787                    }
4788                }
4789            }
4790
4791            return new ParceledListSlice<PackageInfo>(list);
4792        }
4793    }
4794
4795    @Override
4796    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
4797        if (!sUserManager.exists(userId)) return null;
4798        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4799
4800        // writer
4801        synchronized (mPackages) {
4802            ArrayList<ApplicationInfo> list;
4803            if (listUninstalled) {
4804                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
4805                for (PackageSetting ps : mSettings.mPackages.values()) {
4806                    ApplicationInfo ai;
4807                    if (ps.pkg != null) {
4808                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4809                                ps.readUserState(userId), userId);
4810                    } else {
4811                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
4812                    }
4813                    if (ai != null) {
4814                        list.add(ai);
4815                    }
4816                }
4817            } else {
4818                list = new ArrayList<ApplicationInfo>(mPackages.size());
4819                for (PackageParser.Package p : mPackages.values()) {
4820                    if (p.mExtras != null) {
4821                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4822                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
4823                        if (ai != null) {
4824                            list.add(ai);
4825                        }
4826                    }
4827                }
4828            }
4829
4830            return new ParceledListSlice<ApplicationInfo>(list);
4831        }
4832    }
4833
4834    public List<ApplicationInfo> getPersistentApplications(int flags) {
4835        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
4836
4837        // reader
4838        synchronized (mPackages) {
4839            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
4840            final int userId = UserHandle.getCallingUserId();
4841            while (i.hasNext()) {
4842                final PackageParser.Package p = i.next();
4843                if (p.applicationInfo != null
4844                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
4845                        && (!mSafeMode || isSystemApp(p))) {
4846                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
4847                    if (ps != null) {
4848                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4849                                ps.readUserState(userId), userId);
4850                        if (ai != null) {
4851                            finalList.add(ai);
4852                        }
4853                    }
4854                }
4855            }
4856        }
4857
4858        return finalList;
4859    }
4860
4861    @Override
4862    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
4863        if (!sUserManager.exists(userId)) return null;
4864        // reader
4865        synchronized (mPackages) {
4866            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
4867            PackageSetting ps = provider != null
4868                    ? mSettings.mPackages.get(provider.owner.packageName)
4869                    : null;
4870            return ps != null
4871                    && mSettings.isEnabledLPr(provider.info, flags, userId)
4872                    && (!mSafeMode || (provider.info.applicationInfo.flags
4873                            &ApplicationInfo.FLAG_SYSTEM) != 0)
4874                    ? PackageParser.generateProviderInfo(provider, flags,
4875                            ps.readUserState(userId), userId)
4876                    : null;
4877        }
4878    }
4879
4880    /**
4881     * @deprecated
4882     */
4883    @Deprecated
4884    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
4885        // reader
4886        synchronized (mPackages) {
4887            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
4888                    .entrySet().iterator();
4889            final int userId = UserHandle.getCallingUserId();
4890            while (i.hasNext()) {
4891                Map.Entry<String, PackageParser.Provider> entry = i.next();
4892                PackageParser.Provider p = entry.getValue();
4893                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4894
4895                if (ps != null && p.syncable
4896                        && (!mSafeMode || (p.info.applicationInfo.flags
4897                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
4898                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
4899                            ps.readUserState(userId), userId);
4900                    if (info != null) {
4901                        outNames.add(entry.getKey());
4902                        outInfo.add(info);
4903                    }
4904                }
4905            }
4906        }
4907    }
4908
4909    @Override
4910    public List<ProviderInfo> queryContentProviders(String processName,
4911            int uid, int flags) {
4912        ArrayList<ProviderInfo> finalList = null;
4913        // reader
4914        synchronized (mPackages) {
4915            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
4916            final int userId = processName != null ?
4917                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
4918            while (i.hasNext()) {
4919                final PackageParser.Provider p = i.next();
4920                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4921                if (ps != null && p.info.authority != null
4922                        && (processName == null
4923                                || (p.info.processName.equals(processName)
4924                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
4925                        && mSettings.isEnabledLPr(p.info, flags, userId)
4926                        && (!mSafeMode
4927                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
4928                    if (finalList == null) {
4929                        finalList = new ArrayList<ProviderInfo>(3);
4930                    }
4931                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
4932                            ps.readUserState(userId), userId);
4933                    if (info != null) {
4934                        finalList.add(info);
4935                    }
4936                }
4937            }
4938        }
4939
4940        if (finalList != null) {
4941            Collections.sort(finalList, mProviderInitOrderSorter);
4942        }
4943
4944        return finalList;
4945    }
4946
4947    @Override
4948    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
4949            int flags) {
4950        // reader
4951        synchronized (mPackages) {
4952            final PackageParser.Instrumentation i = mInstrumentation.get(name);
4953            return PackageParser.generateInstrumentationInfo(i, flags);
4954        }
4955    }
4956
4957    @Override
4958    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4959            int flags) {
4960        ArrayList<InstrumentationInfo> finalList =
4961            new ArrayList<InstrumentationInfo>();
4962
4963        // reader
4964        synchronized (mPackages) {
4965            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4966            while (i.hasNext()) {
4967                final PackageParser.Instrumentation p = i.next();
4968                if (targetPackage == null
4969                        || targetPackage.equals(p.info.targetPackage)) {
4970                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4971                            flags);
4972                    if (ii != null) {
4973                        finalList.add(ii);
4974                    }
4975                }
4976            }
4977        }
4978
4979        return finalList;
4980    }
4981
4982    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4983        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4984        if (overlays == null) {
4985            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4986            return;
4987        }
4988        for (PackageParser.Package opkg : overlays.values()) {
4989            // Not much to do if idmap fails: we already logged the error
4990            // and we certainly don't want to abort installation of pkg simply
4991            // because an overlay didn't fit properly. For these reasons,
4992            // ignore the return value of createIdmapForPackagePairLI.
4993            createIdmapForPackagePairLI(pkg, opkg);
4994        }
4995    }
4996
4997    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4998            PackageParser.Package opkg) {
4999        if (!opkg.mTrustedOverlay) {
5000            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5001                    opkg.baseCodePath + ": overlay not trusted");
5002            return false;
5003        }
5004        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5005        if (overlaySet == null) {
5006            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5007                    opkg.baseCodePath + " but target package has no known overlays");
5008            return false;
5009        }
5010        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5011        // TODO: generate idmap for split APKs
5012        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5013            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5014                    + opkg.baseCodePath);
5015            return false;
5016        }
5017        PackageParser.Package[] overlayArray =
5018            overlaySet.values().toArray(new PackageParser.Package[0]);
5019        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5020            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5021                return p1.mOverlayPriority - p2.mOverlayPriority;
5022            }
5023        };
5024        Arrays.sort(overlayArray, cmp);
5025
5026        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5027        int i = 0;
5028        for (PackageParser.Package p : overlayArray) {
5029            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5030        }
5031        return true;
5032    }
5033
5034    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5035        final File[] files = dir.listFiles();
5036        if (ArrayUtils.isEmpty(files)) {
5037            Log.d(TAG, "No files in app dir " + dir);
5038            return;
5039        }
5040
5041        if (DEBUG_PACKAGE_SCANNING) {
5042            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5043                    + " flags=0x" + Integer.toHexString(parseFlags));
5044        }
5045
5046        for (File file : files) {
5047            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5048                    && !PackageInstallerService.isStageName(file.getName());
5049            if (!isPackage) {
5050                // Ignore entries which are not packages
5051                continue;
5052            }
5053            try {
5054                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5055                        scanFlags, currentTime, null);
5056            } catch (PackageManagerException e) {
5057                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5058
5059                // Delete invalid userdata apps
5060                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5061                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5062                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5063                    if (file.isDirectory()) {
5064                        mInstaller.rmPackageDir(file.getAbsolutePath());
5065                    } else {
5066                        file.delete();
5067                    }
5068                }
5069            }
5070        }
5071    }
5072
5073    private static File getSettingsProblemFile() {
5074        File dataDir = Environment.getDataDirectory();
5075        File systemDir = new File(dataDir, "system");
5076        File fname = new File(systemDir, "uiderrors.txt");
5077        return fname;
5078    }
5079
5080    static void reportSettingsProblem(int priority, String msg) {
5081        logCriticalInfo(priority, msg);
5082    }
5083
5084    static void logCriticalInfo(int priority, String msg) {
5085        Slog.println(priority, TAG, msg);
5086        EventLogTags.writePmCriticalInfo(msg);
5087        try {
5088            File fname = getSettingsProblemFile();
5089            FileOutputStream out = new FileOutputStream(fname, true);
5090            PrintWriter pw = new FastPrintWriter(out);
5091            SimpleDateFormat formatter = new SimpleDateFormat();
5092            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5093            pw.println(dateString + ": " + msg);
5094            pw.close();
5095            FileUtils.setPermissions(
5096                    fname.toString(),
5097                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5098                    -1, -1);
5099        } catch (java.io.IOException e) {
5100        }
5101    }
5102
5103    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5104            PackageParser.Package pkg, File srcFile, int parseFlags)
5105            throws PackageManagerException {
5106        if (ps != null
5107                && ps.codePath.equals(srcFile)
5108                && ps.timeStamp == srcFile.lastModified()
5109                && !isCompatSignatureUpdateNeeded(pkg)
5110                && !isRecoverSignatureUpdateNeeded(pkg)) {
5111            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5112            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5113            ArraySet<PublicKey> signingKs;
5114            synchronized (mPackages) {
5115                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5116            }
5117            if (ps.signatures.mSignatures != null
5118                    && ps.signatures.mSignatures.length != 0
5119                    && signingKs != null) {
5120                // Optimization: reuse the existing cached certificates
5121                // if the package appears to be unchanged.
5122                pkg.mSignatures = ps.signatures.mSignatures;
5123                pkg.mSigningKeys = signingKs;
5124                return;
5125            }
5126
5127            Slog.w(TAG, "PackageSetting for " + ps.name
5128                    + " is missing signatures.  Collecting certs again to recover them.");
5129        } else {
5130            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5131        }
5132
5133        try {
5134            pp.collectCertificates(pkg, parseFlags);
5135            pp.collectManifestDigest(pkg);
5136        } catch (PackageParserException e) {
5137            throw PackageManagerException.from(e);
5138        }
5139    }
5140
5141    /*
5142     *  Scan a package and return the newly parsed package.
5143     *  Returns null in case of errors and the error code is stored in mLastScanError
5144     */
5145    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5146            long currentTime, UserHandle user) throws PackageManagerException {
5147        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5148        parseFlags |= mDefParseFlags;
5149        PackageParser pp = new PackageParser();
5150        pp.setSeparateProcesses(mSeparateProcesses);
5151        pp.setOnlyCoreApps(mOnlyCore);
5152        pp.setDisplayMetrics(mMetrics);
5153
5154        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5155            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5156        }
5157
5158        final PackageParser.Package pkg;
5159        try {
5160            pkg = pp.parsePackage(scanFile, parseFlags);
5161        } catch (PackageParserException e) {
5162            throw PackageManagerException.from(e);
5163        }
5164
5165        PackageSetting ps = null;
5166        PackageSetting updatedPkg;
5167        // reader
5168        synchronized (mPackages) {
5169            // Look to see if we already know about this package.
5170            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5171            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5172                // This package has been renamed to its original name.  Let's
5173                // use that.
5174                ps = mSettings.peekPackageLPr(oldName);
5175            }
5176            // If there was no original package, see one for the real package name.
5177            if (ps == null) {
5178                ps = mSettings.peekPackageLPr(pkg.packageName);
5179            }
5180            // Check to see if this package could be hiding/updating a system
5181            // package.  Must look for it either under the original or real
5182            // package name depending on our state.
5183            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5184            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5185        }
5186        boolean updatedPkgBetter = false;
5187        // First check if this is a system package that may involve an update
5188        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5189            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5190            // it needs to drop FLAG_PRIVILEGED.
5191            if (locationIsPrivileged(scanFile)) {
5192                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5193            } else {
5194                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5195            }
5196
5197            if (ps != null && !ps.codePath.equals(scanFile)) {
5198                // The path has changed from what was last scanned...  check the
5199                // version of the new path against what we have stored to determine
5200                // what to do.
5201                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5202                if (pkg.mVersionCode <= ps.versionCode) {
5203                    // The system package has been updated and the code path does not match
5204                    // Ignore entry. Skip it.
5205                    Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5206                            + " ignored: updated version " + ps.versionCode
5207                            + " better than this " + pkg.mVersionCode);
5208                    if (!updatedPkg.codePath.equals(scanFile)) {
5209                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5210                                + ps.name + " changing from " + updatedPkg.codePathString
5211                                + " to " + scanFile);
5212                        updatedPkg.codePath = scanFile;
5213                        updatedPkg.codePathString = scanFile.toString();
5214                        updatedPkg.resourcePath = scanFile;
5215                        updatedPkg.resourcePathString = scanFile.toString();
5216                    }
5217                    updatedPkg.pkg = pkg;
5218                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
5219                } else {
5220                    // The current app on the system partition is better than
5221                    // what we have updated to on the data partition; switch
5222                    // back to the system partition version.
5223                    // At this point, its safely assumed that package installation for
5224                    // apps in system partition will go through. If not there won't be a working
5225                    // version of the app
5226                    // writer
5227                    synchronized (mPackages) {
5228                        // Just remove the loaded entries from package lists.
5229                        mPackages.remove(ps.name);
5230                    }
5231
5232                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5233                            + " reverting from " + ps.codePathString
5234                            + ": new version " + pkg.mVersionCode
5235                            + " better than installed " + ps.versionCode);
5236
5237                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5238                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5239                    synchronized (mInstallLock) {
5240                        args.cleanUpResourcesLI();
5241                    }
5242                    synchronized (mPackages) {
5243                        mSettings.enableSystemPackageLPw(ps.name);
5244                    }
5245                    updatedPkgBetter = true;
5246                }
5247            }
5248        }
5249
5250        if (updatedPkg != null) {
5251            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5252            // initially
5253            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5254
5255            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5256            // flag set initially
5257            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5258                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5259            }
5260        }
5261
5262        // Verify certificates against what was last scanned
5263        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5264
5265        /*
5266         * A new system app appeared, but we already had a non-system one of the
5267         * same name installed earlier.
5268         */
5269        boolean shouldHideSystemApp = false;
5270        if (updatedPkg == null && ps != null
5271                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5272            /*
5273             * Check to make sure the signatures match first. If they don't,
5274             * wipe the installed application and its data.
5275             */
5276            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5277                    != PackageManager.SIGNATURE_MATCH) {
5278                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5279                        + " signatures don't match existing userdata copy; removing");
5280                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5281                ps = null;
5282            } else {
5283                /*
5284                 * If the newly-added system app is an older version than the
5285                 * already installed version, hide it. It will be scanned later
5286                 * and re-added like an update.
5287                 */
5288                if (pkg.mVersionCode <= ps.versionCode) {
5289                    shouldHideSystemApp = true;
5290                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5291                            + " but new version " + pkg.mVersionCode + " better than installed "
5292                            + ps.versionCode + "; hiding system");
5293                } else {
5294                    /*
5295                     * The newly found system app is a newer version that the
5296                     * one previously installed. Simply remove the
5297                     * already-installed application and replace it with our own
5298                     * while keeping the application data.
5299                     */
5300                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5301                            + " reverting from " + ps.codePathString + ": new version "
5302                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5303                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5304                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5305                    synchronized (mInstallLock) {
5306                        args.cleanUpResourcesLI();
5307                    }
5308                }
5309            }
5310        }
5311
5312        // The apk is forward locked (not public) if its code and resources
5313        // are kept in different files. (except for app in either system or
5314        // vendor path).
5315        // TODO grab this value from PackageSettings
5316        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5317            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5318                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5319            }
5320        }
5321
5322        // TODO: extend to support forward-locked splits
5323        String resourcePath = null;
5324        String baseResourcePath = null;
5325        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5326            if (ps != null && ps.resourcePathString != null) {
5327                resourcePath = ps.resourcePathString;
5328                baseResourcePath = ps.resourcePathString;
5329            } else {
5330                // Should not happen at all. Just log an error.
5331                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5332            }
5333        } else {
5334            resourcePath = pkg.codePath;
5335            baseResourcePath = pkg.baseCodePath;
5336        }
5337
5338        // Set application objects path explicitly.
5339        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5340        pkg.applicationInfo.setCodePath(pkg.codePath);
5341        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5342        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5343        pkg.applicationInfo.setResourcePath(resourcePath);
5344        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5345        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5346
5347        // Note that we invoke the following method only if we are about to unpack an application
5348        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5349                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5350
5351        /*
5352         * If the system app should be overridden by a previously installed
5353         * data, hide the system app now and let the /data/app scan pick it up
5354         * again.
5355         */
5356        if (shouldHideSystemApp) {
5357            synchronized (mPackages) {
5358                /*
5359                 * We have to grant systems permissions before we hide, because
5360                 * grantPermissions will assume the package update is trying to
5361                 * expand its permissions.
5362                 */
5363                grantPermissionsLPw(pkg, true, pkg.packageName);
5364                mSettings.disableSystemPackageLPw(pkg.packageName);
5365            }
5366        }
5367
5368        return scannedPkg;
5369    }
5370
5371    private static String fixProcessName(String defProcessName,
5372            String processName, int uid) {
5373        if (processName == null) {
5374            return defProcessName;
5375        }
5376        return processName;
5377    }
5378
5379    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5380            throws PackageManagerException {
5381        if (pkgSetting.signatures.mSignatures != null) {
5382            // Already existing package. Make sure signatures match
5383            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5384                    == PackageManager.SIGNATURE_MATCH;
5385            if (!match) {
5386                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5387                        == PackageManager.SIGNATURE_MATCH;
5388            }
5389            if (!match) {
5390                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5391                        == PackageManager.SIGNATURE_MATCH;
5392            }
5393            if (!match) {
5394                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5395                        + pkg.packageName + " signatures do not match the "
5396                        + "previously installed version; ignoring!");
5397            }
5398        }
5399
5400        // Check for shared user signatures
5401        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5402            // Already existing package. Make sure signatures match
5403            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5404                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5405            if (!match) {
5406                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5407                        == PackageManager.SIGNATURE_MATCH;
5408            }
5409            if (!match) {
5410                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5411                        == PackageManager.SIGNATURE_MATCH;
5412            }
5413            if (!match) {
5414                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5415                        "Package " + pkg.packageName
5416                        + " has no signatures that match those in shared user "
5417                        + pkgSetting.sharedUser.name + "; ignoring!");
5418            }
5419        }
5420    }
5421
5422    /**
5423     * Enforces that only the system UID or root's UID can call a method exposed
5424     * via Binder.
5425     *
5426     * @param message used as message if SecurityException is thrown
5427     * @throws SecurityException if the caller is not system or root
5428     */
5429    private static final void enforceSystemOrRoot(String message) {
5430        final int uid = Binder.getCallingUid();
5431        if (uid != Process.SYSTEM_UID && uid != 0) {
5432            throw new SecurityException(message);
5433        }
5434    }
5435
5436    @Override
5437    public void performBootDexOpt() {
5438        enforceSystemOrRoot("Only the system can request dexopt be performed");
5439
5440        // Before everything else, see whether we need to fstrim.
5441        try {
5442            IMountService ms = PackageHelper.getMountService();
5443            if (ms != null) {
5444                final boolean isUpgrade = isUpgrade();
5445                boolean doTrim = isUpgrade;
5446                if (doTrim) {
5447                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5448                } else {
5449                    final long interval = android.provider.Settings.Global.getLong(
5450                            mContext.getContentResolver(),
5451                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5452                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5453                    if (interval > 0) {
5454                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5455                        if (timeSinceLast > interval) {
5456                            doTrim = true;
5457                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5458                                    + "; running immediately");
5459                        }
5460                    }
5461                }
5462                if (doTrim) {
5463                    if (!isFirstBoot()) {
5464                        try {
5465                            ActivityManagerNative.getDefault().showBootMessage(
5466                                    mContext.getResources().getString(
5467                                            R.string.android_upgrading_fstrim), true);
5468                        } catch (RemoteException e) {
5469                        }
5470                    }
5471                    ms.runMaintenance();
5472                }
5473            } else {
5474                Slog.e(TAG, "Mount service unavailable!");
5475            }
5476        } catch (RemoteException e) {
5477            // Can't happen; MountService is local
5478        }
5479
5480        final ArraySet<PackageParser.Package> pkgs;
5481        synchronized (mPackages) {
5482            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5483        }
5484
5485        if (pkgs != null) {
5486            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5487            // in case the device runs out of space.
5488            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5489            // Give priority to core apps.
5490            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5491                PackageParser.Package pkg = it.next();
5492                if (pkg.coreApp) {
5493                    if (DEBUG_DEXOPT) {
5494                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5495                    }
5496                    sortedPkgs.add(pkg);
5497                    it.remove();
5498                }
5499            }
5500            // Give priority to system apps that listen for pre boot complete.
5501            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5502            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
5503            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5504                PackageParser.Package pkg = it.next();
5505                if (pkgNames.contains(pkg.packageName)) {
5506                    if (DEBUG_DEXOPT) {
5507                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
5508                    }
5509                    sortedPkgs.add(pkg);
5510                    it.remove();
5511                }
5512            }
5513            // Give priority to system apps.
5514            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5515                PackageParser.Package pkg = it.next();
5516                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
5517                    if (DEBUG_DEXOPT) {
5518                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
5519                    }
5520                    sortedPkgs.add(pkg);
5521                    it.remove();
5522                }
5523            }
5524            // Give priority to updated system apps.
5525            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5526                PackageParser.Package pkg = it.next();
5527                if (pkg.isUpdatedSystemApp()) {
5528                    if (DEBUG_DEXOPT) {
5529                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
5530                    }
5531                    sortedPkgs.add(pkg);
5532                    it.remove();
5533                }
5534            }
5535            // Give priority to apps that listen for boot complete.
5536            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
5537            pkgNames = getPackageNamesForIntent(intent);
5538            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5539                PackageParser.Package pkg = it.next();
5540                if (pkgNames.contains(pkg.packageName)) {
5541                    if (DEBUG_DEXOPT) {
5542                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
5543                    }
5544                    sortedPkgs.add(pkg);
5545                    it.remove();
5546                }
5547            }
5548            // Filter out packages that aren't recently used.
5549            filterRecentlyUsedApps(pkgs);
5550            // Add all remaining apps.
5551            for (PackageParser.Package pkg : pkgs) {
5552                if (DEBUG_DEXOPT) {
5553                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
5554                }
5555                sortedPkgs.add(pkg);
5556            }
5557
5558            // If we want to be lazy, filter everything that wasn't recently used.
5559            if (mLazyDexOpt) {
5560                filterRecentlyUsedApps(sortedPkgs);
5561            }
5562
5563            int i = 0;
5564            int total = sortedPkgs.size();
5565            File dataDir = Environment.getDataDirectory();
5566            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
5567            if (lowThreshold == 0) {
5568                throw new IllegalStateException("Invalid low memory threshold");
5569            }
5570            for (PackageParser.Package pkg : sortedPkgs) {
5571                long usableSpace = dataDir.getUsableSpace();
5572                if (usableSpace < lowThreshold) {
5573                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
5574                    break;
5575                }
5576                performBootDexOpt(pkg, ++i, total);
5577            }
5578        }
5579    }
5580
5581    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
5582        // Filter out packages that aren't recently used.
5583        //
5584        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
5585        // should do a full dexopt.
5586        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
5587            int total = pkgs.size();
5588            int skipped = 0;
5589            long now = System.currentTimeMillis();
5590            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
5591                PackageParser.Package pkg = i.next();
5592                long then = pkg.mLastPackageUsageTimeInMills;
5593                if (then + mDexOptLRUThresholdInMills < now) {
5594                    if (DEBUG_DEXOPT) {
5595                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
5596                              ((then == 0) ? "never" : new Date(then)));
5597                    }
5598                    i.remove();
5599                    skipped++;
5600                }
5601            }
5602            if (DEBUG_DEXOPT) {
5603                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
5604            }
5605        }
5606    }
5607
5608    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
5609        List<ResolveInfo> ris = null;
5610        try {
5611            ris = AppGlobals.getPackageManager().queryIntentReceivers(
5612                    intent, null, 0, UserHandle.USER_OWNER);
5613        } catch (RemoteException e) {
5614        }
5615        ArraySet<String> pkgNames = new ArraySet<String>();
5616        if (ris != null) {
5617            for (ResolveInfo ri : ris) {
5618                pkgNames.add(ri.activityInfo.packageName);
5619            }
5620        }
5621        return pkgNames;
5622    }
5623
5624    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
5625        if (DEBUG_DEXOPT) {
5626            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
5627        }
5628        if (!isFirstBoot()) {
5629            try {
5630                ActivityManagerNative.getDefault().showBootMessage(
5631                        mContext.getResources().getString(R.string.android_upgrading_apk,
5632                                curr, total), true);
5633            } catch (RemoteException e) {
5634            }
5635        }
5636        PackageParser.Package p = pkg;
5637        synchronized (mInstallLock) {
5638            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
5639                    false /* force dex */, false /* defer */, true /* include dependencies */);
5640        }
5641    }
5642
5643    @Override
5644    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
5645        return performDexOpt(packageName, instructionSet, false);
5646    }
5647
5648    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
5649        boolean dexopt = mLazyDexOpt || backgroundDexopt;
5650        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
5651        if (!dexopt && !updateUsage) {
5652            // We aren't going to dexopt or update usage, so bail early.
5653            return false;
5654        }
5655        PackageParser.Package p;
5656        final String targetInstructionSet;
5657        synchronized (mPackages) {
5658            p = mPackages.get(packageName);
5659            if (p == null) {
5660                return false;
5661            }
5662            if (updateUsage) {
5663                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
5664            }
5665            mPackageUsage.write(false);
5666            if (!dexopt) {
5667                // We aren't going to dexopt, so bail early.
5668                return false;
5669            }
5670
5671            targetInstructionSet = instructionSet != null ? instructionSet :
5672                    getPrimaryInstructionSet(p.applicationInfo);
5673            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
5674                return false;
5675            }
5676        }
5677
5678        synchronized (mInstallLock) {
5679            final String[] instructionSets = new String[] { targetInstructionSet };
5680            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
5681                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
5682            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
5683        }
5684    }
5685
5686    public ArraySet<String> getPackagesThatNeedDexOpt() {
5687        ArraySet<String> pkgs = null;
5688        synchronized (mPackages) {
5689            for (PackageParser.Package p : mPackages.values()) {
5690                if (DEBUG_DEXOPT) {
5691                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
5692                }
5693                if (!p.mDexOptPerformed.isEmpty()) {
5694                    continue;
5695                }
5696                if (pkgs == null) {
5697                    pkgs = new ArraySet<String>();
5698                }
5699                pkgs.add(p.packageName);
5700            }
5701        }
5702        return pkgs;
5703    }
5704
5705    public void shutdown() {
5706        mPackageUsage.write(true);
5707    }
5708
5709    @Override
5710    public void forceDexOpt(String packageName) {
5711        enforceSystemOrRoot("forceDexOpt");
5712
5713        PackageParser.Package pkg;
5714        synchronized (mPackages) {
5715            pkg = mPackages.get(packageName);
5716            if (pkg == null) {
5717                throw new IllegalArgumentException("Missing package: " + packageName);
5718            }
5719        }
5720
5721        synchronized (mInstallLock) {
5722            final String[] instructionSets = new String[] {
5723                    getPrimaryInstructionSet(pkg.applicationInfo) };
5724            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
5725                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
5726            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
5727                throw new IllegalStateException("Failed to dexopt: " + res);
5728            }
5729        }
5730    }
5731
5732    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
5733        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
5734            Slog.w(TAG, "Unable to update from " + oldPkg.name
5735                    + " to " + newPkg.packageName
5736                    + ": old package not in system partition");
5737            return false;
5738        } else if (mPackages.get(oldPkg.name) != null) {
5739            Slog.w(TAG, "Unable to update from " + oldPkg.name
5740                    + " to " + newPkg.packageName
5741                    + ": old package still exists");
5742            return false;
5743        }
5744        return true;
5745    }
5746
5747    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
5748        int[] users = sUserManager.getUserIds();
5749        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
5750        if (res < 0) {
5751            return res;
5752        }
5753        for (int user : users) {
5754            if (user != 0) {
5755                res = mInstaller.createUserData(volumeUuid, packageName,
5756                        UserHandle.getUid(user, uid), user, seinfo);
5757                if (res < 0) {
5758                    return res;
5759                }
5760            }
5761        }
5762        return res;
5763    }
5764
5765    private int removeDataDirsLI(String volumeUuid, String packageName) {
5766        int[] users = sUserManager.getUserIds();
5767        int res = 0;
5768        for (int user : users) {
5769            int resInner = mInstaller.remove(volumeUuid, packageName, user);
5770            if (resInner < 0) {
5771                res = resInner;
5772            }
5773        }
5774
5775        return res;
5776    }
5777
5778    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
5779        int[] users = sUserManager.getUserIds();
5780        int res = 0;
5781        for (int user : users) {
5782            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
5783            if (resInner < 0) {
5784                res = resInner;
5785            }
5786        }
5787        return res;
5788    }
5789
5790    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
5791            PackageParser.Package changingLib) {
5792        if (file.path != null) {
5793            usesLibraryFiles.add(file.path);
5794            return;
5795        }
5796        PackageParser.Package p = mPackages.get(file.apk);
5797        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
5798            // If we are doing this while in the middle of updating a library apk,
5799            // then we need to make sure to use that new apk for determining the
5800            // dependencies here.  (We haven't yet finished committing the new apk
5801            // to the package manager state.)
5802            if (p == null || p.packageName.equals(changingLib.packageName)) {
5803                p = changingLib;
5804            }
5805        }
5806        if (p != null) {
5807            usesLibraryFiles.addAll(p.getAllCodePaths());
5808        }
5809    }
5810
5811    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
5812            PackageParser.Package changingLib) throws PackageManagerException {
5813        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
5814            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
5815            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
5816            for (int i=0; i<N; i++) {
5817                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
5818                if (file == null) {
5819                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
5820                            "Package " + pkg.packageName + " requires unavailable shared library "
5821                            + pkg.usesLibraries.get(i) + "; failing!");
5822                }
5823                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5824            }
5825            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
5826            for (int i=0; i<N; i++) {
5827                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
5828                if (file == null) {
5829                    Slog.w(TAG, "Package " + pkg.packageName
5830                            + " desires unavailable shared library "
5831                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
5832                } else {
5833                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5834                }
5835            }
5836            N = usesLibraryFiles.size();
5837            if (N > 0) {
5838                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
5839            } else {
5840                pkg.usesLibraryFiles = null;
5841            }
5842        }
5843    }
5844
5845    private static boolean hasString(List<String> list, List<String> which) {
5846        if (list == null) {
5847            return false;
5848        }
5849        for (int i=list.size()-1; i>=0; i--) {
5850            for (int j=which.size()-1; j>=0; j--) {
5851                if (which.get(j).equals(list.get(i))) {
5852                    return true;
5853                }
5854            }
5855        }
5856        return false;
5857    }
5858
5859    private void updateAllSharedLibrariesLPw() {
5860        for (PackageParser.Package pkg : mPackages.values()) {
5861            try {
5862                updateSharedLibrariesLPw(pkg, null);
5863            } catch (PackageManagerException e) {
5864                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5865            }
5866        }
5867    }
5868
5869    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
5870            PackageParser.Package changingPkg) {
5871        ArrayList<PackageParser.Package> res = null;
5872        for (PackageParser.Package pkg : mPackages.values()) {
5873            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
5874                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
5875                if (res == null) {
5876                    res = new ArrayList<PackageParser.Package>();
5877                }
5878                res.add(pkg);
5879                try {
5880                    updateSharedLibrariesLPw(pkg, changingPkg);
5881                } catch (PackageManagerException e) {
5882                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5883                }
5884            }
5885        }
5886        return res;
5887    }
5888
5889    /**
5890     * Derive the value of the {@code cpuAbiOverride} based on the provided
5891     * value and an optional stored value from the package settings.
5892     */
5893    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
5894        String cpuAbiOverride = null;
5895
5896        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
5897            cpuAbiOverride = null;
5898        } else if (abiOverride != null) {
5899            cpuAbiOverride = abiOverride;
5900        } else if (settings != null) {
5901            cpuAbiOverride = settings.cpuAbiOverrideString;
5902        }
5903
5904        return cpuAbiOverride;
5905    }
5906
5907    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
5908            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5909        boolean success = false;
5910        try {
5911            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
5912                    currentTime, user);
5913            success = true;
5914            return res;
5915        } finally {
5916            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5917                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
5918            }
5919        }
5920    }
5921
5922    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
5923            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5924        final File scanFile = new File(pkg.codePath);
5925        if (pkg.applicationInfo.getCodePath() == null ||
5926                pkg.applicationInfo.getResourcePath() == null) {
5927            // Bail out. The resource and code paths haven't been set.
5928            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
5929                    "Code and resource paths haven't been set correctly");
5930        }
5931
5932        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5933            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
5934        } else {
5935            // Only allow system apps to be flagged as core apps.
5936            pkg.coreApp = false;
5937        }
5938
5939        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5940            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5941        }
5942
5943        if (mCustomResolverComponentName != null &&
5944                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5945            setUpCustomResolverActivity(pkg);
5946        }
5947
5948        if (pkg.packageName.equals("android")) {
5949            synchronized (mPackages) {
5950                if (mAndroidApplication != null) {
5951                    Slog.w(TAG, "*************************************************");
5952                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5953                    Slog.w(TAG, " file=" + scanFile);
5954                    Slog.w(TAG, "*************************************************");
5955                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5956                            "Core android package being redefined.  Skipping.");
5957                }
5958
5959                // Set up information for our fall-back user intent resolution activity.
5960                mPlatformPackage = pkg;
5961                pkg.mVersionCode = mSdkVersion;
5962                mAndroidApplication = pkg.applicationInfo;
5963
5964                if (!mResolverReplaced) {
5965                    mResolveActivity.applicationInfo = mAndroidApplication;
5966                    mResolveActivity.name = ResolverActivity.class.getName();
5967                    mResolveActivity.packageName = mAndroidApplication.packageName;
5968                    mResolveActivity.processName = "system:ui";
5969                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5970                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5971                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5972                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5973                    mResolveActivity.exported = true;
5974                    mResolveActivity.enabled = true;
5975                    mResolveInfo.activityInfo = mResolveActivity;
5976                    mResolveInfo.priority = 0;
5977                    mResolveInfo.preferredOrder = 0;
5978                    mResolveInfo.match = 0;
5979                    mResolveComponentName = new ComponentName(
5980                            mAndroidApplication.packageName, mResolveActivity.name);
5981                }
5982            }
5983        }
5984
5985        if (DEBUG_PACKAGE_SCANNING) {
5986            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5987                Log.d(TAG, "Scanning package " + pkg.packageName);
5988        }
5989
5990        if (mPackages.containsKey(pkg.packageName)
5991                || mSharedLibraries.containsKey(pkg.packageName)) {
5992            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5993                    "Application package " + pkg.packageName
5994                    + " already installed.  Skipping duplicate.");
5995        }
5996
5997        // If we're only installing presumed-existing packages, require that the
5998        // scanned APK is both already known and at the path previously established
5999        // for it.  Previously unknown packages we pick up normally, but if we have an
6000        // a priori expectation about this package's install presence, enforce it.
6001        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6002            PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6003            if (known != null) {
6004                if (DEBUG_PACKAGE_SCANNING) {
6005                    Log.d(TAG, "Examining " + pkg.codePath
6006                            + " and requiring known paths " + known.codePathString
6007                            + " & " + known.resourcePathString);
6008                }
6009                if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6010                        || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6011                    throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6012                            "Application package " + pkg.packageName
6013                            + " found at " + pkg.applicationInfo.getCodePath()
6014                            + " but expected at " + known.codePathString + "; ignoring.");
6015                }
6016            }
6017        }
6018
6019        // Initialize package source and resource directories
6020        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6021        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6022
6023        SharedUserSetting suid = null;
6024        PackageSetting pkgSetting = null;
6025
6026        if (!isSystemApp(pkg)) {
6027            // Only system apps can use these features.
6028            pkg.mOriginalPackages = null;
6029            pkg.mRealPackage = null;
6030            pkg.mAdoptPermissions = null;
6031        }
6032
6033        // writer
6034        synchronized (mPackages) {
6035            if (pkg.mSharedUserId != null) {
6036                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6037                if (suid == null) {
6038                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6039                            "Creating application package " + pkg.packageName
6040                            + " for shared user failed");
6041                }
6042                if (DEBUG_PACKAGE_SCANNING) {
6043                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6044                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6045                                + "): packages=" + suid.packages);
6046                }
6047            }
6048
6049            // Check if we are renaming from an original package name.
6050            PackageSetting origPackage = null;
6051            String realName = null;
6052            if (pkg.mOriginalPackages != null) {
6053                // This package may need to be renamed to a previously
6054                // installed name.  Let's check on that...
6055                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6056                if (pkg.mOriginalPackages.contains(renamed)) {
6057                    // This package had originally been installed as the
6058                    // original name, and we have already taken care of
6059                    // transitioning to the new one.  Just update the new
6060                    // one to continue using the old name.
6061                    realName = pkg.mRealPackage;
6062                    if (!pkg.packageName.equals(renamed)) {
6063                        // Callers into this function may have already taken
6064                        // care of renaming the package; only do it here if
6065                        // it is not already done.
6066                        pkg.setPackageName(renamed);
6067                    }
6068
6069                } else {
6070                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6071                        if ((origPackage = mSettings.peekPackageLPr(
6072                                pkg.mOriginalPackages.get(i))) != null) {
6073                            // We do have the package already installed under its
6074                            // original name...  should we use it?
6075                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6076                                // New package is not compatible with original.
6077                                origPackage = null;
6078                                continue;
6079                            } else if (origPackage.sharedUser != null) {
6080                                // Make sure uid is compatible between packages.
6081                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6082                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6083                                            + " to " + pkg.packageName + ": old uid "
6084                                            + origPackage.sharedUser.name
6085                                            + " differs from " + pkg.mSharedUserId);
6086                                    origPackage = null;
6087                                    continue;
6088                                }
6089                            } else {
6090                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6091                                        + pkg.packageName + " to old name " + origPackage.name);
6092                            }
6093                            break;
6094                        }
6095                    }
6096                }
6097            }
6098
6099            if (mTransferedPackages.contains(pkg.packageName)) {
6100                Slog.w(TAG, "Package " + pkg.packageName
6101                        + " was transferred to another, but its .apk remains");
6102            }
6103
6104            // Just create the setting, don't add it yet. For already existing packages
6105            // the PkgSetting exists already and doesn't have to be created.
6106            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6107                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6108                    pkg.applicationInfo.primaryCpuAbi,
6109                    pkg.applicationInfo.secondaryCpuAbi,
6110                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6111                    user, false);
6112            if (pkgSetting == null) {
6113                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6114                        "Creating application package " + pkg.packageName + " failed");
6115            }
6116
6117            if (pkgSetting.origPackage != null) {
6118                // If we are first transitioning from an original package,
6119                // fix up the new package's name now.  We need to do this after
6120                // looking up the package under its new name, so getPackageLP
6121                // can take care of fiddling things correctly.
6122                pkg.setPackageName(origPackage.name);
6123
6124                // File a report about this.
6125                String msg = "New package " + pkgSetting.realName
6126                        + " renamed to replace old package " + pkgSetting.name;
6127                reportSettingsProblem(Log.WARN, msg);
6128
6129                // Make a note of it.
6130                mTransferedPackages.add(origPackage.name);
6131
6132                // No longer need to retain this.
6133                pkgSetting.origPackage = null;
6134            }
6135
6136            if (realName != null) {
6137                // Make a note of it.
6138                mTransferedPackages.add(pkg.packageName);
6139            }
6140
6141            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6142                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6143            }
6144
6145            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6146                // Check all shared libraries and map to their actual file path.
6147                // We only do this here for apps not on a system dir, because those
6148                // are the only ones that can fail an install due to this.  We
6149                // will take care of the system apps by updating all of their
6150                // library paths after the scan is done.
6151                updateSharedLibrariesLPw(pkg, null);
6152            }
6153
6154            if (mFoundPolicyFile) {
6155                SELinuxMMAC.assignSeinfoValue(pkg);
6156            }
6157
6158            pkg.applicationInfo.uid = pkgSetting.appId;
6159            pkg.mExtras = pkgSetting;
6160            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6161                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6162                    // We just determined the app is signed correctly, so bring
6163                    // over the latest parsed certs.
6164                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6165                } else {
6166                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6167                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6168                                "Package " + pkg.packageName + " upgrade keys do not match the "
6169                                + "previously installed version");
6170                    } else {
6171                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6172                        String msg = "System package " + pkg.packageName
6173                            + " signature changed; retaining data.";
6174                        reportSettingsProblem(Log.WARN, msg);
6175                    }
6176                }
6177            } else {
6178                try {
6179                    verifySignaturesLP(pkgSetting, pkg);
6180                    // We just determined the app is signed correctly, so bring
6181                    // over the latest parsed certs.
6182                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6183                } catch (PackageManagerException e) {
6184                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6185                        throw e;
6186                    }
6187                    // The signature has changed, but this package is in the system
6188                    // image...  let's recover!
6189                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6190                    // However...  if this package is part of a shared user, but it
6191                    // doesn't match the signature of the shared user, let's fail.
6192                    // What this means is that you can't change the signatures
6193                    // associated with an overall shared user, which doesn't seem all
6194                    // that unreasonable.
6195                    if (pkgSetting.sharedUser != null) {
6196                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6197                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6198                            throw new PackageManagerException(
6199                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6200                                            "Signature mismatch for shared user : "
6201                                            + pkgSetting.sharedUser);
6202                        }
6203                    }
6204                    // File a report about this.
6205                    String msg = "System package " + pkg.packageName
6206                        + " signature changed; retaining data.";
6207                    reportSettingsProblem(Log.WARN, msg);
6208                }
6209            }
6210            // Verify that this new package doesn't have any content providers
6211            // that conflict with existing packages.  Only do this if the
6212            // package isn't already installed, since we don't want to break
6213            // things that are installed.
6214            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6215                final int N = pkg.providers.size();
6216                int i;
6217                for (i=0; i<N; i++) {
6218                    PackageParser.Provider p = pkg.providers.get(i);
6219                    if (p.info.authority != null) {
6220                        String names[] = p.info.authority.split(";");
6221                        for (int j = 0; j < names.length; j++) {
6222                            if (mProvidersByAuthority.containsKey(names[j])) {
6223                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6224                                final String otherPackageName =
6225                                        ((other != null && other.getComponentName() != null) ?
6226                                                other.getComponentName().getPackageName() : "?");
6227                                throw new PackageManagerException(
6228                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6229                                                "Can't install because provider name " + names[j]
6230                                                + " (in package " + pkg.applicationInfo.packageName
6231                                                + ") is already used by " + otherPackageName);
6232                            }
6233                        }
6234                    }
6235                }
6236            }
6237
6238            if (pkg.mAdoptPermissions != null) {
6239                // This package wants to adopt ownership of permissions from
6240                // another package.
6241                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6242                    final String origName = pkg.mAdoptPermissions.get(i);
6243                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6244                    if (orig != null) {
6245                        if (verifyPackageUpdateLPr(orig, pkg)) {
6246                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6247                                    + pkg.packageName);
6248                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6249                        }
6250                    }
6251                }
6252            }
6253        }
6254
6255        final String pkgName = pkg.packageName;
6256
6257        final long scanFileTime = scanFile.lastModified();
6258        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6259        pkg.applicationInfo.processName = fixProcessName(
6260                pkg.applicationInfo.packageName,
6261                pkg.applicationInfo.processName,
6262                pkg.applicationInfo.uid);
6263
6264        File dataPath;
6265        if (mPlatformPackage == pkg) {
6266            // The system package is special.
6267            dataPath = new File(Environment.getDataDirectory(), "system");
6268
6269            pkg.applicationInfo.dataDir = dataPath.getPath();
6270
6271        } else {
6272            // This is a normal package, need to make its data directory.
6273            dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName,
6274                    UserHandle.USER_OWNER);
6275
6276            boolean uidError = false;
6277            if (dataPath.exists()) {
6278                int currentUid = 0;
6279                try {
6280                    StructStat stat = Os.stat(dataPath.getPath());
6281                    currentUid = stat.st_uid;
6282                } catch (ErrnoException e) {
6283                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6284                }
6285
6286                // If we have mismatched owners for the data path, we have a problem.
6287                if (currentUid != pkg.applicationInfo.uid) {
6288                    boolean recovered = false;
6289                    if (currentUid == 0) {
6290                        // The directory somehow became owned by root.  Wow.
6291                        // This is probably because the system was stopped while
6292                        // installd was in the middle of messing with its libs
6293                        // directory.  Ask installd to fix that.
6294                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6295                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6296                        if (ret >= 0) {
6297                            recovered = true;
6298                            String msg = "Package " + pkg.packageName
6299                                    + " unexpectedly changed to uid 0; recovered to " +
6300                                    + pkg.applicationInfo.uid;
6301                            reportSettingsProblem(Log.WARN, msg);
6302                        }
6303                    }
6304                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6305                            || (scanFlags&SCAN_BOOTING) != 0)) {
6306                        // If this is a system app, we can at least delete its
6307                        // current data so the application will still work.
6308                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6309                        if (ret >= 0) {
6310                            // TODO: Kill the processes first
6311                            // Old data gone!
6312                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6313                                    ? "System package " : "Third party package ";
6314                            String msg = prefix + pkg.packageName
6315                                    + " has changed from uid: "
6316                                    + currentUid + " to "
6317                                    + pkg.applicationInfo.uid + "; old data erased";
6318                            reportSettingsProblem(Log.WARN, msg);
6319                            recovered = true;
6320
6321                            // And now re-install the app.
6322                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6323                                    pkg.applicationInfo.seinfo);
6324                            if (ret == -1) {
6325                                // Ack should not happen!
6326                                msg = prefix + pkg.packageName
6327                                        + " could not have data directory re-created after delete.";
6328                                reportSettingsProblem(Log.WARN, msg);
6329                                throw new PackageManagerException(
6330                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6331                            }
6332                        }
6333                        if (!recovered) {
6334                            mHasSystemUidErrors = true;
6335                        }
6336                    } else if (!recovered) {
6337                        // If we allow this install to proceed, we will be broken.
6338                        // Abort, abort!
6339                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6340                                "scanPackageLI");
6341                    }
6342                    if (!recovered) {
6343                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6344                            + pkg.applicationInfo.uid + "/fs_"
6345                            + currentUid;
6346                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6347                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6348                        String msg = "Package " + pkg.packageName
6349                                + " has mismatched uid: "
6350                                + currentUid + " on disk, "
6351                                + pkg.applicationInfo.uid + " in settings";
6352                        // writer
6353                        synchronized (mPackages) {
6354                            mSettings.mReadMessages.append(msg);
6355                            mSettings.mReadMessages.append('\n');
6356                            uidError = true;
6357                            if (!pkgSetting.uidError) {
6358                                reportSettingsProblem(Log.ERROR, msg);
6359                            }
6360                        }
6361                    }
6362                }
6363                pkg.applicationInfo.dataDir = dataPath.getPath();
6364                if (mShouldRestoreconData) {
6365                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6366                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6367                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6368                }
6369            } else {
6370                if (DEBUG_PACKAGE_SCANNING) {
6371                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6372                        Log.v(TAG, "Want this data dir: " + dataPath);
6373                }
6374                //invoke installer to do the actual installation
6375                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6376                        pkg.applicationInfo.seinfo);
6377                if (ret < 0) {
6378                    // Error from installer
6379                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6380                            "Unable to create data dirs [errorCode=" + ret + "]");
6381                }
6382
6383                if (dataPath.exists()) {
6384                    pkg.applicationInfo.dataDir = dataPath.getPath();
6385                } else {
6386                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6387                    pkg.applicationInfo.dataDir = null;
6388                }
6389            }
6390
6391            pkgSetting.uidError = uidError;
6392        }
6393
6394        final String path = scanFile.getPath();
6395        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6396
6397        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6398            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6399
6400            // Some system apps still use directory structure for native libraries
6401            // in which case we might end up not detecting abi solely based on apk
6402            // structure. Try to detect abi based on directory structure.
6403            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6404                    pkg.applicationInfo.primaryCpuAbi == null) {
6405                setBundledAppAbisAndRoots(pkg, pkgSetting);
6406                setNativeLibraryPaths(pkg);
6407            }
6408
6409        } else {
6410            if ((scanFlags & SCAN_MOVE) != 0) {
6411                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6412                // but we already have this packages package info in the PackageSetting. We just
6413                // use that and derive the native library path based on the new codepath.
6414                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6415                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6416            }
6417
6418            // Set native library paths again. For moves, the path will be updated based on the
6419            // ABIs we've determined above. For non-moves, the path will be updated based on the
6420            // ABIs we determined during compilation, but the path will depend on the final
6421            // package path (after the rename away from the stage path).
6422            setNativeLibraryPaths(pkg);
6423        }
6424
6425        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6426        final int[] userIds = sUserManager.getUserIds();
6427        synchronized (mInstallLock) {
6428            // Create a native library symlink only if we have native libraries
6429            // and if the native libraries are 32 bit libraries. We do not provide
6430            // this symlink for 64 bit libraries.
6431            if (pkg.applicationInfo.primaryCpuAbi != null &&
6432                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6433                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6434                for (int userId : userIds) {
6435                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6436                            nativeLibPath, userId) < 0) {
6437                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6438                                "Failed linking native library dir (user=" + userId + ")");
6439                    }
6440                }
6441            }
6442        }
6443
6444        // This is a special case for the "system" package, where the ABI is
6445        // dictated by the zygote configuration (and init.rc). We should keep track
6446        // of this ABI so that we can deal with "normal" applications that run under
6447        // the same UID correctly.
6448        if (mPlatformPackage == pkg) {
6449            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6450                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6451        }
6452
6453        // If there's a mismatch between the abi-override in the package setting
6454        // and the abiOverride specified for the install. Warn about this because we
6455        // would've already compiled the app without taking the package setting into
6456        // account.
6457        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
6458            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
6459                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
6460                        " for package: " + pkg.packageName);
6461            }
6462        }
6463
6464        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6465        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6466        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6467
6468        // Copy the derived override back to the parsed package, so that we can
6469        // update the package settings accordingly.
6470        pkg.cpuAbiOverride = cpuAbiOverride;
6471
6472        if (DEBUG_ABI_SELECTION) {
6473            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6474                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6475                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6476        }
6477
6478        // Push the derived path down into PackageSettings so we know what to
6479        // clean up at uninstall time.
6480        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6481
6482        if (DEBUG_ABI_SELECTION) {
6483            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6484                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6485                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6486        }
6487
6488        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6489            // We don't do this here during boot because we can do it all
6490            // at once after scanning all existing packages.
6491            //
6492            // We also do this *before* we perform dexopt on this package, so that
6493            // we can avoid redundant dexopts, and also to make sure we've got the
6494            // code and package path correct.
6495            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
6496                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
6497        }
6498
6499        if ((scanFlags & SCAN_NO_DEX) == 0) {
6500            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
6501                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
6502            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6503                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
6504            }
6505        }
6506        if (mFactoryTest && pkg.requestedPermissions.contains(
6507                android.Manifest.permission.FACTORY_TEST)) {
6508            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
6509        }
6510
6511        ArrayList<PackageParser.Package> clientLibPkgs = null;
6512
6513        // writer
6514        synchronized (mPackages) {
6515            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6516                // Only system apps can add new shared libraries.
6517                if (pkg.libraryNames != null) {
6518                    for (int i=0; i<pkg.libraryNames.size(); i++) {
6519                        String name = pkg.libraryNames.get(i);
6520                        boolean allowed = false;
6521                        if (pkg.isUpdatedSystemApp()) {
6522                            // New library entries can only be added through the
6523                            // system image.  This is important to get rid of a lot
6524                            // of nasty edge cases: for example if we allowed a non-
6525                            // system update of the app to add a library, then uninstalling
6526                            // the update would make the library go away, and assumptions
6527                            // we made such as through app install filtering would now
6528                            // have allowed apps on the device which aren't compatible
6529                            // with it.  Better to just have the restriction here, be
6530                            // conservative, and create many fewer cases that can negatively
6531                            // impact the user experience.
6532                            final PackageSetting sysPs = mSettings
6533                                    .getDisabledSystemPkgLPr(pkg.packageName);
6534                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
6535                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
6536                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
6537                                        allowed = true;
6538                                        allowed = true;
6539                                        break;
6540                                    }
6541                                }
6542                            }
6543                        } else {
6544                            allowed = true;
6545                        }
6546                        if (allowed) {
6547                            if (!mSharedLibraries.containsKey(name)) {
6548                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
6549                            } else if (!name.equals(pkg.packageName)) {
6550                                Slog.w(TAG, "Package " + pkg.packageName + " library "
6551                                        + name + " already exists; skipping");
6552                            }
6553                        } else {
6554                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
6555                                    + name + " that is not declared on system image; skipping");
6556                        }
6557                    }
6558                    if ((scanFlags&SCAN_BOOTING) == 0) {
6559                        // If we are not booting, we need to update any applications
6560                        // that are clients of our shared library.  If we are booting,
6561                        // this will all be done once the scan is complete.
6562                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
6563                    }
6564                }
6565            }
6566        }
6567
6568        // We also need to dexopt any apps that are dependent on this library.  Note that
6569        // if these fail, we should abort the install since installing the library will
6570        // result in some apps being broken.
6571        if (clientLibPkgs != null) {
6572            if ((scanFlags & SCAN_NO_DEX) == 0) {
6573                for (int i = 0; i < clientLibPkgs.size(); i++) {
6574                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
6575                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
6576                            null /* instruction sets */, forceDex,
6577                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
6578                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6579                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
6580                                "scanPackageLI failed to dexopt clientLibPkgs");
6581                    }
6582                }
6583            }
6584        }
6585
6586        // Also need to kill any apps that are dependent on the library.
6587        if (clientLibPkgs != null) {
6588            for (int i=0; i<clientLibPkgs.size(); i++) {
6589                PackageParser.Package clientPkg = clientLibPkgs.get(i);
6590                killApplication(clientPkg.applicationInfo.packageName,
6591                        clientPkg.applicationInfo.uid, "update lib");
6592            }
6593        }
6594
6595        // Make sure we're not adding any bogus keyset info
6596        KeySetManagerService ksms = mSettings.mKeySetManagerService;
6597        ksms.assertScannedPackageValid(pkg);
6598
6599        // writer
6600        synchronized (mPackages) {
6601            // We don't expect installation to fail beyond this point
6602
6603            // Add the new setting to mSettings
6604            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
6605            // Add the new setting to mPackages
6606            mPackages.put(pkg.applicationInfo.packageName, pkg);
6607            // Make sure we don't accidentally delete its data.
6608            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
6609            while (iter.hasNext()) {
6610                PackageCleanItem item = iter.next();
6611                if (pkgName.equals(item.packageName)) {
6612                    iter.remove();
6613                }
6614            }
6615
6616            // Take care of first install / last update times.
6617            if (currentTime != 0) {
6618                if (pkgSetting.firstInstallTime == 0) {
6619                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
6620                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
6621                    pkgSetting.lastUpdateTime = currentTime;
6622                }
6623            } else if (pkgSetting.firstInstallTime == 0) {
6624                // We need *something*.  Take time time stamp of the file.
6625                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
6626            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
6627                if (scanFileTime != pkgSetting.timeStamp) {
6628                    // A package on the system image has changed; consider this
6629                    // to be an update.
6630                    pkgSetting.lastUpdateTime = scanFileTime;
6631                }
6632            }
6633
6634            // Add the package's KeySets to the global KeySetManagerService
6635            ksms.addScannedPackageLPw(pkg);
6636
6637            int N = pkg.providers.size();
6638            StringBuilder r = null;
6639            int i;
6640            for (i=0; i<N; i++) {
6641                PackageParser.Provider p = pkg.providers.get(i);
6642                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
6643                        p.info.processName, pkg.applicationInfo.uid);
6644                mProviders.addProvider(p);
6645                p.syncable = p.info.isSyncable;
6646                if (p.info.authority != null) {
6647                    String names[] = p.info.authority.split(";");
6648                    p.info.authority = null;
6649                    for (int j = 0; j < names.length; j++) {
6650                        if (j == 1 && p.syncable) {
6651                            // We only want the first authority for a provider to possibly be
6652                            // syncable, so if we already added this provider using a different
6653                            // authority clear the syncable flag. We copy the provider before
6654                            // changing it because the mProviders object contains a reference
6655                            // to a provider that we don't want to change.
6656                            // Only do this for the second authority since the resulting provider
6657                            // object can be the same for all future authorities for this provider.
6658                            p = new PackageParser.Provider(p);
6659                            p.syncable = false;
6660                        }
6661                        if (!mProvidersByAuthority.containsKey(names[j])) {
6662                            mProvidersByAuthority.put(names[j], p);
6663                            if (p.info.authority == null) {
6664                                p.info.authority = names[j];
6665                            } else {
6666                                p.info.authority = p.info.authority + ";" + names[j];
6667                            }
6668                            if (DEBUG_PACKAGE_SCANNING) {
6669                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6670                                    Log.d(TAG, "Registered content provider: " + names[j]
6671                                            + ", className = " + p.info.name + ", isSyncable = "
6672                                            + p.info.isSyncable);
6673                            }
6674                        } else {
6675                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6676                            Slog.w(TAG, "Skipping provider name " + names[j] +
6677                                    " (in package " + pkg.applicationInfo.packageName +
6678                                    "): name already used by "
6679                                    + ((other != null && other.getComponentName() != null)
6680                                            ? other.getComponentName().getPackageName() : "?"));
6681                        }
6682                    }
6683                }
6684                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6685                    if (r == null) {
6686                        r = new StringBuilder(256);
6687                    } else {
6688                        r.append(' ');
6689                    }
6690                    r.append(p.info.name);
6691                }
6692            }
6693            if (r != null) {
6694                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
6695            }
6696
6697            N = pkg.services.size();
6698            r = null;
6699            for (i=0; i<N; i++) {
6700                PackageParser.Service s = pkg.services.get(i);
6701                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
6702                        s.info.processName, pkg.applicationInfo.uid);
6703                mServices.addService(s);
6704                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6705                    if (r == null) {
6706                        r = new StringBuilder(256);
6707                    } else {
6708                        r.append(' ');
6709                    }
6710                    r.append(s.info.name);
6711                }
6712            }
6713            if (r != null) {
6714                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
6715            }
6716
6717            N = pkg.receivers.size();
6718            r = null;
6719            for (i=0; i<N; i++) {
6720                PackageParser.Activity a = pkg.receivers.get(i);
6721                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6722                        a.info.processName, pkg.applicationInfo.uid);
6723                mReceivers.addActivity(a, "receiver");
6724                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6725                    if (r == null) {
6726                        r = new StringBuilder(256);
6727                    } else {
6728                        r.append(' ');
6729                    }
6730                    r.append(a.info.name);
6731                }
6732            }
6733            if (r != null) {
6734                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
6735            }
6736
6737            N = pkg.activities.size();
6738            r = null;
6739            for (i=0; i<N; i++) {
6740                PackageParser.Activity a = pkg.activities.get(i);
6741                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6742                        a.info.processName, pkg.applicationInfo.uid);
6743                mActivities.addActivity(a, "activity");
6744                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6745                    if (r == null) {
6746                        r = new StringBuilder(256);
6747                    } else {
6748                        r.append(' ');
6749                    }
6750                    r.append(a.info.name);
6751                }
6752            }
6753            if (r != null) {
6754                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
6755            }
6756
6757            N = pkg.permissionGroups.size();
6758            r = null;
6759            for (i=0; i<N; i++) {
6760                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
6761                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
6762                if (cur == null) {
6763                    mPermissionGroups.put(pg.info.name, pg);
6764                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6765                        if (r == null) {
6766                            r = new StringBuilder(256);
6767                        } else {
6768                            r.append(' ');
6769                        }
6770                        r.append(pg.info.name);
6771                    }
6772                } else {
6773                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
6774                            + pg.info.packageName + " ignored: original from "
6775                            + cur.info.packageName);
6776                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6777                        if (r == null) {
6778                            r = new StringBuilder(256);
6779                        } else {
6780                            r.append(' ');
6781                        }
6782                        r.append("DUP:");
6783                        r.append(pg.info.name);
6784                    }
6785                }
6786            }
6787            if (r != null) {
6788                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6789            }
6790
6791            N = pkg.permissions.size();
6792            r = null;
6793            for (i=0; i<N; i++) {
6794                PackageParser.Permission p = pkg.permissions.get(i);
6795
6796                // Now that permission groups have a special meaning, we ignore permission
6797                // groups for legacy apps to prevent unexpected behavior. In particular,
6798                // permissions for one app being granted to someone just becuase they happen
6799                // to be in a group defined by another app (before this had no implications).
6800                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
6801                    p.group = mPermissionGroups.get(p.info.group);
6802                    // Warn for a permission in an unknown group.
6803                    if (p.info.group != null && p.group == null) {
6804                        Slog.w(TAG, "Permission " + p.info.name + " from package "
6805                                + p.info.packageName + " in an unknown group " + p.info.group);
6806                    }
6807                }
6808
6809                ArrayMap<String, BasePermission> permissionMap =
6810                        p.tree ? mSettings.mPermissionTrees
6811                                : mSettings.mPermissions;
6812                BasePermission bp = permissionMap.get(p.info.name);
6813
6814                // Allow system apps to redefine non-system permissions
6815                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
6816                    final boolean currentOwnerIsSystem = (bp.perm != null
6817                            && isSystemApp(bp.perm.owner));
6818                    if (isSystemApp(p.owner)) {
6819                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
6820                            // It's a built-in permission and no owner, take ownership now
6821                            bp.packageSetting = pkgSetting;
6822                            bp.perm = p;
6823                            bp.uid = pkg.applicationInfo.uid;
6824                            bp.sourcePackage = p.info.packageName;
6825                        } else if (!currentOwnerIsSystem) {
6826                            String msg = "New decl " + p.owner + " of permission  "
6827                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
6828                            reportSettingsProblem(Log.WARN, msg);
6829                            bp = null;
6830                        }
6831                    }
6832                }
6833
6834                if (bp == null) {
6835                    bp = new BasePermission(p.info.name, p.info.packageName,
6836                            BasePermission.TYPE_NORMAL);
6837                    permissionMap.put(p.info.name, bp);
6838                }
6839
6840                if (bp.perm == null) {
6841                    if (bp.sourcePackage == null
6842                            || bp.sourcePackage.equals(p.info.packageName)) {
6843                        BasePermission tree = findPermissionTreeLP(p.info.name);
6844                        if (tree == null
6845                                || tree.sourcePackage.equals(p.info.packageName)) {
6846                            bp.packageSetting = pkgSetting;
6847                            bp.perm = p;
6848                            bp.uid = pkg.applicationInfo.uid;
6849                            bp.sourcePackage = p.info.packageName;
6850                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6851                                if (r == null) {
6852                                    r = new StringBuilder(256);
6853                                } else {
6854                                    r.append(' ');
6855                                }
6856                                r.append(p.info.name);
6857                            }
6858                        } else {
6859                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6860                                    + p.info.packageName + " ignored: base tree "
6861                                    + tree.name + " is from package "
6862                                    + tree.sourcePackage);
6863                        }
6864                    } else {
6865                        Slog.w(TAG, "Permission " + p.info.name + " from package "
6866                                + p.info.packageName + " ignored: original from "
6867                                + bp.sourcePackage);
6868                    }
6869                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6870                    if (r == null) {
6871                        r = new StringBuilder(256);
6872                    } else {
6873                        r.append(' ');
6874                    }
6875                    r.append("DUP:");
6876                    r.append(p.info.name);
6877                }
6878                if (bp.perm == p) {
6879                    bp.protectionLevel = p.info.protectionLevel;
6880                }
6881            }
6882
6883            if (r != null) {
6884                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6885            }
6886
6887            N = pkg.instrumentation.size();
6888            r = null;
6889            for (i=0; i<N; i++) {
6890                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6891                a.info.packageName = pkg.applicationInfo.packageName;
6892                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6893                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6894                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6895                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6896                a.info.dataDir = pkg.applicationInfo.dataDir;
6897
6898                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6899                // need other information about the application, like the ABI and what not ?
6900                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6901                mInstrumentation.put(a.getComponentName(), a);
6902                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6903                    if (r == null) {
6904                        r = new StringBuilder(256);
6905                    } else {
6906                        r.append(' ');
6907                    }
6908                    r.append(a.info.name);
6909                }
6910            }
6911            if (r != null) {
6912                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6913            }
6914
6915            if (pkg.protectedBroadcasts != null) {
6916                N = pkg.protectedBroadcasts.size();
6917                for (i=0; i<N; i++) {
6918                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6919                }
6920            }
6921
6922            pkgSetting.setTimeStamp(scanFileTime);
6923
6924            // Create idmap files for pairs of (packages, overlay packages).
6925            // Note: "android", ie framework-res.apk, is handled by native layers.
6926            if (pkg.mOverlayTarget != null) {
6927                // This is an overlay package.
6928                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6929                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6930                        mOverlays.put(pkg.mOverlayTarget,
6931                                new ArrayMap<String, PackageParser.Package>());
6932                    }
6933                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6934                    map.put(pkg.packageName, pkg);
6935                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6936                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6937                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6938                                "scanPackageLI failed to createIdmap");
6939                    }
6940                }
6941            } else if (mOverlays.containsKey(pkg.packageName) &&
6942                    !pkg.packageName.equals("android")) {
6943                // This is a regular package, with one or more known overlay packages.
6944                createIdmapsForPackageLI(pkg);
6945            }
6946        }
6947
6948        return pkg;
6949    }
6950
6951    /**
6952     * Derive the ABI of a non-system package located at {@code scanFile}. This information
6953     * is derived purely on the basis of the contents of {@code scanFile} and
6954     * {@code cpuAbiOverride}.
6955     *
6956     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
6957     */
6958    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
6959                                 String cpuAbiOverride, boolean extractLibs)
6960            throws PackageManagerException {
6961        // TODO: We can probably be smarter about this stuff. For installed apps,
6962        // we can calculate this information at install time once and for all. For
6963        // system apps, we can probably assume that this information doesn't change
6964        // after the first boot scan. As things stand, we do lots of unnecessary work.
6965
6966        // Give ourselves some initial paths; we'll come back for another
6967        // pass once we've determined ABI below.
6968        setNativeLibraryPaths(pkg);
6969
6970        // We would never need to extract libs for forward-locked and external packages,
6971        // since the container service will do it for us. We shouldn't attempt to
6972        // extract libs from system app when it was not updated.
6973        if (pkg.isForwardLocked() || isExternal(pkg) ||
6974            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
6975            extractLibs = false;
6976        }
6977
6978        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
6979        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
6980
6981        NativeLibraryHelper.Handle handle = null;
6982        try {
6983            handle = NativeLibraryHelper.Handle.create(scanFile);
6984            // TODO(multiArch): This can be null for apps that didn't go through the
6985            // usual installation process. We can calculate it again, like we
6986            // do during install time.
6987            //
6988            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
6989            // unnecessary.
6990            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
6991
6992            // Null out the abis so that they can be recalculated.
6993            pkg.applicationInfo.primaryCpuAbi = null;
6994            pkg.applicationInfo.secondaryCpuAbi = null;
6995            if (isMultiArch(pkg.applicationInfo)) {
6996                // Warn if we've set an abiOverride for multi-lib packages..
6997                // By definition, we need to copy both 32 and 64 bit libraries for
6998                // such packages.
6999                if (pkg.cpuAbiOverride != null
7000                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7001                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7002                }
7003
7004                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7005                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7006                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7007                    if (extractLibs) {
7008                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7009                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7010                                useIsaSpecificSubdirs);
7011                    } else {
7012                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7013                    }
7014                }
7015
7016                maybeThrowExceptionForMultiArchCopy(
7017                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7018
7019                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7020                    if (extractLibs) {
7021                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7022                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7023                                useIsaSpecificSubdirs);
7024                    } else {
7025                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7026                    }
7027                }
7028
7029                maybeThrowExceptionForMultiArchCopy(
7030                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7031
7032                if (abi64 >= 0) {
7033                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7034                }
7035
7036                if (abi32 >= 0) {
7037                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7038                    if (abi64 >= 0) {
7039                        pkg.applicationInfo.secondaryCpuAbi = abi;
7040                    } else {
7041                        pkg.applicationInfo.primaryCpuAbi = abi;
7042                    }
7043                }
7044            } else {
7045                String[] abiList = (cpuAbiOverride != null) ?
7046                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7047
7048                // Enable gross and lame hacks for apps that are built with old
7049                // SDK tools. We must scan their APKs for renderscript bitcode and
7050                // not launch them if it's present. Don't bother checking on devices
7051                // that don't have 64 bit support.
7052                boolean needsRenderScriptOverride = false;
7053                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7054                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7055                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7056                    needsRenderScriptOverride = true;
7057                }
7058
7059                final int copyRet;
7060                if (extractLibs) {
7061                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7062                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7063                } else {
7064                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7065                }
7066
7067                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7068                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7069                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7070                }
7071
7072                if (copyRet >= 0) {
7073                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7074                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7075                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7076                } else if (needsRenderScriptOverride) {
7077                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7078                }
7079            }
7080        } catch (IOException ioe) {
7081            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7082        } finally {
7083            IoUtils.closeQuietly(handle);
7084        }
7085
7086        // Now that we've calculated the ABIs and determined if it's an internal app,
7087        // we will go ahead and populate the nativeLibraryPath.
7088        setNativeLibraryPaths(pkg);
7089    }
7090
7091    /**
7092     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7093     * i.e, so that all packages can be run inside a single process if required.
7094     *
7095     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7096     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7097     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7098     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7099     * updating a package that belongs to a shared user.
7100     *
7101     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7102     * adds unnecessary complexity.
7103     */
7104    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7105            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7106        String requiredInstructionSet = null;
7107        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7108            requiredInstructionSet = VMRuntime.getInstructionSet(
7109                     scannedPackage.applicationInfo.primaryCpuAbi);
7110        }
7111
7112        PackageSetting requirer = null;
7113        for (PackageSetting ps : packagesForUser) {
7114            // If packagesForUser contains scannedPackage, we skip it. This will happen
7115            // when scannedPackage is an update of an existing package. Without this check,
7116            // we will never be able to change the ABI of any package belonging to a shared
7117            // user, even if it's compatible with other packages.
7118            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7119                if (ps.primaryCpuAbiString == null) {
7120                    continue;
7121                }
7122
7123                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7124                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7125                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7126                    // this but there's not much we can do.
7127                    String errorMessage = "Instruction set mismatch, "
7128                            + ((requirer == null) ? "[caller]" : requirer)
7129                            + " requires " + requiredInstructionSet + " whereas " + ps
7130                            + " requires " + instructionSet;
7131                    Slog.w(TAG, errorMessage);
7132                }
7133
7134                if (requiredInstructionSet == null) {
7135                    requiredInstructionSet = instructionSet;
7136                    requirer = ps;
7137                }
7138            }
7139        }
7140
7141        if (requiredInstructionSet != null) {
7142            String adjustedAbi;
7143            if (requirer != null) {
7144                // requirer != null implies that either scannedPackage was null or that scannedPackage
7145                // did not require an ABI, in which case we have to adjust scannedPackage to match
7146                // the ABI of the set (which is the same as requirer's ABI)
7147                adjustedAbi = requirer.primaryCpuAbiString;
7148                if (scannedPackage != null) {
7149                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7150                }
7151            } else {
7152                // requirer == null implies that we're updating all ABIs in the set to
7153                // match scannedPackage.
7154                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7155            }
7156
7157            for (PackageSetting ps : packagesForUser) {
7158                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7159                    if (ps.primaryCpuAbiString != null) {
7160                        continue;
7161                    }
7162
7163                    ps.primaryCpuAbiString = adjustedAbi;
7164                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7165                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7166                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7167
7168                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7169                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7170                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7171                            ps.primaryCpuAbiString = null;
7172                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7173                            return;
7174                        } else {
7175                            mInstaller.rmdex(ps.codePathString,
7176                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7177                        }
7178                    }
7179                }
7180            }
7181        }
7182    }
7183
7184    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7185        synchronized (mPackages) {
7186            mResolverReplaced = true;
7187            // Set up information for custom user intent resolution activity.
7188            mResolveActivity.applicationInfo = pkg.applicationInfo;
7189            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7190            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7191            mResolveActivity.processName = pkg.applicationInfo.packageName;
7192            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7193            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7194                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7195            mResolveActivity.theme = 0;
7196            mResolveActivity.exported = true;
7197            mResolveActivity.enabled = true;
7198            mResolveInfo.activityInfo = mResolveActivity;
7199            mResolveInfo.priority = 0;
7200            mResolveInfo.preferredOrder = 0;
7201            mResolveInfo.match = 0;
7202            mResolveComponentName = mCustomResolverComponentName;
7203            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7204                    mResolveComponentName);
7205        }
7206    }
7207
7208    private static String calculateBundledApkRoot(final String codePathString) {
7209        final File codePath = new File(codePathString);
7210        final File codeRoot;
7211        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7212            codeRoot = Environment.getRootDirectory();
7213        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7214            codeRoot = Environment.getOemDirectory();
7215        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7216            codeRoot = Environment.getVendorDirectory();
7217        } else {
7218            // Unrecognized code path; take its top real segment as the apk root:
7219            // e.g. /something/app/blah.apk => /something
7220            try {
7221                File f = codePath.getCanonicalFile();
7222                File parent = f.getParentFile();    // non-null because codePath is a file
7223                File tmp;
7224                while ((tmp = parent.getParentFile()) != null) {
7225                    f = parent;
7226                    parent = tmp;
7227                }
7228                codeRoot = f;
7229                Slog.w(TAG, "Unrecognized code path "
7230                        + codePath + " - using " + codeRoot);
7231            } catch (IOException e) {
7232                // Can't canonicalize the code path -- shenanigans?
7233                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7234                return Environment.getRootDirectory().getPath();
7235            }
7236        }
7237        return codeRoot.getPath();
7238    }
7239
7240    /**
7241     * Derive and set the location of native libraries for the given package,
7242     * which varies depending on where and how the package was installed.
7243     */
7244    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7245        final ApplicationInfo info = pkg.applicationInfo;
7246        final String codePath = pkg.codePath;
7247        final File codeFile = new File(codePath);
7248        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7249        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7250
7251        info.nativeLibraryRootDir = null;
7252        info.nativeLibraryRootRequiresIsa = false;
7253        info.nativeLibraryDir = null;
7254        info.secondaryNativeLibraryDir = null;
7255
7256        if (isApkFile(codeFile)) {
7257            // Monolithic install
7258            if (bundledApp) {
7259                // If "/system/lib64/apkname" exists, assume that is the per-package
7260                // native library directory to use; otherwise use "/system/lib/apkname".
7261                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7262                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7263                        getPrimaryInstructionSet(info));
7264
7265                // This is a bundled system app so choose the path based on the ABI.
7266                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7267                // is just the default path.
7268                final String apkName = deriveCodePathName(codePath);
7269                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7270                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7271                        apkName).getAbsolutePath();
7272
7273                if (info.secondaryCpuAbi != null) {
7274                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7275                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7276                            secondaryLibDir, apkName).getAbsolutePath();
7277                }
7278            } else if (asecApp) {
7279                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7280                        .getAbsolutePath();
7281            } else {
7282                final String apkName = deriveCodePathName(codePath);
7283                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7284                        .getAbsolutePath();
7285            }
7286
7287            info.nativeLibraryRootRequiresIsa = false;
7288            info.nativeLibraryDir = info.nativeLibraryRootDir;
7289        } else {
7290            // Cluster install
7291            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7292            info.nativeLibraryRootRequiresIsa = true;
7293
7294            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7295                    getPrimaryInstructionSet(info)).getAbsolutePath();
7296
7297            if (info.secondaryCpuAbi != null) {
7298                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7299                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7300            }
7301        }
7302    }
7303
7304    /**
7305     * Calculate the abis and roots for a bundled app. These can uniquely
7306     * be determined from the contents of the system partition, i.e whether
7307     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7308     * of this information, and instead assume that the system was built
7309     * sensibly.
7310     */
7311    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7312                                           PackageSetting pkgSetting) {
7313        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7314
7315        // If "/system/lib64/apkname" exists, assume that is the per-package
7316        // native library directory to use; otherwise use "/system/lib/apkname".
7317        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7318        setBundledAppAbi(pkg, apkRoot, apkName);
7319        // pkgSetting might be null during rescan following uninstall of updates
7320        // to a bundled app, so accommodate that possibility.  The settings in
7321        // that case will be established later from the parsed package.
7322        //
7323        // If the settings aren't null, sync them up with what we've just derived.
7324        // note that apkRoot isn't stored in the package settings.
7325        if (pkgSetting != null) {
7326            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7327            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7328        }
7329    }
7330
7331    /**
7332     * Deduces the ABI of a bundled app and sets the relevant fields on the
7333     * parsed pkg object.
7334     *
7335     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7336     *        under which system libraries are installed.
7337     * @param apkName the name of the installed package.
7338     */
7339    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7340        final File codeFile = new File(pkg.codePath);
7341
7342        final boolean has64BitLibs;
7343        final boolean has32BitLibs;
7344        if (isApkFile(codeFile)) {
7345            // Monolithic install
7346            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7347            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7348        } else {
7349            // Cluster install
7350            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7351            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7352                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7353                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7354                has64BitLibs = (new File(rootDir, isa)).exists();
7355            } else {
7356                has64BitLibs = false;
7357            }
7358            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7359                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7360                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7361                has32BitLibs = (new File(rootDir, isa)).exists();
7362            } else {
7363                has32BitLibs = false;
7364            }
7365        }
7366
7367        if (has64BitLibs && !has32BitLibs) {
7368            // The package has 64 bit libs, but not 32 bit libs. Its primary
7369            // ABI should be 64 bit. We can safely assume here that the bundled
7370            // native libraries correspond to the most preferred ABI in the list.
7371
7372            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7373            pkg.applicationInfo.secondaryCpuAbi = null;
7374        } else if (has32BitLibs && !has64BitLibs) {
7375            // The package has 32 bit libs but not 64 bit libs. Its primary
7376            // ABI should be 32 bit.
7377
7378            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7379            pkg.applicationInfo.secondaryCpuAbi = null;
7380        } else if (has32BitLibs && has64BitLibs) {
7381            // The application has both 64 and 32 bit bundled libraries. We check
7382            // here that the app declares multiArch support, and warn if it doesn't.
7383            //
7384            // We will be lenient here and record both ABIs. The primary will be the
7385            // ABI that's higher on the list, i.e, a device that's configured to prefer
7386            // 64 bit apps will see a 64 bit primary ABI,
7387
7388            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7389                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7390            }
7391
7392            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7393                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7394                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7395            } else {
7396                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7397                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7398            }
7399        } else {
7400            pkg.applicationInfo.primaryCpuAbi = null;
7401            pkg.applicationInfo.secondaryCpuAbi = null;
7402        }
7403    }
7404
7405    private void killApplication(String pkgName, int appId, String reason) {
7406        // Request the ActivityManager to kill the process(only for existing packages)
7407        // so that we do not end up in a confused state while the user is still using the older
7408        // version of the application while the new one gets installed.
7409        IActivityManager am = ActivityManagerNative.getDefault();
7410        if (am != null) {
7411            try {
7412                am.killApplicationWithAppId(pkgName, appId, reason);
7413            } catch (RemoteException e) {
7414            }
7415        }
7416    }
7417
7418    void removePackageLI(PackageSetting ps, boolean chatty) {
7419        if (DEBUG_INSTALL) {
7420            if (chatty)
7421                Log.d(TAG, "Removing package " + ps.name);
7422        }
7423
7424        // writer
7425        synchronized (mPackages) {
7426            mPackages.remove(ps.name);
7427            final PackageParser.Package pkg = ps.pkg;
7428            if (pkg != null) {
7429                cleanPackageDataStructuresLILPw(pkg, chatty);
7430            }
7431        }
7432    }
7433
7434    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7435        if (DEBUG_INSTALL) {
7436            if (chatty)
7437                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7438        }
7439
7440        // writer
7441        synchronized (mPackages) {
7442            mPackages.remove(pkg.applicationInfo.packageName);
7443            cleanPackageDataStructuresLILPw(pkg, chatty);
7444        }
7445    }
7446
7447    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7448        int N = pkg.providers.size();
7449        StringBuilder r = null;
7450        int i;
7451        for (i=0; i<N; i++) {
7452            PackageParser.Provider p = pkg.providers.get(i);
7453            mProviders.removeProvider(p);
7454            if (p.info.authority == null) {
7455
7456                /* There was another ContentProvider with this authority when
7457                 * this app was installed so this authority is null,
7458                 * Ignore it as we don't have to unregister the provider.
7459                 */
7460                continue;
7461            }
7462            String names[] = p.info.authority.split(";");
7463            for (int j = 0; j < names.length; j++) {
7464                if (mProvidersByAuthority.get(names[j]) == p) {
7465                    mProvidersByAuthority.remove(names[j]);
7466                    if (DEBUG_REMOVE) {
7467                        if (chatty)
7468                            Log.d(TAG, "Unregistered content provider: " + names[j]
7469                                    + ", className = " + p.info.name + ", isSyncable = "
7470                                    + p.info.isSyncable);
7471                    }
7472                }
7473            }
7474            if (DEBUG_REMOVE && chatty) {
7475                if (r == null) {
7476                    r = new StringBuilder(256);
7477                } else {
7478                    r.append(' ');
7479                }
7480                r.append(p.info.name);
7481            }
7482        }
7483        if (r != null) {
7484            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7485        }
7486
7487        N = pkg.services.size();
7488        r = null;
7489        for (i=0; i<N; i++) {
7490            PackageParser.Service s = pkg.services.get(i);
7491            mServices.removeService(s);
7492            if (chatty) {
7493                if (r == null) {
7494                    r = new StringBuilder(256);
7495                } else {
7496                    r.append(' ');
7497                }
7498                r.append(s.info.name);
7499            }
7500        }
7501        if (r != null) {
7502            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
7503        }
7504
7505        N = pkg.receivers.size();
7506        r = null;
7507        for (i=0; i<N; i++) {
7508            PackageParser.Activity a = pkg.receivers.get(i);
7509            mReceivers.removeActivity(a, "receiver");
7510            if (DEBUG_REMOVE && chatty) {
7511                if (r == null) {
7512                    r = new StringBuilder(256);
7513                } else {
7514                    r.append(' ');
7515                }
7516                r.append(a.info.name);
7517            }
7518        }
7519        if (r != null) {
7520            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
7521        }
7522
7523        N = pkg.activities.size();
7524        r = null;
7525        for (i=0; i<N; i++) {
7526            PackageParser.Activity a = pkg.activities.get(i);
7527            mActivities.removeActivity(a, "activity");
7528            if (DEBUG_REMOVE && chatty) {
7529                if (r == null) {
7530                    r = new StringBuilder(256);
7531                } else {
7532                    r.append(' ');
7533                }
7534                r.append(a.info.name);
7535            }
7536        }
7537        if (r != null) {
7538            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
7539        }
7540
7541        N = pkg.permissions.size();
7542        r = null;
7543        for (i=0; i<N; i++) {
7544            PackageParser.Permission p = pkg.permissions.get(i);
7545            BasePermission bp = mSettings.mPermissions.get(p.info.name);
7546            if (bp == null) {
7547                bp = mSettings.mPermissionTrees.get(p.info.name);
7548            }
7549            if (bp != null && bp.perm == p) {
7550                bp.perm = null;
7551                if (DEBUG_REMOVE && chatty) {
7552                    if (r == null) {
7553                        r = new StringBuilder(256);
7554                    } else {
7555                        r.append(' ');
7556                    }
7557                    r.append(p.info.name);
7558                }
7559            }
7560            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7561                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
7562                if (appOpPerms != null) {
7563                    appOpPerms.remove(pkg.packageName);
7564                }
7565            }
7566        }
7567        if (r != null) {
7568            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7569        }
7570
7571        N = pkg.requestedPermissions.size();
7572        r = null;
7573        for (i=0; i<N; i++) {
7574            String perm = pkg.requestedPermissions.get(i);
7575            BasePermission bp = mSettings.mPermissions.get(perm);
7576            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7577                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
7578                if (appOpPerms != null) {
7579                    appOpPerms.remove(pkg.packageName);
7580                    if (appOpPerms.isEmpty()) {
7581                        mAppOpPermissionPackages.remove(perm);
7582                    }
7583                }
7584            }
7585        }
7586        if (r != null) {
7587            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7588        }
7589
7590        N = pkg.instrumentation.size();
7591        r = null;
7592        for (i=0; i<N; i++) {
7593            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7594            mInstrumentation.remove(a.getComponentName());
7595            if (DEBUG_REMOVE && chatty) {
7596                if (r == null) {
7597                    r = new StringBuilder(256);
7598                } else {
7599                    r.append(' ');
7600                }
7601                r.append(a.info.name);
7602            }
7603        }
7604        if (r != null) {
7605            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
7606        }
7607
7608        r = null;
7609        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7610            // Only system apps can hold shared libraries.
7611            if (pkg.libraryNames != null) {
7612                for (i=0; i<pkg.libraryNames.size(); i++) {
7613                    String name = pkg.libraryNames.get(i);
7614                    SharedLibraryEntry cur = mSharedLibraries.get(name);
7615                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
7616                        mSharedLibraries.remove(name);
7617                        if (DEBUG_REMOVE && chatty) {
7618                            if (r == null) {
7619                                r = new StringBuilder(256);
7620                            } else {
7621                                r.append(' ');
7622                            }
7623                            r.append(name);
7624                        }
7625                    }
7626                }
7627            }
7628        }
7629        if (r != null) {
7630            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
7631        }
7632    }
7633
7634    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
7635        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
7636            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
7637                return true;
7638            }
7639        }
7640        return false;
7641    }
7642
7643    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
7644    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
7645    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
7646
7647    private void updatePermissionsLPw(String changingPkg,
7648            PackageParser.Package pkgInfo, int flags) {
7649        // Make sure there are no dangling permission trees.
7650        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
7651        while (it.hasNext()) {
7652            final BasePermission bp = it.next();
7653            if (bp.packageSetting == null) {
7654                // We may not yet have parsed the package, so just see if
7655                // we still know about its settings.
7656                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7657            }
7658            if (bp.packageSetting == null) {
7659                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
7660                        + " from package " + bp.sourcePackage);
7661                it.remove();
7662            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7663                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7664                    Slog.i(TAG, "Removing old permission tree: " + bp.name
7665                            + " from package " + bp.sourcePackage);
7666                    flags |= UPDATE_PERMISSIONS_ALL;
7667                    it.remove();
7668                }
7669            }
7670        }
7671
7672        // Make sure all dynamic permissions have been assigned to a package,
7673        // and make sure there are no dangling permissions.
7674        it = mSettings.mPermissions.values().iterator();
7675        while (it.hasNext()) {
7676            final BasePermission bp = it.next();
7677            if (bp.type == BasePermission.TYPE_DYNAMIC) {
7678                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
7679                        + bp.name + " pkg=" + bp.sourcePackage
7680                        + " info=" + bp.pendingInfo);
7681                if (bp.packageSetting == null && bp.pendingInfo != null) {
7682                    final BasePermission tree = findPermissionTreeLP(bp.name);
7683                    if (tree != null && tree.perm != null) {
7684                        bp.packageSetting = tree.packageSetting;
7685                        bp.perm = new PackageParser.Permission(tree.perm.owner,
7686                                new PermissionInfo(bp.pendingInfo));
7687                        bp.perm.info.packageName = tree.perm.info.packageName;
7688                        bp.perm.info.name = bp.name;
7689                        bp.uid = tree.uid;
7690                    }
7691                }
7692            }
7693            if (bp.packageSetting == null) {
7694                // We may not yet have parsed the package, so just see if
7695                // we still know about its settings.
7696                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7697            }
7698            if (bp.packageSetting == null) {
7699                Slog.w(TAG, "Removing dangling permission: " + bp.name
7700                        + " from package " + bp.sourcePackage);
7701                it.remove();
7702            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7703                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7704                    Slog.i(TAG, "Removing old permission: " + bp.name
7705                            + " from package " + bp.sourcePackage);
7706                    flags |= UPDATE_PERMISSIONS_ALL;
7707                    it.remove();
7708                }
7709            }
7710        }
7711
7712        // Now update the permissions for all packages, in particular
7713        // replace the granted permissions of the system packages.
7714        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
7715            for (PackageParser.Package pkg : mPackages.values()) {
7716                if (pkg != pkgInfo) {
7717                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
7718                            changingPkg);
7719                }
7720            }
7721        }
7722
7723        if (pkgInfo != null) {
7724            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
7725        }
7726    }
7727
7728    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
7729            String packageOfInterest) {
7730        // IMPORTANT: There are two types of permissions: install and runtime.
7731        // Install time permissions are granted when the app is installed to
7732        // all device users and users added in the future. Runtime permissions
7733        // are granted at runtime explicitly to specific users. Normal and signature
7734        // protected permissions are install time permissions. Dangerous permissions
7735        // are install permissions if the app's target SDK is Lollipop MR1 or older,
7736        // otherwise they are runtime permissions. This function does not manage
7737        // runtime permissions except for the case an app targeting Lollipop MR1
7738        // being upgraded to target a newer SDK, in which case dangerous permissions
7739        // are transformed from install time to runtime ones.
7740
7741        final PackageSetting ps = (PackageSetting) pkg.mExtras;
7742        if (ps == null) {
7743            return;
7744        }
7745
7746        PermissionsState permissionsState = ps.getPermissionsState();
7747        PermissionsState origPermissions = permissionsState;
7748
7749        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
7750
7751        int[] upgradeUserIds = EMPTY_INT_ARRAY;
7752        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
7753
7754        boolean changedInstallPermission = false;
7755
7756        if (replace) {
7757            ps.installPermissionsFixed = false;
7758            if (!ps.isSharedUser()) {
7759                origPermissions = new PermissionsState(permissionsState);
7760                permissionsState.reset();
7761            }
7762        }
7763
7764        permissionsState.setGlobalGids(mGlobalGids);
7765
7766        final int N = pkg.requestedPermissions.size();
7767        for (int i=0; i<N; i++) {
7768            final String name = pkg.requestedPermissions.get(i);
7769            final BasePermission bp = mSettings.mPermissions.get(name);
7770
7771            if (DEBUG_INSTALL) {
7772                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
7773            }
7774
7775            if (bp == null || bp.packageSetting == null) {
7776                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7777                    Slog.w(TAG, "Unknown permission " + name
7778                            + " in package " + pkg.packageName);
7779                }
7780                continue;
7781            }
7782
7783            final String perm = bp.name;
7784            boolean allowedSig = false;
7785            int grant = GRANT_DENIED;
7786
7787            // Keep track of app op permissions.
7788            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7789                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
7790                if (pkgs == null) {
7791                    pkgs = new ArraySet<>();
7792                    mAppOpPermissionPackages.put(bp.name, pkgs);
7793                }
7794                pkgs.add(pkg.packageName);
7795            }
7796
7797            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
7798            switch (level) {
7799                case PermissionInfo.PROTECTION_NORMAL: {
7800                    // For all apps normal permissions are install time ones.
7801                    grant = GRANT_INSTALL;
7802                } break;
7803
7804                case PermissionInfo.PROTECTION_DANGEROUS: {
7805                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
7806                        // For legacy apps dangerous permissions are install time ones.
7807                        grant = GRANT_INSTALL_LEGACY;
7808                    } else if (ps.isSystem()) {
7809                        final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds();
7810                        if (origPermissions.hasInstallPermission(bp.name)) {
7811                            // If a system app had an install permission, then the app was
7812                            // upgraded and we grant the permissions as runtime to all users.
7813                            grant = GRANT_UPGRADE;
7814                            upgradeUserIds = currentUserIds;
7815                        } else if (!Arrays.equals(updatedUserIds, currentUserIds)) {
7816                            // If users changed since the last permissions update for a
7817                            // system app, we grant the permission as runtime to the new users.
7818                            grant = GRANT_UPGRADE;
7819                            upgradeUserIds = currentUserIds;
7820                            for (int userId : updatedUserIds) {
7821                                upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId);
7822                            }
7823                        } else {
7824                            // Otherwise, we grant the permission as runtime if the app
7825                            // already had it, i.e. we preserve runtime permissions.
7826                            grant = GRANT_RUNTIME;
7827                        }
7828                    } else if (origPermissions.hasInstallPermission(bp.name)) {
7829                        // For legacy apps that became modern, install becomes runtime.
7830                        grant = GRANT_UPGRADE;
7831                        upgradeUserIds = currentUserIds;
7832                    } else if (replace) {
7833                        // For upgraded modern apps keep runtime permissions unchanged.
7834                        grant = GRANT_RUNTIME;
7835                    }
7836                } break;
7837
7838                case PermissionInfo.PROTECTION_SIGNATURE: {
7839                    // For all apps signature permissions are install time ones.
7840                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
7841                    if (allowedSig) {
7842                        grant = GRANT_INSTALL;
7843                    }
7844                } break;
7845            }
7846
7847            if (DEBUG_INSTALL) {
7848                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
7849            }
7850
7851            if (grant != GRANT_DENIED) {
7852                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
7853                    // If this is an existing, non-system package, then
7854                    // we can't add any new permissions to it.
7855                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
7856                        // Except...  if this is a permission that was added
7857                        // to the platform (note: need to only do this when
7858                        // updating the platform).
7859                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
7860                            grant = GRANT_DENIED;
7861                        }
7862                    }
7863                }
7864
7865                switch (grant) {
7866                    case GRANT_INSTALL: {
7867                        // Revoke this as runtime permission to handle the case of
7868                        // a runtime permssion being downgraded to an install one.
7869                        for (int userId : UserManagerService.getInstance().getUserIds()) {
7870                            if (origPermissions.getRuntimePermissionState(
7871                                    bp.name, userId) != null) {
7872                                // Revoke the runtime permission and clear the flags.
7873                                origPermissions.revokeRuntimePermission(bp, userId);
7874                                origPermissions.updatePermissionFlags(bp, userId,
7875                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
7876                                // If we revoked a permission permission, we have to write.
7877                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7878                                        changedRuntimePermissionUserIds, userId);
7879                            }
7880                        }
7881                        // Grant an install permission.
7882                        if (permissionsState.grantInstallPermission(bp) !=
7883                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
7884                            changedInstallPermission = true;
7885                        }
7886                    } break;
7887
7888                    case GRANT_INSTALL_LEGACY: {
7889                        // Grant an install permission.
7890                        if (permissionsState.grantInstallPermission(bp) !=
7891                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
7892                            changedInstallPermission = true;
7893                        }
7894                    } break;
7895
7896                    case GRANT_RUNTIME: {
7897                        // Grant previously granted runtime permissions.
7898                        for (int userId : UserManagerService.getInstance().getUserIds()) {
7899                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
7900                                PermissionState permissionState = origPermissions
7901                                        .getRuntimePermissionState(bp.name, userId);
7902                                final int flags = permissionState.getFlags();
7903                                if (permissionsState.grantRuntimePermission(bp, userId) ==
7904                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7905                                    // If we cannot put the permission as it was, we have to write.
7906                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7907                                            changedRuntimePermissionUserIds, userId);
7908                                } else {
7909                                    // System components not only get the permissions but
7910                                    // they are also fixed, so nothing can change that.
7911                                    final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg)
7912                                            ? flags
7913                                            : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
7914                                    // Propagate the permission flags.
7915                                    permissionsState.updatePermissionFlags(bp, userId,
7916                                            newFlags, newFlags);
7917                                }
7918                            }
7919                        }
7920                    } break;
7921
7922                    case GRANT_UPGRADE: {
7923                        // Grant runtime permissions for a previously held install permission.
7924                        PermissionState permissionState = origPermissions
7925                                .getInstallPermissionState(bp.name);
7926                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
7927
7928                        origPermissions.revokeInstallPermission(bp);
7929                        // We will be transferring the permission flags, so clear them.
7930                        origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
7931                                PackageManager.MASK_PERMISSION_FLAGS, 0);
7932
7933                        // If the permission is not to be promoted to runtime we ignore it and
7934                        // also its other flags as they are not applicable to install permissions.
7935                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
7936                            for (int userId : upgradeUserIds) {
7937                                if (permissionsState.grantRuntimePermission(bp, userId) !=
7938                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7939                                    // System components not only get the permissions but
7940                                    // they are also fixed so nothing can change that.
7941                                    final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg)
7942                                            ? flags
7943                                            : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
7944                                    // Transfer the permission flags.
7945                                    permissionsState.updatePermissionFlags(bp, userId,
7946                                            newFlags, newFlags);
7947                                    // If we granted the permission, we have to write.
7948                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7949                                            changedRuntimePermissionUserIds, userId);
7950                                }
7951                            }
7952                        }
7953                    } break;
7954
7955                    default: {
7956                        if (packageOfInterest == null
7957                                || packageOfInterest.equals(pkg.packageName)) {
7958                            Slog.w(TAG, "Not granting permission " + perm
7959                                    + " to package " + pkg.packageName
7960                                    + " because it was previously installed without");
7961                        }
7962                    } break;
7963                }
7964            } else {
7965                if (permissionsState.revokeInstallPermission(bp) !=
7966                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7967                    // Also drop the permission flags.
7968                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
7969                            PackageManager.MASK_PERMISSION_FLAGS, 0);
7970                    changedInstallPermission = true;
7971                    Slog.i(TAG, "Un-granting permission " + perm
7972                            + " from package " + pkg.packageName
7973                            + " (protectionLevel=" + bp.protectionLevel
7974                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7975                            + ")");
7976                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
7977                    // Don't print warning for app op permissions, since it is fine for them
7978                    // not to be granted, there is a UI for the user to decide.
7979                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7980                        Slog.w(TAG, "Not granting permission " + perm
7981                                + " to package " + pkg.packageName
7982                                + " (protectionLevel=" + bp.protectionLevel
7983                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7984                                + ")");
7985                    }
7986                }
7987            }
7988        }
7989
7990        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
7991                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
7992            // This is the first that we have heard about this package, so the
7993            // permissions we have now selected are fixed until explicitly
7994            // changed.
7995            ps.installPermissionsFixed = true;
7996        }
7997
7998        ps.setPermissionsUpdatedForUserIds(currentUserIds);
7999
8000        // Persist the runtime permissions state for users with changes.
8001        for (int userId : changedRuntimePermissionUserIds) {
8002            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
8003        }
8004    }
8005
8006    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8007        boolean allowed = false;
8008        final int NP = PackageParser.NEW_PERMISSIONS.length;
8009        for (int ip=0; ip<NP; ip++) {
8010            final PackageParser.NewPermissionInfo npi
8011                    = PackageParser.NEW_PERMISSIONS[ip];
8012            if (npi.name.equals(perm)
8013                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8014                allowed = true;
8015                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8016                        + pkg.packageName);
8017                break;
8018            }
8019        }
8020        return allowed;
8021    }
8022
8023    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8024            BasePermission bp, PermissionsState origPermissions) {
8025        boolean allowed;
8026        allowed = (compareSignatures(
8027                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8028                        == PackageManager.SIGNATURE_MATCH)
8029                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8030                        == PackageManager.SIGNATURE_MATCH);
8031        if (!allowed && (bp.protectionLevel
8032                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
8033            if (isSystemApp(pkg)) {
8034                // For updated system applications, a system permission
8035                // is granted only if it had been defined by the original application.
8036                if (pkg.isUpdatedSystemApp()) {
8037                    final PackageSetting sysPs = mSettings
8038                            .getDisabledSystemPkgLPr(pkg.packageName);
8039                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8040                        // If the original was granted this permission, we take
8041                        // that grant decision as read and propagate it to the
8042                        // update.
8043                        if (sysPs.isPrivileged()) {
8044                            allowed = true;
8045                        }
8046                    } else {
8047                        // The system apk may have been updated with an older
8048                        // version of the one on the data partition, but which
8049                        // granted a new system permission that it didn't have
8050                        // before.  In this case we do want to allow the app to
8051                        // now get the new permission if the ancestral apk is
8052                        // privileged to get it.
8053                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8054                            for (int j=0;
8055                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8056                                if (perm.equals(
8057                                        sysPs.pkg.requestedPermissions.get(j))) {
8058                                    allowed = true;
8059                                    break;
8060                                }
8061                            }
8062                        }
8063                    }
8064                } else {
8065                    allowed = isPrivilegedApp(pkg);
8066                }
8067            }
8068        }
8069        if (!allowed && (bp.protectionLevel
8070                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8071            // For development permissions, a development permission
8072            // is granted only if it was already granted.
8073            allowed = origPermissions.hasInstallPermission(perm);
8074        }
8075        return allowed;
8076    }
8077
8078    final class ActivityIntentResolver
8079            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8080        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8081                boolean defaultOnly, int userId) {
8082            if (!sUserManager.exists(userId)) return null;
8083            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8084            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8085        }
8086
8087        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8088                int userId) {
8089            if (!sUserManager.exists(userId)) return null;
8090            mFlags = flags;
8091            return super.queryIntent(intent, resolvedType,
8092                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8093        }
8094
8095        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8096                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8097            if (!sUserManager.exists(userId)) return null;
8098            if (packageActivities == null) {
8099                return null;
8100            }
8101            mFlags = flags;
8102            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8103            final int N = packageActivities.size();
8104            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8105                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8106
8107            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8108            for (int i = 0; i < N; ++i) {
8109                intentFilters = packageActivities.get(i).intents;
8110                if (intentFilters != null && intentFilters.size() > 0) {
8111                    PackageParser.ActivityIntentInfo[] array =
8112                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8113                    intentFilters.toArray(array);
8114                    listCut.add(array);
8115                }
8116            }
8117            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8118        }
8119
8120        public final void addActivity(PackageParser.Activity a, String type) {
8121            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8122            mActivities.put(a.getComponentName(), a);
8123            if (DEBUG_SHOW_INFO)
8124                Log.v(
8125                TAG, "  " + type + " " +
8126                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8127            if (DEBUG_SHOW_INFO)
8128                Log.v(TAG, "    Class=" + a.info.name);
8129            final int NI = a.intents.size();
8130            for (int j=0; j<NI; j++) {
8131                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8132                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8133                    intent.setPriority(0);
8134                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8135                            + a.className + " with priority > 0, forcing to 0");
8136                }
8137                if (DEBUG_SHOW_INFO) {
8138                    Log.v(TAG, "    IntentFilter:");
8139                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8140                }
8141                if (!intent.debugCheck()) {
8142                    Log.w(TAG, "==> For Activity " + a.info.name);
8143                }
8144                addFilter(intent);
8145            }
8146        }
8147
8148        public final void removeActivity(PackageParser.Activity a, String type) {
8149            mActivities.remove(a.getComponentName());
8150            if (DEBUG_SHOW_INFO) {
8151                Log.v(TAG, "  " + type + " "
8152                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8153                                : a.info.name) + ":");
8154                Log.v(TAG, "    Class=" + a.info.name);
8155            }
8156            final int NI = a.intents.size();
8157            for (int j=0; j<NI; j++) {
8158                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8159                if (DEBUG_SHOW_INFO) {
8160                    Log.v(TAG, "    IntentFilter:");
8161                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8162                }
8163                removeFilter(intent);
8164            }
8165        }
8166
8167        @Override
8168        protected boolean allowFilterResult(
8169                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8170            ActivityInfo filterAi = filter.activity.info;
8171            for (int i=dest.size()-1; i>=0; i--) {
8172                ActivityInfo destAi = dest.get(i).activityInfo;
8173                if (destAi.name == filterAi.name
8174                        && destAi.packageName == filterAi.packageName) {
8175                    return false;
8176                }
8177            }
8178            return true;
8179        }
8180
8181        @Override
8182        protected ActivityIntentInfo[] newArray(int size) {
8183            return new ActivityIntentInfo[size];
8184        }
8185
8186        @Override
8187        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8188            if (!sUserManager.exists(userId)) return true;
8189            PackageParser.Package p = filter.activity.owner;
8190            if (p != null) {
8191                PackageSetting ps = (PackageSetting)p.mExtras;
8192                if (ps != null) {
8193                    // System apps are never considered stopped for purposes of
8194                    // filtering, because there may be no way for the user to
8195                    // actually re-launch them.
8196                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8197                            && ps.getStopped(userId);
8198                }
8199            }
8200            return false;
8201        }
8202
8203        @Override
8204        protected boolean isPackageForFilter(String packageName,
8205                PackageParser.ActivityIntentInfo info) {
8206            return packageName.equals(info.activity.owner.packageName);
8207        }
8208
8209        @Override
8210        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8211                int match, int userId) {
8212            if (!sUserManager.exists(userId)) return null;
8213            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8214                return null;
8215            }
8216            final PackageParser.Activity activity = info.activity;
8217            if (mSafeMode && (activity.info.applicationInfo.flags
8218                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8219                return null;
8220            }
8221            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8222            if (ps == null) {
8223                return null;
8224            }
8225            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8226                    ps.readUserState(userId), userId);
8227            if (ai == null) {
8228                return null;
8229            }
8230            final ResolveInfo res = new ResolveInfo();
8231            res.activityInfo = ai;
8232            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8233                res.filter = info;
8234            }
8235            if (info != null) {
8236                res.handleAllWebDataURI = info.handleAllWebDataURI();
8237            }
8238            res.priority = info.getPriority();
8239            res.preferredOrder = activity.owner.mPreferredOrder;
8240            //System.out.println("Result: " + res.activityInfo.className +
8241            //                   " = " + res.priority);
8242            res.match = match;
8243            res.isDefault = info.hasDefault;
8244            res.labelRes = info.labelRes;
8245            res.nonLocalizedLabel = info.nonLocalizedLabel;
8246            if (userNeedsBadging(userId)) {
8247                res.noResourceId = true;
8248            } else {
8249                res.icon = info.icon;
8250            }
8251            res.system = res.activityInfo.applicationInfo.isSystemApp();
8252            return res;
8253        }
8254
8255        @Override
8256        protected void sortResults(List<ResolveInfo> results) {
8257            Collections.sort(results, mResolvePrioritySorter);
8258        }
8259
8260        @Override
8261        protected void dumpFilter(PrintWriter out, String prefix,
8262                PackageParser.ActivityIntentInfo filter) {
8263            out.print(prefix); out.print(
8264                    Integer.toHexString(System.identityHashCode(filter.activity)));
8265                    out.print(' ');
8266                    filter.activity.printComponentShortName(out);
8267                    out.print(" filter ");
8268                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8269        }
8270
8271        @Override
8272        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8273            return filter.activity;
8274        }
8275
8276        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8277            PackageParser.Activity activity = (PackageParser.Activity)label;
8278            out.print(prefix); out.print(
8279                    Integer.toHexString(System.identityHashCode(activity)));
8280                    out.print(' ');
8281                    activity.printComponentShortName(out);
8282            if (count > 1) {
8283                out.print(" ("); out.print(count); out.print(" filters)");
8284            }
8285            out.println();
8286        }
8287
8288//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8289//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8290//            final List<ResolveInfo> retList = Lists.newArrayList();
8291//            while (i.hasNext()) {
8292//                final ResolveInfo resolveInfo = i.next();
8293//                if (isEnabledLP(resolveInfo.activityInfo)) {
8294//                    retList.add(resolveInfo);
8295//                }
8296//            }
8297//            return retList;
8298//        }
8299
8300        // Keys are String (activity class name), values are Activity.
8301        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8302                = new ArrayMap<ComponentName, PackageParser.Activity>();
8303        private int mFlags;
8304    }
8305
8306    private final class ServiceIntentResolver
8307            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8308        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8309                boolean defaultOnly, int userId) {
8310            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8311            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8312        }
8313
8314        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8315                int userId) {
8316            if (!sUserManager.exists(userId)) return null;
8317            mFlags = flags;
8318            return super.queryIntent(intent, resolvedType,
8319                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8320        }
8321
8322        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8323                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8324            if (!sUserManager.exists(userId)) return null;
8325            if (packageServices == null) {
8326                return null;
8327            }
8328            mFlags = flags;
8329            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8330            final int N = packageServices.size();
8331            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8332                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8333
8334            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8335            for (int i = 0; i < N; ++i) {
8336                intentFilters = packageServices.get(i).intents;
8337                if (intentFilters != null && intentFilters.size() > 0) {
8338                    PackageParser.ServiceIntentInfo[] array =
8339                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8340                    intentFilters.toArray(array);
8341                    listCut.add(array);
8342                }
8343            }
8344            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8345        }
8346
8347        public final void addService(PackageParser.Service s) {
8348            mServices.put(s.getComponentName(), s);
8349            if (DEBUG_SHOW_INFO) {
8350                Log.v(TAG, "  "
8351                        + (s.info.nonLocalizedLabel != null
8352                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8353                Log.v(TAG, "    Class=" + s.info.name);
8354            }
8355            final int NI = s.intents.size();
8356            int j;
8357            for (j=0; j<NI; j++) {
8358                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8359                if (DEBUG_SHOW_INFO) {
8360                    Log.v(TAG, "    IntentFilter:");
8361                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8362                }
8363                if (!intent.debugCheck()) {
8364                    Log.w(TAG, "==> For Service " + s.info.name);
8365                }
8366                addFilter(intent);
8367            }
8368        }
8369
8370        public final void removeService(PackageParser.Service s) {
8371            mServices.remove(s.getComponentName());
8372            if (DEBUG_SHOW_INFO) {
8373                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8374                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8375                Log.v(TAG, "    Class=" + s.info.name);
8376            }
8377            final int NI = s.intents.size();
8378            int j;
8379            for (j=0; j<NI; j++) {
8380                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8381                if (DEBUG_SHOW_INFO) {
8382                    Log.v(TAG, "    IntentFilter:");
8383                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8384                }
8385                removeFilter(intent);
8386            }
8387        }
8388
8389        @Override
8390        protected boolean allowFilterResult(
8391                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8392            ServiceInfo filterSi = filter.service.info;
8393            for (int i=dest.size()-1; i>=0; i--) {
8394                ServiceInfo destAi = dest.get(i).serviceInfo;
8395                if (destAi.name == filterSi.name
8396                        && destAi.packageName == filterSi.packageName) {
8397                    return false;
8398                }
8399            }
8400            return true;
8401        }
8402
8403        @Override
8404        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8405            return new PackageParser.ServiceIntentInfo[size];
8406        }
8407
8408        @Override
8409        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8410            if (!sUserManager.exists(userId)) return true;
8411            PackageParser.Package p = filter.service.owner;
8412            if (p != null) {
8413                PackageSetting ps = (PackageSetting)p.mExtras;
8414                if (ps != null) {
8415                    // System apps are never considered stopped for purposes of
8416                    // filtering, because there may be no way for the user to
8417                    // actually re-launch them.
8418                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8419                            && ps.getStopped(userId);
8420                }
8421            }
8422            return false;
8423        }
8424
8425        @Override
8426        protected boolean isPackageForFilter(String packageName,
8427                PackageParser.ServiceIntentInfo info) {
8428            return packageName.equals(info.service.owner.packageName);
8429        }
8430
8431        @Override
8432        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8433                int match, int userId) {
8434            if (!sUserManager.exists(userId)) return null;
8435            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8436            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8437                return null;
8438            }
8439            final PackageParser.Service service = info.service;
8440            if (mSafeMode && (service.info.applicationInfo.flags
8441                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8442                return null;
8443            }
8444            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8445            if (ps == null) {
8446                return null;
8447            }
8448            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8449                    ps.readUserState(userId), userId);
8450            if (si == null) {
8451                return null;
8452            }
8453            final ResolveInfo res = new ResolveInfo();
8454            res.serviceInfo = si;
8455            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8456                res.filter = filter;
8457            }
8458            res.priority = info.getPriority();
8459            res.preferredOrder = service.owner.mPreferredOrder;
8460            res.match = match;
8461            res.isDefault = info.hasDefault;
8462            res.labelRes = info.labelRes;
8463            res.nonLocalizedLabel = info.nonLocalizedLabel;
8464            res.icon = info.icon;
8465            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8466            return res;
8467        }
8468
8469        @Override
8470        protected void sortResults(List<ResolveInfo> results) {
8471            Collections.sort(results, mResolvePrioritySorter);
8472        }
8473
8474        @Override
8475        protected void dumpFilter(PrintWriter out, String prefix,
8476                PackageParser.ServiceIntentInfo filter) {
8477            out.print(prefix); out.print(
8478                    Integer.toHexString(System.identityHashCode(filter.service)));
8479                    out.print(' ');
8480                    filter.service.printComponentShortName(out);
8481                    out.print(" filter ");
8482                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8483        }
8484
8485        @Override
8486        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8487            return filter.service;
8488        }
8489
8490        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8491            PackageParser.Service service = (PackageParser.Service)label;
8492            out.print(prefix); out.print(
8493                    Integer.toHexString(System.identityHashCode(service)));
8494                    out.print(' ');
8495                    service.printComponentShortName(out);
8496            if (count > 1) {
8497                out.print(" ("); out.print(count); out.print(" filters)");
8498            }
8499            out.println();
8500        }
8501
8502//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8503//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8504//            final List<ResolveInfo> retList = Lists.newArrayList();
8505//            while (i.hasNext()) {
8506//                final ResolveInfo resolveInfo = (ResolveInfo) i;
8507//                if (isEnabledLP(resolveInfo.serviceInfo)) {
8508//                    retList.add(resolveInfo);
8509//                }
8510//            }
8511//            return retList;
8512//        }
8513
8514        // Keys are String (activity class name), values are Activity.
8515        private final ArrayMap<ComponentName, PackageParser.Service> mServices
8516                = new ArrayMap<ComponentName, PackageParser.Service>();
8517        private int mFlags;
8518    };
8519
8520    private final class ProviderIntentResolver
8521            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
8522        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8523                boolean defaultOnly, int userId) {
8524            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8525            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8526        }
8527
8528        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8529                int userId) {
8530            if (!sUserManager.exists(userId))
8531                return null;
8532            mFlags = flags;
8533            return super.queryIntent(intent, resolvedType,
8534                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8535        }
8536
8537        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8538                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
8539            if (!sUserManager.exists(userId))
8540                return null;
8541            if (packageProviders == null) {
8542                return null;
8543            }
8544            mFlags = flags;
8545            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
8546            final int N = packageProviders.size();
8547            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
8548                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
8549
8550            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
8551            for (int i = 0; i < N; ++i) {
8552                intentFilters = packageProviders.get(i).intents;
8553                if (intentFilters != null && intentFilters.size() > 0) {
8554                    PackageParser.ProviderIntentInfo[] array =
8555                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
8556                    intentFilters.toArray(array);
8557                    listCut.add(array);
8558                }
8559            }
8560            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8561        }
8562
8563        public final void addProvider(PackageParser.Provider p) {
8564            if (mProviders.containsKey(p.getComponentName())) {
8565                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
8566                return;
8567            }
8568
8569            mProviders.put(p.getComponentName(), p);
8570            if (DEBUG_SHOW_INFO) {
8571                Log.v(TAG, "  "
8572                        + (p.info.nonLocalizedLabel != null
8573                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
8574                Log.v(TAG, "    Class=" + p.info.name);
8575            }
8576            final int NI = p.intents.size();
8577            int j;
8578            for (j = 0; j < NI; j++) {
8579                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8580                if (DEBUG_SHOW_INFO) {
8581                    Log.v(TAG, "    IntentFilter:");
8582                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8583                }
8584                if (!intent.debugCheck()) {
8585                    Log.w(TAG, "==> For Provider " + p.info.name);
8586                }
8587                addFilter(intent);
8588            }
8589        }
8590
8591        public final void removeProvider(PackageParser.Provider p) {
8592            mProviders.remove(p.getComponentName());
8593            if (DEBUG_SHOW_INFO) {
8594                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
8595                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
8596                Log.v(TAG, "    Class=" + p.info.name);
8597            }
8598            final int NI = p.intents.size();
8599            int j;
8600            for (j = 0; j < NI; j++) {
8601                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8602                if (DEBUG_SHOW_INFO) {
8603                    Log.v(TAG, "    IntentFilter:");
8604                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8605                }
8606                removeFilter(intent);
8607            }
8608        }
8609
8610        @Override
8611        protected boolean allowFilterResult(
8612                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
8613            ProviderInfo filterPi = filter.provider.info;
8614            for (int i = dest.size() - 1; i >= 0; i--) {
8615                ProviderInfo destPi = dest.get(i).providerInfo;
8616                if (destPi.name == filterPi.name
8617                        && destPi.packageName == filterPi.packageName) {
8618                    return false;
8619                }
8620            }
8621            return true;
8622        }
8623
8624        @Override
8625        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
8626            return new PackageParser.ProviderIntentInfo[size];
8627        }
8628
8629        @Override
8630        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
8631            if (!sUserManager.exists(userId))
8632                return true;
8633            PackageParser.Package p = filter.provider.owner;
8634            if (p != null) {
8635                PackageSetting ps = (PackageSetting) p.mExtras;
8636                if (ps != null) {
8637                    // System apps are never considered stopped for purposes of
8638                    // filtering, because there may be no way for the user to
8639                    // actually re-launch them.
8640                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8641                            && ps.getStopped(userId);
8642                }
8643            }
8644            return false;
8645        }
8646
8647        @Override
8648        protected boolean isPackageForFilter(String packageName,
8649                PackageParser.ProviderIntentInfo info) {
8650            return packageName.equals(info.provider.owner.packageName);
8651        }
8652
8653        @Override
8654        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
8655                int match, int userId) {
8656            if (!sUserManager.exists(userId))
8657                return null;
8658            final PackageParser.ProviderIntentInfo info = filter;
8659            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
8660                return null;
8661            }
8662            final PackageParser.Provider provider = info.provider;
8663            if (mSafeMode && (provider.info.applicationInfo.flags
8664                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
8665                return null;
8666            }
8667            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
8668            if (ps == null) {
8669                return null;
8670            }
8671            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
8672                    ps.readUserState(userId), userId);
8673            if (pi == null) {
8674                return null;
8675            }
8676            final ResolveInfo res = new ResolveInfo();
8677            res.providerInfo = pi;
8678            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
8679                res.filter = filter;
8680            }
8681            res.priority = info.getPriority();
8682            res.preferredOrder = provider.owner.mPreferredOrder;
8683            res.match = match;
8684            res.isDefault = info.hasDefault;
8685            res.labelRes = info.labelRes;
8686            res.nonLocalizedLabel = info.nonLocalizedLabel;
8687            res.icon = info.icon;
8688            res.system = res.providerInfo.applicationInfo.isSystemApp();
8689            return res;
8690        }
8691
8692        @Override
8693        protected void sortResults(List<ResolveInfo> results) {
8694            Collections.sort(results, mResolvePrioritySorter);
8695        }
8696
8697        @Override
8698        protected void dumpFilter(PrintWriter out, String prefix,
8699                PackageParser.ProviderIntentInfo filter) {
8700            out.print(prefix);
8701            out.print(
8702                    Integer.toHexString(System.identityHashCode(filter.provider)));
8703            out.print(' ');
8704            filter.provider.printComponentShortName(out);
8705            out.print(" filter ");
8706            out.println(Integer.toHexString(System.identityHashCode(filter)));
8707        }
8708
8709        @Override
8710        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
8711            return filter.provider;
8712        }
8713
8714        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8715            PackageParser.Provider provider = (PackageParser.Provider)label;
8716            out.print(prefix); out.print(
8717                    Integer.toHexString(System.identityHashCode(provider)));
8718                    out.print(' ');
8719                    provider.printComponentShortName(out);
8720            if (count > 1) {
8721                out.print(" ("); out.print(count); out.print(" filters)");
8722            }
8723            out.println();
8724        }
8725
8726        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
8727                = new ArrayMap<ComponentName, PackageParser.Provider>();
8728        private int mFlags;
8729    };
8730
8731    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
8732            new Comparator<ResolveInfo>() {
8733        public int compare(ResolveInfo r1, ResolveInfo r2) {
8734            int v1 = r1.priority;
8735            int v2 = r2.priority;
8736            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
8737            if (v1 != v2) {
8738                return (v1 > v2) ? -1 : 1;
8739            }
8740            v1 = r1.preferredOrder;
8741            v2 = r2.preferredOrder;
8742            if (v1 != v2) {
8743                return (v1 > v2) ? -1 : 1;
8744            }
8745            if (r1.isDefault != r2.isDefault) {
8746                return r1.isDefault ? -1 : 1;
8747            }
8748            v1 = r1.match;
8749            v2 = r2.match;
8750            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
8751            if (v1 != v2) {
8752                return (v1 > v2) ? -1 : 1;
8753            }
8754            if (r1.system != r2.system) {
8755                return r1.system ? -1 : 1;
8756            }
8757            return 0;
8758        }
8759    };
8760
8761    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
8762            new Comparator<ProviderInfo>() {
8763        public int compare(ProviderInfo p1, ProviderInfo p2) {
8764            final int v1 = p1.initOrder;
8765            final int v2 = p2.initOrder;
8766            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
8767        }
8768    };
8769
8770    final void sendPackageBroadcast(final String action, final String pkg,
8771            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
8772            final int[] userIds) {
8773        mHandler.post(new Runnable() {
8774            @Override
8775            public void run() {
8776                try {
8777                    final IActivityManager am = ActivityManagerNative.getDefault();
8778                    if (am == null) return;
8779                    final int[] resolvedUserIds;
8780                    if (userIds == null) {
8781                        resolvedUserIds = am.getRunningUserIds();
8782                    } else {
8783                        resolvedUserIds = userIds;
8784                    }
8785                    for (int id : resolvedUserIds) {
8786                        final Intent intent = new Intent(action,
8787                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
8788                        if (extras != null) {
8789                            intent.putExtras(extras);
8790                        }
8791                        if (targetPkg != null) {
8792                            intent.setPackage(targetPkg);
8793                        }
8794                        // Modify the UID when posting to other users
8795                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
8796                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
8797                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
8798                            intent.putExtra(Intent.EXTRA_UID, uid);
8799                        }
8800                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
8801                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
8802                        if (DEBUG_BROADCASTS) {
8803                            RuntimeException here = new RuntimeException("here");
8804                            here.fillInStackTrace();
8805                            Slog.d(TAG, "Sending to user " + id + ": "
8806                                    + intent.toShortString(false, true, false, false)
8807                                    + " " + intent.getExtras(), here);
8808                        }
8809                        am.broadcastIntent(null, intent, null, finishedReceiver,
8810                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
8811                                finishedReceiver != null, false, id);
8812                    }
8813                } catch (RemoteException ex) {
8814                }
8815            }
8816        });
8817    }
8818
8819    /**
8820     * Check if the external storage media is available. This is true if there
8821     * is a mounted external storage medium or if the external storage is
8822     * emulated.
8823     */
8824    private boolean isExternalMediaAvailable() {
8825        return mMediaMounted || Environment.isExternalStorageEmulated();
8826    }
8827
8828    @Override
8829    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
8830        // writer
8831        synchronized (mPackages) {
8832            if (!isExternalMediaAvailable()) {
8833                // If the external storage is no longer mounted at this point,
8834                // the caller may not have been able to delete all of this
8835                // packages files and can not delete any more.  Bail.
8836                return null;
8837            }
8838            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
8839            if (lastPackage != null) {
8840                pkgs.remove(lastPackage);
8841            }
8842            if (pkgs.size() > 0) {
8843                return pkgs.get(0);
8844            }
8845        }
8846        return null;
8847    }
8848
8849    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
8850        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
8851                userId, andCode ? 1 : 0, packageName);
8852        if (mSystemReady) {
8853            msg.sendToTarget();
8854        } else {
8855            if (mPostSystemReadyMessages == null) {
8856                mPostSystemReadyMessages = new ArrayList<>();
8857            }
8858            mPostSystemReadyMessages.add(msg);
8859        }
8860    }
8861
8862    void startCleaningPackages() {
8863        // reader
8864        synchronized (mPackages) {
8865            if (!isExternalMediaAvailable()) {
8866                return;
8867            }
8868            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
8869                return;
8870            }
8871        }
8872        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
8873        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
8874        IActivityManager am = ActivityManagerNative.getDefault();
8875        if (am != null) {
8876            try {
8877                am.startService(null, intent, null, UserHandle.USER_OWNER);
8878            } catch (RemoteException e) {
8879            }
8880        }
8881    }
8882
8883    @Override
8884    public void installPackage(String originPath, IPackageInstallObserver2 observer,
8885            int installFlags, String installerPackageName, VerificationParams verificationParams,
8886            String packageAbiOverride) {
8887        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
8888                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
8889    }
8890
8891    @Override
8892    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
8893            int installFlags, String installerPackageName, VerificationParams verificationParams,
8894            String packageAbiOverride, int userId) {
8895        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
8896
8897        final int callingUid = Binder.getCallingUid();
8898        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
8899
8900        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8901            try {
8902                if (observer != null) {
8903                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
8904                }
8905            } catch (RemoteException re) {
8906            }
8907            return;
8908        }
8909
8910        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
8911            installFlags |= PackageManager.INSTALL_FROM_ADB;
8912
8913        } else {
8914            // Caller holds INSTALL_PACKAGES permission, so we're less strict
8915            // about installerPackageName.
8916
8917            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
8918            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
8919        }
8920
8921        UserHandle user;
8922        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
8923            user = UserHandle.ALL;
8924        } else {
8925            user = new UserHandle(userId);
8926        }
8927
8928        // Only system components can circumvent runtime permissions when installing.
8929        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
8930                && mContext.checkCallingOrSelfPermission(Manifest.permission
8931                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
8932            throw new SecurityException("You need the "
8933                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
8934                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
8935        }
8936
8937        verificationParams.setInstallerUid(callingUid);
8938
8939        final File originFile = new File(originPath);
8940        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
8941
8942        final Message msg = mHandler.obtainMessage(INIT_COPY);
8943        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
8944                null, verificationParams, user, packageAbiOverride);
8945        mHandler.sendMessage(msg);
8946    }
8947
8948    void installStage(String packageName, File stagedDir, String stagedCid,
8949            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
8950            String installerPackageName, int installerUid, UserHandle user) {
8951        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
8952                params.referrerUri, installerUid, null);
8953
8954        final OriginInfo origin;
8955        if (stagedDir != null) {
8956            origin = OriginInfo.fromStagedFile(stagedDir);
8957        } else {
8958            origin = OriginInfo.fromStagedContainer(stagedCid);
8959        }
8960
8961        final Message msg = mHandler.obtainMessage(INIT_COPY);
8962        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
8963                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
8964        mHandler.sendMessage(msg);
8965    }
8966
8967    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
8968        Bundle extras = new Bundle(1);
8969        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
8970
8971        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
8972                packageName, extras, null, null, new int[] {userId});
8973        try {
8974            IActivityManager am = ActivityManagerNative.getDefault();
8975            final boolean isSystem =
8976                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
8977            if (isSystem && am.isUserRunning(userId, false)) {
8978                // The just-installed/enabled app is bundled on the system, so presumed
8979                // to be able to run automatically without needing an explicit launch.
8980                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
8981                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
8982                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
8983                        .setPackage(packageName);
8984                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
8985                        android.app.AppOpsManager.OP_NONE, false, false, userId);
8986            }
8987        } catch (RemoteException e) {
8988            // shouldn't happen
8989            Slog.w(TAG, "Unable to bootstrap installed package", e);
8990        }
8991    }
8992
8993    @Override
8994    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
8995            int userId) {
8996        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8997        PackageSetting pkgSetting;
8998        final int uid = Binder.getCallingUid();
8999        enforceCrossUserPermission(uid, userId, true, true,
9000                "setApplicationHiddenSetting for user " + userId);
9001
9002        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9003            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9004            return false;
9005        }
9006
9007        long callingId = Binder.clearCallingIdentity();
9008        try {
9009            boolean sendAdded = false;
9010            boolean sendRemoved = false;
9011            // writer
9012            synchronized (mPackages) {
9013                pkgSetting = mSettings.mPackages.get(packageName);
9014                if (pkgSetting == null) {
9015                    return false;
9016                }
9017                if (pkgSetting.getHidden(userId) != hidden) {
9018                    pkgSetting.setHidden(hidden, userId);
9019                    mSettings.writePackageRestrictionsLPr(userId);
9020                    if (hidden) {
9021                        sendRemoved = true;
9022                    } else {
9023                        sendAdded = true;
9024                    }
9025                }
9026            }
9027            if (sendAdded) {
9028                sendPackageAddedForUser(packageName, pkgSetting, userId);
9029                return true;
9030            }
9031            if (sendRemoved) {
9032                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9033                        "hiding pkg");
9034                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9035            }
9036        } finally {
9037            Binder.restoreCallingIdentity(callingId);
9038        }
9039        return false;
9040    }
9041
9042    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9043            int userId) {
9044        final PackageRemovedInfo info = new PackageRemovedInfo();
9045        info.removedPackage = packageName;
9046        info.removedUsers = new int[] {userId};
9047        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9048        info.sendBroadcast(false, false, false);
9049    }
9050
9051    /**
9052     * Returns true if application is not found or there was an error. Otherwise it returns
9053     * the hidden state of the package for the given user.
9054     */
9055    @Override
9056    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9057        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9058        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9059                false, "getApplicationHidden for user " + userId);
9060        PackageSetting pkgSetting;
9061        long callingId = Binder.clearCallingIdentity();
9062        try {
9063            // writer
9064            synchronized (mPackages) {
9065                pkgSetting = mSettings.mPackages.get(packageName);
9066                if (pkgSetting == null) {
9067                    return true;
9068                }
9069                return pkgSetting.getHidden(userId);
9070            }
9071        } finally {
9072            Binder.restoreCallingIdentity(callingId);
9073        }
9074    }
9075
9076    /**
9077     * @hide
9078     */
9079    @Override
9080    public int installExistingPackageAsUser(String packageName, int userId) {
9081        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9082                null);
9083        PackageSetting pkgSetting;
9084        final int uid = Binder.getCallingUid();
9085        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9086                + userId);
9087        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9088            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9089        }
9090
9091        long callingId = Binder.clearCallingIdentity();
9092        try {
9093            boolean sendAdded = false;
9094
9095            // writer
9096            synchronized (mPackages) {
9097                pkgSetting = mSettings.mPackages.get(packageName);
9098                if (pkgSetting == null) {
9099                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9100                }
9101                if (!pkgSetting.getInstalled(userId)) {
9102                    pkgSetting.setInstalled(true, userId);
9103                    pkgSetting.setHidden(false, userId);
9104                    mSettings.writePackageRestrictionsLPr(userId);
9105                    sendAdded = true;
9106                }
9107            }
9108
9109            if (sendAdded) {
9110                sendPackageAddedForUser(packageName, pkgSetting, userId);
9111            }
9112        } finally {
9113            Binder.restoreCallingIdentity(callingId);
9114        }
9115
9116        return PackageManager.INSTALL_SUCCEEDED;
9117    }
9118
9119    boolean isUserRestricted(int userId, String restrictionKey) {
9120        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9121        if (restrictions.getBoolean(restrictionKey, false)) {
9122            Log.w(TAG, "User is restricted: " + restrictionKey);
9123            return true;
9124        }
9125        return false;
9126    }
9127
9128    @Override
9129    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9130        mContext.enforceCallingOrSelfPermission(
9131                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9132                "Only package verification agents can verify applications");
9133
9134        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9135        final PackageVerificationResponse response = new PackageVerificationResponse(
9136                verificationCode, Binder.getCallingUid());
9137        msg.arg1 = id;
9138        msg.obj = response;
9139        mHandler.sendMessage(msg);
9140    }
9141
9142    @Override
9143    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9144            long millisecondsToDelay) {
9145        mContext.enforceCallingOrSelfPermission(
9146                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9147                "Only package verification agents can extend verification timeouts");
9148
9149        final PackageVerificationState state = mPendingVerification.get(id);
9150        final PackageVerificationResponse response = new PackageVerificationResponse(
9151                verificationCodeAtTimeout, Binder.getCallingUid());
9152
9153        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9154            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9155        }
9156        if (millisecondsToDelay < 0) {
9157            millisecondsToDelay = 0;
9158        }
9159        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9160                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9161            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9162        }
9163
9164        if ((state != null) && !state.timeoutExtended()) {
9165            state.extendTimeout();
9166
9167            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9168            msg.arg1 = id;
9169            msg.obj = response;
9170            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9171        }
9172    }
9173
9174    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9175            int verificationCode, UserHandle user) {
9176        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9177        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9178        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9179        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9180        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9181
9182        mContext.sendBroadcastAsUser(intent, user,
9183                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9184    }
9185
9186    private ComponentName matchComponentForVerifier(String packageName,
9187            List<ResolveInfo> receivers) {
9188        ActivityInfo targetReceiver = null;
9189
9190        final int NR = receivers.size();
9191        for (int i = 0; i < NR; i++) {
9192            final ResolveInfo info = receivers.get(i);
9193            if (info.activityInfo == null) {
9194                continue;
9195            }
9196
9197            if (packageName.equals(info.activityInfo.packageName)) {
9198                targetReceiver = info.activityInfo;
9199                break;
9200            }
9201        }
9202
9203        if (targetReceiver == null) {
9204            return null;
9205        }
9206
9207        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9208    }
9209
9210    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9211            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9212        if (pkgInfo.verifiers.length == 0) {
9213            return null;
9214        }
9215
9216        final int N = pkgInfo.verifiers.length;
9217        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9218        for (int i = 0; i < N; i++) {
9219            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9220
9221            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9222                    receivers);
9223            if (comp == null) {
9224                continue;
9225            }
9226
9227            final int verifierUid = getUidForVerifier(verifierInfo);
9228            if (verifierUid == -1) {
9229                continue;
9230            }
9231
9232            if (DEBUG_VERIFY) {
9233                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9234                        + " with the correct signature");
9235            }
9236            sufficientVerifiers.add(comp);
9237            verificationState.addSufficientVerifier(verifierUid);
9238        }
9239
9240        return sufficientVerifiers;
9241    }
9242
9243    private int getUidForVerifier(VerifierInfo verifierInfo) {
9244        synchronized (mPackages) {
9245            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9246            if (pkg == null) {
9247                return -1;
9248            } else if (pkg.mSignatures.length != 1) {
9249                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9250                        + " has more than one signature; ignoring");
9251                return -1;
9252            }
9253
9254            /*
9255             * If the public key of the package's signature does not match
9256             * our expected public key, then this is a different package and
9257             * we should skip.
9258             */
9259
9260            final byte[] expectedPublicKey;
9261            try {
9262                final Signature verifierSig = pkg.mSignatures[0];
9263                final PublicKey publicKey = verifierSig.getPublicKey();
9264                expectedPublicKey = publicKey.getEncoded();
9265            } catch (CertificateException e) {
9266                return -1;
9267            }
9268
9269            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9270
9271            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9272                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9273                        + " does not have the expected public key; ignoring");
9274                return -1;
9275            }
9276
9277            return pkg.applicationInfo.uid;
9278        }
9279    }
9280
9281    @Override
9282    public void finishPackageInstall(int token) {
9283        enforceSystemOrRoot("Only the system is allowed to finish installs");
9284
9285        if (DEBUG_INSTALL) {
9286            Slog.v(TAG, "BM finishing package install for " + token);
9287        }
9288
9289        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9290        mHandler.sendMessage(msg);
9291    }
9292
9293    /**
9294     * Get the verification agent timeout.
9295     *
9296     * @return verification timeout in milliseconds
9297     */
9298    private long getVerificationTimeout() {
9299        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9300                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9301                DEFAULT_VERIFICATION_TIMEOUT);
9302    }
9303
9304    /**
9305     * Get the default verification agent response code.
9306     *
9307     * @return default verification response code
9308     */
9309    private int getDefaultVerificationResponse() {
9310        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9311                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9312                DEFAULT_VERIFICATION_RESPONSE);
9313    }
9314
9315    /**
9316     * Check whether or not package verification has been enabled.
9317     *
9318     * @return true if verification should be performed
9319     */
9320    private boolean isVerificationEnabled(int userId, int installFlags) {
9321        if (!DEFAULT_VERIFY_ENABLE) {
9322            return false;
9323        }
9324
9325        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9326
9327        // Check if installing from ADB
9328        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9329            // Do not run verification in a test harness environment
9330            if (ActivityManager.isRunningInTestHarness()) {
9331                return false;
9332            }
9333            if (ensureVerifyAppsEnabled) {
9334                return true;
9335            }
9336            // Check if the developer does not want package verification for ADB installs
9337            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9338                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9339                return false;
9340            }
9341        }
9342
9343        if (ensureVerifyAppsEnabled) {
9344            return true;
9345        }
9346
9347        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9348                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9349    }
9350
9351    @Override
9352    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9353            throws RemoteException {
9354        mContext.enforceCallingOrSelfPermission(
9355                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9356                "Only intentfilter verification agents can verify applications");
9357
9358        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9359        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9360                Binder.getCallingUid(), verificationCode, failedDomains);
9361        msg.arg1 = id;
9362        msg.obj = response;
9363        mHandler.sendMessage(msg);
9364    }
9365
9366    @Override
9367    public int getIntentVerificationStatus(String packageName, int userId) {
9368        synchronized (mPackages) {
9369            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9370        }
9371    }
9372
9373    @Override
9374    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9375        boolean result = false;
9376        synchronized (mPackages) {
9377            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9378        }
9379        if (result) {
9380            scheduleWritePackageRestrictionsLocked(userId);
9381        }
9382        return result;
9383    }
9384
9385    @Override
9386    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9387        synchronized (mPackages) {
9388            return mSettings.getIntentFilterVerificationsLPr(packageName);
9389        }
9390    }
9391
9392    @Override
9393    public List<IntentFilter> getAllIntentFilters(String packageName) {
9394        if (TextUtils.isEmpty(packageName)) {
9395            return Collections.<IntentFilter>emptyList();
9396        }
9397        synchronized (mPackages) {
9398            PackageParser.Package pkg = mPackages.get(packageName);
9399            if (pkg == null || pkg.activities == null) {
9400                return Collections.<IntentFilter>emptyList();
9401            }
9402            final int count = pkg.activities.size();
9403            ArrayList<IntentFilter> result = new ArrayList<>();
9404            for (int n=0; n<count; n++) {
9405                PackageParser.Activity activity = pkg.activities.get(n);
9406                if (activity.intents != null || activity.intents.size() > 0) {
9407                    result.addAll(activity.intents);
9408                }
9409            }
9410            return result;
9411        }
9412    }
9413
9414    @Override
9415    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9416        synchronized (mPackages) {
9417            boolean result = mSettings.setDefaultBrowserPackageNameLPr(packageName, userId);
9418            if (packageName != null) {
9419                result |= updateIntentVerificationStatus(packageName,
9420                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9421                        UserHandle.myUserId());
9422            }
9423            return result;
9424        }
9425    }
9426
9427    @Override
9428    public String getDefaultBrowserPackageName(int userId) {
9429        synchronized (mPackages) {
9430            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9431        }
9432    }
9433
9434    /**
9435     * Get the "allow unknown sources" setting.
9436     *
9437     * @return the current "allow unknown sources" setting
9438     */
9439    private int getUnknownSourcesSettings() {
9440        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9441                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9442                -1);
9443    }
9444
9445    @Override
9446    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9447        final int uid = Binder.getCallingUid();
9448        // writer
9449        synchronized (mPackages) {
9450            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9451            if (targetPackageSetting == null) {
9452                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9453            }
9454
9455            PackageSetting installerPackageSetting;
9456            if (installerPackageName != null) {
9457                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9458                if (installerPackageSetting == null) {
9459                    throw new IllegalArgumentException("Unknown installer package: "
9460                            + installerPackageName);
9461                }
9462            } else {
9463                installerPackageSetting = null;
9464            }
9465
9466            Signature[] callerSignature;
9467            Object obj = mSettings.getUserIdLPr(uid);
9468            if (obj != null) {
9469                if (obj instanceof SharedUserSetting) {
9470                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9471                } else if (obj instanceof PackageSetting) {
9472                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9473                } else {
9474                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9475                }
9476            } else {
9477                throw new SecurityException("Unknown calling uid " + uid);
9478            }
9479
9480            // Verify: can't set installerPackageName to a package that is
9481            // not signed with the same cert as the caller.
9482            if (installerPackageSetting != null) {
9483                if (compareSignatures(callerSignature,
9484                        installerPackageSetting.signatures.mSignatures)
9485                        != PackageManager.SIGNATURE_MATCH) {
9486                    throw new SecurityException(
9487                            "Caller does not have same cert as new installer package "
9488                            + installerPackageName);
9489                }
9490            }
9491
9492            // Verify: if target already has an installer package, it must
9493            // be signed with the same cert as the caller.
9494            if (targetPackageSetting.installerPackageName != null) {
9495                PackageSetting setting = mSettings.mPackages.get(
9496                        targetPackageSetting.installerPackageName);
9497                // If the currently set package isn't valid, then it's always
9498                // okay to change it.
9499                if (setting != null) {
9500                    if (compareSignatures(callerSignature,
9501                            setting.signatures.mSignatures)
9502                            != PackageManager.SIGNATURE_MATCH) {
9503                        throw new SecurityException(
9504                                "Caller does not have same cert as old installer package "
9505                                + targetPackageSetting.installerPackageName);
9506                    }
9507                }
9508            }
9509
9510            // Okay!
9511            targetPackageSetting.installerPackageName = installerPackageName;
9512            scheduleWriteSettingsLocked();
9513        }
9514    }
9515
9516    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
9517        // Queue up an async operation since the package installation may take a little while.
9518        mHandler.post(new Runnable() {
9519            public void run() {
9520                mHandler.removeCallbacks(this);
9521                 // Result object to be returned
9522                PackageInstalledInfo res = new PackageInstalledInfo();
9523                res.returnCode = currentStatus;
9524                res.uid = -1;
9525                res.pkg = null;
9526                res.removedInfo = new PackageRemovedInfo();
9527                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9528                    args.doPreInstall(res.returnCode);
9529                    synchronized (mInstallLock) {
9530                        installPackageLI(args, res);
9531                    }
9532                    args.doPostInstall(res.returnCode, res.uid);
9533                }
9534
9535                // A restore should be performed at this point if (a) the install
9536                // succeeded, (b) the operation is not an update, and (c) the new
9537                // package has not opted out of backup participation.
9538                final boolean update = res.removedInfo.removedPackage != null;
9539                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
9540                boolean doRestore = !update
9541                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
9542
9543                // Set up the post-install work request bookkeeping.  This will be used
9544                // and cleaned up by the post-install event handling regardless of whether
9545                // there's a restore pass performed.  Token values are >= 1.
9546                int token;
9547                if (mNextInstallToken < 0) mNextInstallToken = 1;
9548                token = mNextInstallToken++;
9549
9550                PostInstallData data = new PostInstallData(args, res);
9551                mRunningInstalls.put(token, data);
9552                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
9553
9554                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
9555                    // Pass responsibility to the Backup Manager.  It will perform a
9556                    // restore if appropriate, then pass responsibility back to the
9557                    // Package Manager to run the post-install observer callbacks
9558                    // and broadcasts.
9559                    IBackupManager bm = IBackupManager.Stub.asInterface(
9560                            ServiceManager.getService(Context.BACKUP_SERVICE));
9561                    if (bm != null) {
9562                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
9563                                + " to BM for possible restore");
9564                        try {
9565                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
9566                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
9567                            } else {
9568                                doRestore = false;
9569                            }
9570                        } catch (RemoteException e) {
9571                            // can't happen; the backup manager is local
9572                        } catch (Exception e) {
9573                            Slog.e(TAG, "Exception trying to enqueue restore", e);
9574                            doRestore = false;
9575                        }
9576                    } else {
9577                        Slog.e(TAG, "Backup Manager not found!");
9578                        doRestore = false;
9579                    }
9580                }
9581
9582                if (!doRestore) {
9583                    // No restore possible, or the Backup Manager was mysteriously not
9584                    // available -- just fire the post-install work request directly.
9585                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
9586                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9587                    mHandler.sendMessage(msg);
9588                }
9589            }
9590        });
9591    }
9592
9593    private abstract class HandlerParams {
9594        private static final int MAX_RETRIES = 4;
9595
9596        /**
9597         * Number of times startCopy() has been attempted and had a non-fatal
9598         * error.
9599         */
9600        private int mRetries = 0;
9601
9602        /** User handle for the user requesting the information or installation. */
9603        private final UserHandle mUser;
9604
9605        HandlerParams(UserHandle user) {
9606            mUser = user;
9607        }
9608
9609        UserHandle getUser() {
9610            return mUser;
9611        }
9612
9613        final boolean startCopy() {
9614            boolean res;
9615            try {
9616                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
9617
9618                if (++mRetries > MAX_RETRIES) {
9619                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
9620                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
9621                    handleServiceError();
9622                    return false;
9623                } else {
9624                    handleStartCopy();
9625                    res = true;
9626                }
9627            } catch (RemoteException e) {
9628                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
9629                mHandler.sendEmptyMessage(MCS_RECONNECT);
9630                res = false;
9631            }
9632            handleReturnCode();
9633            return res;
9634        }
9635
9636        final void serviceError() {
9637            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
9638            handleServiceError();
9639            handleReturnCode();
9640        }
9641
9642        abstract void handleStartCopy() throws RemoteException;
9643        abstract void handleServiceError();
9644        abstract void handleReturnCode();
9645    }
9646
9647    class MeasureParams extends HandlerParams {
9648        private final PackageStats mStats;
9649        private boolean mSuccess;
9650
9651        private final IPackageStatsObserver mObserver;
9652
9653        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
9654            super(new UserHandle(stats.userHandle));
9655            mObserver = observer;
9656            mStats = stats;
9657        }
9658
9659        @Override
9660        public String toString() {
9661            return "MeasureParams{"
9662                + Integer.toHexString(System.identityHashCode(this))
9663                + " " + mStats.packageName + "}";
9664        }
9665
9666        @Override
9667        void handleStartCopy() throws RemoteException {
9668            synchronized (mInstallLock) {
9669                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
9670            }
9671
9672            if (mSuccess) {
9673                final boolean mounted;
9674                if (Environment.isExternalStorageEmulated()) {
9675                    mounted = true;
9676                } else {
9677                    final String status = Environment.getExternalStorageState();
9678                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
9679                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
9680                }
9681
9682                if (mounted) {
9683                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
9684
9685                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
9686                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
9687
9688                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
9689                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
9690
9691                    // Always subtract cache size, since it's a subdirectory
9692                    mStats.externalDataSize -= mStats.externalCacheSize;
9693
9694                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
9695                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
9696
9697                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
9698                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
9699                }
9700            }
9701        }
9702
9703        @Override
9704        void handleReturnCode() {
9705            if (mObserver != null) {
9706                try {
9707                    mObserver.onGetStatsCompleted(mStats, mSuccess);
9708                } catch (RemoteException e) {
9709                    Slog.i(TAG, "Observer no longer exists.");
9710                }
9711            }
9712        }
9713
9714        @Override
9715        void handleServiceError() {
9716            Slog.e(TAG, "Could not measure application " + mStats.packageName
9717                            + " external storage");
9718        }
9719    }
9720
9721    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
9722            throws RemoteException {
9723        long result = 0;
9724        for (File path : paths) {
9725            result += mcs.calculateDirectorySize(path.getAbsolutePath());
9726        }
9727        return result;
9728    }
9729
9730    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
9731        for (File path : paths) {
9732            try {
9733                mcs.clearDirectory(path.getAbsolutePath());
9734            } catch (RemoteException e) {
9735            }
9736        }
9737    }
9738
9739    static class OriginInfo {
9740        /**
9741         * Location where install is coming from, before it has been
9742         * copied/renamed into place. This could be a single monolithic APK
9743         * file, or a cluster directory. This location may be untrusted.
9744         */
9745        final File file;
9746        final String cid;
9747
9748        /**
9749         * Flag indicating that {@link #file} or {@link #cid} has already been
9750         * staged, meaning downstream users don't need to defensively copy the
9751         * contents.
9752         */
9753        final boolean staged;
9754
9755        /**
9756         * Flag indicating that {@link #file} or {@link #cid} is an already
9757         * installed app that is being moved.
9758         */
9759        final boolean existing;
9760
9761        final String resolvedPath;
9762        final File resolvedFile;
9763
9764        static OriginInfo fromNothing() {
9765            return new OriginInfo(null, null, false, false);
9766        }
9767
9768        static OriginInfo fromUntrustedFile(File file) {
9769            return new OriginInfo(file, null, false, false);
9770        }
9771
9772        static OriginInfo fromExistingFile(File file) {
9773            return new OriginInfo(file, null, false, true);
9774        }
9775
9776        static OriginInfo fromStagedFile(File file) {
9777            return new OriginInfo(file, null, true, false);
9778        }
9779
9780        static OriginInfo fromStagedContainer(String cid) {
9781            return new OriginInfo(null, cid, true, false);
9782        }
9783
9784        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
9785            this.file = file;
9786            this.cid = cid;
9787            this.staged = staged;
9788            this.existing = existing;
9789
9790            if (cid != null) {
9791                resolvedPath = PackageHelper.getSdDir(cid);
9792                resolvedFile = new File(resolvedPath);
9793            } else if (file != null) {
9794                resolvedPath = file.getAbsolutePath();
9795                resolvedFile = file;
9796            } else {
9797                resolvedPath = null;
9798                resolvedFile = null;
9799            }
9800        }
9801    }
9802
9803    class MoveInfo {
9804        final int moveId;
9805        final String fromUuid;
9806        final String toUuid;
9807        final String packageName;
9808        final String dataAppName;
9809        final int appId;
9810        final String seinfo;
9811
9812        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
9813                String dataAppName, int appId, String seinfo) {
9814            this.moveId = moveId;
9815            this.fromUuid = fromUuid;
9816            this.toUuid = toUuid;
9817            this.packageName = packageName;
9818            this.dataAppName = dataAppName;
9819            this.appId = appId;
9820            this.seinfo = seinfo;
9821        }
9822    }
9823
9824    class InstallParams extends HandlerParams {
9825        final OriginInfo origin;
9826        final MoveInfo move;
9827        final IPackageInstallObserver2 observer;
9828        int installFlags;
9829        final String installerPackageName;
9830        final String volumeUuid;
9831        final VerificationParams verificationParams;
9832        private InstallArgs mArgs;
9833        private int mRet;
9834        final String packageAbiOverride;
9835
9836        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
9837                int installFlags, String installerPackageName, String volumeUuid,
9838                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
9839            super(user);
9840            this.origin = origin;
9841            this.move = move;
9842            this.observer = observer;
9843            this.installFlags = installFlags;
9844            this.installerPackageName = installerPackageName;
9845            this.volumeUuid = volumeUuid;
9846            this.verificationParams = verificationParams;
9847            this.packageAbiOverride = packageAbiOverride;
9848        }
9849
9850        @Override
9851        public String toString() {
9852            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
9853                    + " file=" + origin.file + " cid=" + origin.cid + "}";
9854        }
9855
9856        public ManifestDigest getManifestDigest() {
9857            if (verificationParams == null) {
9858                return null;
9859            }
9860            return verificationParams.getManifestDigest();
9861        }
9862
9863        private int installLocationPolicy(PackageInfoLite pkgLite) {
9864            String packageName = pkgLite.packageName;
9865            int installLocation = pkgLite.installLocation;
9866            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9867            // reader
9868            synchronized (mPackages) {
9869                PackageParser.Package pkg = mPackages.get(packageName);
9870                if (pkg != null) {
9871                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
9872                        // Check for downgrading.
9873                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
9874                            try {
9875                                checkDowngrade(pkg, pkgLite);
9876                            } catch (PackageManagerException e) {
9877                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
9878                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
9879                            }
9880                        }
9881                        // Check for updated system application.
9882                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9883                            if (onSd) {
9884                                Slog.w(TAG, "Cannot install update to system app on sdcard");
9885                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
9886                            }
9887                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9888                        } else {
9889                            if (onSd) {
9890                                // Install flag overrides everything.
9891                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9892                            }
9893                            // If current upgrade specifies particular preference
9894                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
9895                                // Application explicitly specified internal.
9896                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9897                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
9898                                // App explictly prefers external. Let policy decide
9899                            } else {
9900                                // Prefer previous location
9901                                if (isExternal(pkg)) {
9902                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9903                                }
9904                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9905                            }
9906                        }
9907                    } else {
9908                        // Invalid install. Return error code
9909                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
9910                    }
9911                }
9912            }
9913            // All the special cases have been taken care of.
9914            // Return result based on recommended install location.
9915            if (onSd) {
9916                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9917            }
9918            return pkgLite.recommendedInstallLocation;
9919        }
9920
9921        /*
9922         * Invoke remote method to get package information and install
9923         * location values. Override install location based on default
9924         * policy if needed and then create install arguments based
9925         * on the install location.
9926         */
9927        public void handleStartCopy() throws RemoteException {
9928            int ret = PackageManager.INSTALL_SUCCEEDED;
9929
9930            // If we're already staged, we've firmly committed to an install location
9931            if (origin.staged) {
9932                if (origin.file != null) {
9933                    installFlags |= PackageManager.INSTALL_INTERNAL;
9934                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
9935                } else if (origin.cid != null) {
9936                    installFlags |= PackageManager.INSTALL_EXTERNAL;
9937                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
9938                } else {
9939                    throw new IllegalStateException("Invalid stage location");
9940                }
9941            }
9942
9943            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9944            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
9945
9946            PackageInfoLite pkgLite = null;
9947
9948            if (onInt && onSd) {
9949                // Check if both bits are set.
9950                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
9951                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9952            } else {
9953                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
9954                        packageAbiOverride);
9955
9956                /*
9957                 * If we have too little free space, try to free cache
9958                 * before giving up.
9959                 */
9960                if (!origin.staged && pkgLite.recommendedInstallLocation
9961                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9962                    // TODO: focus freeing disk space on the target device
9963                    final StorageManager storage = StorageManager.from(mContext);
9964                    final long lowThreshold = storage.getStorageLowBytes(
9965                            Environment.getDataDirectory());
9966
9967                    final long sizeBytes = mContainerService.calculateInstalledSize(
9968                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
9969
9970                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
9971                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
9972                                installFlags, packageAbiOverride);
9973                    }
9974
9975                    /*
9976                     * The cache free must have deleted the file we
9977                     * downloaded to install.
9978                     *
9979                     * TODO: fix the "freeCache" call to not delete
9980                     *       the file we care about.
9981                     */
9982                    if (pkgLite.recommendedInstallLocation
9983                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9984                        pkgLite.recommendedInstallLocation
9985                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
9986                    }
9987                }
9988            }
9989
9990            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9991                int loc = pkgLite.recommendedInstallLocation;
9992                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
9993                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9994                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
9995                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9996                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9997                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9998                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
9999                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10000                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10001                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10002                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10003                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10004                } else {
10005                    // Override with defaults if needed.
10006                    loc = installLocationPolicy(pkgLite);
10007                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10008                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10009                    } else if (!onSd && !onInt) {
10010                        // Override install location with flags
10011                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10012                            // Set the flag to install on external media.
10013                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10014                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10015                        } else {
10016                            // Make sure the flag for installing on external
10017                            // media is unset
10018                            installFlags |= PackageManager.INSTALL_INTERNAL;
10019                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10020                        }
10021                    }
10022                }
10023            }
10024
10025            final InstallArgs args = createInstallArgs(this);
10026            mArgs = args;
10027
10028            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10029                 /*
10030                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10031                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10032                 */
10033                int userIdentifier = getUser().getIdentifier();
10034                if (userIdentifier == UserHandle.USER_ALL
10035                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10036                    userIdentifier = UserHandle.USER_OWNER;
10037                }
10038
10039                /*
10040                 * Determine if we have any installed package verifiers. If we
10041                 * do, then we'll defer to them to verify the packages.
10042                 */
10043                final int requiredUid = mRequiredVerifierPackage == null ? -1
10044                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10045                if (!origin.existing && requiredUid != -1
10046                        && isVerificationEnabled(userIdentifier, installFlags)) {
10047                    final Intent verification = new Intent(
10048                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10049                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10050                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10051                            PACKAGE_MIME_TYPE);
10052                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10053
10054                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10055                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10056                            0 /* TODO: Which userId? */);
10057
10058                    if (DEBUG_VERIFY) {
10059                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10060                                + verification.toString() + " with " + pkgLite.verifiers.length
10061                                + " optional verifiers");
10062                    }
10063
10064                    final int verificationId = mPendingVerificationToken++;
10065
10066                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10067
10068                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10069                            installerPackageName);
10070
10071                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10072                            installFlags);
10073
10074                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10075                            pkgLite.packageName);
10076
10077                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10078                            pkgLite.versionCode);
10079
10080                    if (verificationParams != null) {
10081                        if (verificationParams.getVerificationURI() != null) {
10082                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10083                                 verificationParams.getVerificationURI());
10084                        }
10085                        if (verificationParams.getOriginatingURI() != null) {
10086                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10087                                  verificationParams.getOriginatingURI());
10088                        }
10089                        if (verificationParams.getReferrer() != null) {
10090                            verification.putExtra(Intent.EXTRA_REFERRER,
10091                                  verificationParams.getReferrer());
10092                        }
10093                        if (verificationParams.getOriginatingUid() >= 0) {
10094                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10095                                  verificationParams.getOriginatingUid());
10096                        }
10097                        if (verificationParams.getInstallerUid() >= 0) {
10098                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10099                                  verificationParams.getInstallerUid());
10100                        }
10101                    }
10102
10103                    final PackageVerificationState verificationState = new PackageVerificationState(
10104                            requiredUid, args);
10105
10106                    mPendingVerification.append(verificationId, verificationState);
10107
10108                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10109                            receivers, verificationState);
10110
10111                    /*
10112                     * If any sufficient verifiers were listed in the package
10113                     * manifest, attempt to ask them.
10114                     */
10115                    if (sufficientVerifiers != null) {
10116                        final int N = sufficientVerifiers.size();
10117                        if (N == 0) {
10118                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10119                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10120                        } else {
10121                            for (int i = 0; i < N; i++) {
10122                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10123
10124                                final Intent sufficientIntent = new Intent(verification);
10125                                sufficientIntent.setComponent(verifierComponent);
10126
10127                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
10128                            }
10129                        }
10130                    }
10131
10132                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10133                            mRequiredVerifierPackage, receivers);
10134                    if (ret == PackageManager.INSTALL_SUCCEEDED
10135                            && mRequiredVerifierPackage != null) {
10136                        /*
10137                         * Send the intent to the required verification agent,
10138                         * but only start the verification timeout after the
10139                         * target BroadcastReceivers have run.
10140                         */
10141                        verification.setComponent(requiredVerifierComponent);
10142                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
10143                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10144                                new BroadcastReceiver() {
10145                                    @Override
10146                                    public void onReceive(Context context, Intent intent) {
10147                                        final Message msg = mHandler
10148                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10149                                        msg.arg1 = verificationId;
10150                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10151                                    }
10152                                }, null, 0, null, null);
10153
10154                        /*
10155                         * We don't want the copy to proceed until verification
10156                         * succeeds, so null out this field.
10157                         */
10158                        mArgs = null;
10159                    }
10160                } else {
10161                    /*
10162                     * No package verification is enabled, so immediately start
10163                     * the remote call to initiate copy using temporary file.
10164                     */
10165                    ret = args.copyApk(mContainerService, true);
10166                }
10167            }
10168
10169            mRet = ret;
10170        }
10171
10172        @Override
10173        void handleReturnCode() {
10174            // If mArgs is null, then MCS couldn't be reached. When it
10175            // reconnects, it will try again to install. At that point, this
10176            // will succeed.
10177            if (mArgs != null) {
10178                processPendingInstall(mArgs, mRet);
10179            }
10180        }
10181
10182        @Override
10183        void handleServiceError() {
10184            mArgs = createInstallArgs(this);
10185            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10186        }
10187
10188        public boolean isForwardLocked() {
10189            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10190        }
10191    }
10192
10193    /**
10194     * Used during creation of InstallArgs
10195     *
10196     * @param installFlags package installation flags
10197     * @return true if should be installed on external storage
10198     */
10199    private static boolean installOnExternalAsec(int installFlags) {
10200        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10201            return false;
10202        }
10203        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10204            return true;
10205        }
10206        return false;
10207    }
10208
10209    /**
10210     * Used during creation of InstallArgs
10211     *
10212     * @param installFlags package installation flags
10213     * @return true if should be installed as forward locked
10214     */
10215    private static boolean installForwardLocked(int installFlags) {
10216        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10217    }
10218
10219    private InstallArgs createInstallArgs(InstallParams params) {
10220        if (params.move != null) {
10221            return new MoveInstallArgs(params);
10222        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10223            return new AsecInstallArgs(params);
10224        } else {
10225            return new FileInstallArgs(params);
10226        }
10227    }
10228
10229    /**
10230     * Create args that describe an existing installed package. Typically used
10231     * when cleaning up old installs, or used as a move source.
10232     */
10233    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10234            String resourcePath, String[] instructionSets) {
10235        final boolean isInAsec;
10236        if (installOnExternalAsec(installFlags)) {
10237            /* Apps on SD card are always in ASEC containers. */
10238            isInAsec = true;
10239        } else if (installForwardLocked(installFlags)
10240                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10241            /*
10242             * Forward-locked apps are only in ASEC containers if they're the
10243             * new style
10244             */
10245            isInAsec = true;
10246        } else {
10247            isInAsec = false;
10248        }
10249
10250        if (isInAsec) {
10251            return new AsecInstallArgs(codePath, instructionSets,
10252                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10253        } else {
10254            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10255        }
10256    }
10257
10258    static abstract class InstallArgs {
10259        /** @see InstallParams#origin */
10260        final OriginInfo origin;
10261        /** @see InstallParams#move */
10262        final MoveInfo move;
10263
10264        final IPackageInstallObserver2 observer;
10265        // Always refers to PackageManager flags only
10266        final int installFlags;
10267        final String installerPackageName;
10268        final String volumeUuid;
10269        final ManifestDigest manifestDigest;
10270        final UserHandle user;
10271        final String abiOverride;
10272
10273        // The list of instruction sets supported by this app. This is currently
10274        // only used during the rmdex() phase to clean up resources. We can get rid of this
10275        // if we move dex files under the common app path.
10276        /* nullable */ String[] instructionSets;
10277
10278        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10279                int installFlags, String installerPackageName, String volumeUuid,
10280                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10281                String abiOverride) {
10282            this.origin = origin;
10283            this.move = move;
10284            this.installFlags = installFlags;
10285            this.observer = observer;
10286            this.installerPackageName = installerPackageName;
10287            this.volumeUuid = volumeUuid;
10288            this.manifestDigest = manifestDigest;
10289            this.user = user;
10290            this.instructionSets = instructionSets;
10291            this.abiOverride = abiOverride;
10292        }
10293
10294        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10295        abstract int doPreInstall(int status);
10296
10297        /**
10298         * Rename package into final resting place. All paths on the given
10299         * scanned package should be updated to reflect the rename.
10300         */
10301        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10302        abstract int doPostInstall(int status, int uid);
10303
10304        /** @see PackageSettingBase#codePathString */
10305        abstract String getCodePath();
10306        /** @see PackageSettingBase#resourcePathString */
10307        abstract String getResourcePath();
10308
10309        // Need installer lock especially for dex file removal.
10310        abstract void cleanUpResourcesLI();
10311        abstract boolean doPostDeleteLI(boolean delete);
10312
10313        /**
10314         * Called before the source arguments are copied. This is used mostly
10315         * for MoveParams when it needs to read the source file to put it in the
10316         * destination.
10317         */
10318        int doPreCopy() {
10319            return PackageManager.INSTALL_SUCCEEDED;
10320        }
10321
10322        /**
10323         * Called after the source arguments are copied. This is used mostly for
10324         * MoveParams when it needs to read the source file to put it in the
10325         * destination.
10326         *
10327         * @return
10328         */
10329        int doPostCopy(int uid) {
10330            return PackageManager.INSTALL_SUCCEEDED;
10331        }
10332
10333        protected boolean isFwdLocked() {
10334            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10335        }
10336
10337        protected boolean isExternalAsec() {
10338            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10339        }
10340
10341        UserHandle getUser() {
10342            return user;
10343        }
10344    }
10345
10346    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10347        if (!allCodePaths.isEmpty()) {
10348            if (instructionSets == null) {
10349                throw new IllegalStateException("instructionSet == null");
10350            }
10351            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10352            for (String codePath : allCodePaths) {
10353                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10354                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10355                    if (retCode < 0) {
10356                        Slog.w(TAG, "Couldn't remove dex file for package: "
10357                                + " at location " + codePath + ", retcode=" + retCode);
10358                        // we don't consider this to be a failure of the core package deletion
10359                    }
10360                }
10361            }
10362        }
10363    }
10364
10365    /**
10366     * Logic to handle installation of non-ASEC applications, including copying
10367     * and renaming logic.
10368     */
10369    class FileInstallArgs extends InstallArgs {
10370        private File codeFile;
10371        private File resourceFile;
10372
10373        // Example topology:
10374        // /data/app/com.example/base.apk
10375        // /data/app/com.example/split_foo.apk
10376        // /data/app/com.example/lib/arm/libfoo.so
10377        // /data/app/com.example/lib/arm64/libfoo.so
10378        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10379
10380        /** New install */
10381        FileInstallArgs(InstallParams params) {
10382            super(params.origin, params.move, params.observer, params.installFlags,
10383                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10384                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10385            if (isFwdLocked()) {
10386                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10387            }
10388        }
10389
10390        /** Existing install */
10391        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10392            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10393                    null);
10394            this.codeFile = (codePath != null) ? new File(codePath) : null;
10395            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10396        }
10397
10398        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10399            if (origin.staged) {
10400                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10401                codeFile = origin.file;
10402                resourceFile = origin.file;
10403                return PackageManager.INSTALL_SUCCEEDED;
10404            }
10405
10406            try {
10407                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10408                codeFile = tempDir;
10409                resourceFile = tempDir;
10410            } catch (IOException e) {
10411                Slog.w(TAG, "Failed to create copy file: " + e);
10412                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10413            }
10414
10415            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10416                @Override
10417                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10418                    if (!FileUtils.isValidExtFilename(name)) {
10419                        throw new IllegalArgumentException("Invalid filename: " + name);
10420                    }
10421                    try {
10422                        final File file = new File(codeFile, name);
10423                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10424                                O_RDWR | O_CREAT, 0644);
10425                        Os.chmod(file.getAbsolutePath(), 0644);
10426                        return new ParcelFileDescriptor(fd);
10427                    } catch (ErrnoException e) {
10428                        throw new RemoteException("Failed to open: " + e.getMessage());
10429                    }
10430                }
10431            };
10432
10433            int ret = PackageManager.INSTALL_SUCCEEDED;
10434            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10435            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10436                Slog.e(TAG, "Failed to copy package");
10437                return ret;
10438            }
10439
10440            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10441            NativeLibraryHelper.Handle handle = null;
10442            try {
10443                handle = NativeLibraryHelper.Handle.create(codeFile);
10444                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10445                        abiOverride);
10446            } catch (IOException e) {
10447                Slog.e(TAG, "Copying native libraries failed", e);
10448                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10449            } finally {
10450                IoUtils.closeQuietly(handle);
10451            }
10452
10453            return ret;
10454        }
10455
10456        int doPreInstall(int status) {
10457            if (status != PackageManager.INSTALL_SUCCEEDED) {
10458                cleanUp();
10459            }
10460            return status;
10461        }
10462
10463        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10464            if (status != PackageManager.INSTALL_SUCCEEDED) {
10465                cleanUp();
10466                return false;
10467            }
10468
10469            final File targetDir = codeFile.getParentFile();
10470            final File beforeCodeFile = codeFile;
10471            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10472
10473            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10474            try {
10475                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10476            } catch (ErrnoException e) {
10477                Slog.w(TAG, "Failed to rename", e);
10478                return false;
10479            }
10480
10481            if (!SELinux.restoreconRecursive(afterCodeFile)) {
10482                Slog.w(TAG, "Failed to restorecon");
10483                return false;
10484            }
10485
10486            // Reflect the rename internally
10487            codeFile = afterCodeFile;
10488            resourceFile = afterCodeFile;
10489
10490            // Reflect the rename in scanned details
10491            pkg.codePath = afterCodeFile.getAbsolutePath();
10492            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10493                    pkg.baseCodePath);
10494            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10495                    pkg.splitCodePaths);
10496
10497            // Reflect the rename in app info
10498            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10499            pkg.applicationInfo.setCodePath(pkg.codePath);
10500            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10501            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10502            pkg.applicationInfo.setResourcePath(pkg.codePath);
10503            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10504            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10505
10506            return true;
10507        }
10508
10509        int doPostInstall(int status, int uid) {
10510            if (status != PackageManager.INSTALL_SUCCEEDED) {
10511                cleanUp();
10512            }
10513            return status;
10514        }
10515
10516        @Override
10517        String getCodePath() {
10518            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10519        }
10520
10521        @Override
10522        String getResourcePath() {
10523            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10524        }
10525
10526        private boolean cleanUp() {
10527            if (codeFile == null || !codeFile.exists()) {
10528                return false;
10529            }
10530
10531            if (codeFile.isDirectory()) {
10532                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10533            } else {
10534                codeFile.delete();
10535            }
10536
10537            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10538                resourceFile.delete();
10539            }
10540
10541            return true;
10542        }
10543
10544        void cleanUpResourcesLI() {
10545            // Try enumerating all code paths before deleting
10546            List<String> allCodePaths = Collections.EMPTY_LIST;
10547            if (codeFile != null && codeFile.exists()) {
10548                try {
10549                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10550                    allCodePaths = pkg.getAllCodePaths();
10551                } catch (PackageParserException e) {
10552                    // Ignored; we tried our best
10553                }
10554            }
10555
10556            cleanUp();
10557            removeDexFiles(allCodePaths, instructionSets);
10558        }
10559
10560        boolean doPostDeleteLI(boolean delete) {
10561            // XXX err, shouldn't we respect the delete flag?
10562            cleanUpResourcesLI();
10563            return true;
10564        }
10565    }
10566
10567    private boolean isAsecExternal(String cid) {
10568        final String asecPath = PackageHelper.getSdFilesystem(cid);
10569        return !asecPath.startsWith(mAsecInternalPath);
10570    }
10571
10572    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
10573            PackageManagerException {
10574        if (copyRet < 0) {
10575            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
10576                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
10577                throw new PackageManagerException(copyRet, message);
10578            }
10579        }
10580    }
10581
10582    /**
10583     * Extract the MountService "container ID" from the full code path of an
10584     * .apk.
10585     */
10586    static String cidFromCodePath(String fullCodePath) {
10587        int eidx = fullCodePath.lastIndexOf("/");
10588        String subStr1 = fullCodePath.substring(0, eidx);
10589        int sidx = subStr1.lastIndexOf("/");
10590        return subStr1.substring(sidx+1, eidx);
10591    }
10592
10593    /**
10594     * Logic to handle installation of ASEC applications, including copying and
10595     * renaming logic.
10596     */
10597    class AsecInstallArgs extends InstallArgs {
10598        static final String RES_FILE_NAME = "pkg.apk";
10599        static final String PUBLIC_RES_FILE_NAME = "res.zip";
10600
10601        String cid;
10602        String packagePath;
10603        String resourcePath;
10604
10605        /** New install */
10606        AsecInstallArgs(InstallParams params) {
10607            super(params.origin, params.move, params.observer, params.installFlags,
10608                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10609                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10610        }
10611
10612        /** Existing install */
10613        AsecInstallArgs(String fullCodePath, String[] instructionSets,
10614                        boolean isExternal, boolean isForwardLocked) {
10615            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
10616                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10617                    instructionSets, null);
10618            // Hackily pretend we're still looking at a full code path
10619            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
10620                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
10621            }
10622
10623            // Extract cid from fullCodePath
10624            int eidx = fullCodePath.lastIndexOf("/");
10625            String subStr1 = fullCodePath.substring(0, eidx);
10626            int sidx = subStr1.lastIndexOf("/");
10627            cid = subStr1.substring(sidx+1, eidx);
10628            setMountPath(subStr1);
10629        }
10630
10631        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
10632            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
10633                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10634                    instructionSets, null);
10635            this.cid = cid;
10636            setMountPath(PackageHelper.getSdDir(cid));
10637        }
10638
10639        void createCopyFile() {
10640            cid = mInstallerService.allocateExternalStageCidLegacy();
10641        }
10642
10643        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10644            if (origin.staged) {
10645                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
10646                cid = origin.cid;
10647                setMountPath(PackageHelper.getSdDir(cid));
10648                return PackageManager.INSTALL_SUCCEEDED;
10649            }
10650
10651            if (temp) {
10652                createCopyFile();
10653            } else {
10654                /*
10655                 * Pre-emptively destroy the container since it's destroyed if
10656                 * copying fails due to it existing anyway.
10657                 */
10658                PackageHelper.destroySdDir(cid);
10659            }
10660
10661            final String newMountPath = imcs.copyPackageToContainer(
10662                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
10663                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
10664
10665            if (newMountPath != null) {
10666                setMountPath(newMountPath);
10667                return PackageManager.INSTALL_SUCCEEDED;
10668            } else {
10669                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10670            }
10671        }
10672
10673        @Override
10674        String getCodePath() {
10675            return packagePath;
10676        }
10677
10678        @Override
10679        String getResourcePath() {
10680            return resourcePath;
10681        }
10682
10683        int doPreInstall(int status) {
10684            if (status != PackageManager.INSTALL_SUCCEEDED) {
10685                // Destroy container
10686                PackageHelper.destroySdDir(cid);
10687            } else {
10688                boolean mounted = PackageHelper.isContainerMounted(cid);
10689                if (!mounted) {
10690                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
10691                            Process.SYSTEM_UID);
10692                    if (newMountPath != null) {
10693                        setMountPath(newMountPath);
10694                    } else {
10695                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10696                    }
10697                }
10698            }
10699            return status;
10700        }
10701
10702        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10703            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
10704            String newMountPath = null;
10705            if (PackageHelper.isContainerMounted(cid)) {
10706                // Unmount the container
10707                if (!PackageHelper.unMountSdDir(cid)) {
10708                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
10709                    return false;
10710                }
10711            }
10712            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10713                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
10714                        " which might be stale. Will try to clean up.");
10715                // Clean up the stale container and proceed to recreate.
10716                if (!PackageHelper.destroySdDir(newCacheId)) {
10717                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
10718                    return false;
10719                }
10720                // Successfully cleaned up stale container. Try to rename again.
10721                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10722                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
10723                            + " inspite of cleaning it up.");
10724                    return false;
10725                }
10726            }
10727            if (!PackageHelper.isContainerMounted(newCacheId)) {
10728                Slog.w(TAG, "Mounting container " + newCacheId);
10729                newMountPath = PackageHelper.mountSdDir(newCacheId,
10730                        getEncryptKey(), Process.SYSTEM_UID);
10731            } else {
10732                newMountPath = PackageHelper.getSdDir(newCacheId);
10733            }
10734            if (newMountPath == null) {
10735                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
10736                return false;
10737            }
10738            Log.i(TAG, "Succesfully renamed " + cid +
10739                    " to " + newCacheId +
10740                    " at new path: " + newMountPath);
10741            cid = newCacheId;
10742
10743            final File beforeCodeFile = new File(packagePath);
10744            setMountPath(newMountPath);
10745            final File afterCodeFile = new File(packagePath);
10746
10747            // Reflect the rename in scanned details
10748            pkg.codePath = afterCodeFile.getAbsolutePath();
10749            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10750                    pkg.baseCodePath);
10751            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10752                    pkg.splitCodePaths);
10753
10754            // Reflect the rename in app info
10755            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10756            pkg.applicationInfo.setCodePath(pkg.codePath);
10757            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10758            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10759            pkg.applicationInfo.setResourcePath(pkg.codePath);
10760            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10761            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10762
10763            return true;
10764        }
10765
10766        private void setMountPath(String mountPath) {
10767            final File mountFile = new File(mountPath);
10768
10769            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
10770            if (monolithicFile.exists()) {
10771                packagePath = monolithicFile.getAbsolutePath();
10772                if (isFwdLocked()) {
10773                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
10774                } else {
10775                    resourcePath = packagePath;
10776                }
10777            } else {
10778                packagePath = mountFile.getAbsolutePath();
10779                resourcePath = packagePath;
10780            }
10781        }
10782
10783        int doPostInstall(int status, int uid) {
10784            if (status != PackageManager.INSTALL_SUCCEEDED) {
10785                cleanUp();
10786            } else {
10787                final int groupOwner;
10788                final String protectedFile;
10789                if (isFwdLocked()) {
10790                    groupOwner = UserHandle.getSharedAppGid(uid);
10791                    protectedFile = RES_FILE_NAME;
10792                } else {
10793                    groupOwner = -1;
10794                    protectedFile = null;
10795                }
10796
10797                if (uid < Process.FIRST_APPLICATION_UID
10798                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
10799                    Slog.e(TAG, "Failed to finalize " + cid);
10800                    PackageHelper.destroySdDir(cid);
10801                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10802                }
10803
10804                boolean mounted = PackageHelper.isContainerMounted(cid);
10805                if (!mounted) {
10806                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
10807                }
10808            }
10809            return status;
10810        }
10811
10812        private void cleanUp() {
10813            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
10814
10815            // Destroy secure container
10816            PackageHelper.destroySdDir(cid);
10817        }
10818
10819        private List<String> getAllCodePaths() {
10820            final File codeFile = new File(getCodePath());
10821            if (codeFile != null && codeFile.exists()) {
10822                try {
10823                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10824                    return pkg.getAllCodePaths();
10825                } catch (PackageParserException e) {
10826                    // Ignored; we tried our best
10827                }
10828            }
10829            return Collections.EMPTY_LIST;
10830        }
10831
10832        void cleanUpResourcesLI() {
10833            // Enumerate all code paths before deleting
10834            cleanUpResourcesLI(getAllCodePaths());
10835        }
10836
10837        private void cleanUpResourcesLI(List<String> allCodePaths) {
10838            cleanUp();
10839            removeDexFiles(allCodePaths, instructionSets);
10840        }
10841
10842        String getPackageName() {
10843            return getAsecPackageName(cid);
10844        }
10845
10846        boolean doPostDeleteLI(boolean delete) {
10847            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
10848            final List<String> allCodePaths = getAllCodePaths();
10849            boolean mounted = PackageHelper.isContainerMounted(cid);
10850            if (mounted) {
10851                // Unmount first
10852                if (PackageHelper.unMountSdDir(cid)) {
10853                    mounted = false;
10854                }
10855            }
10856            if (!mounted && delete) {
10857                cleanUpResourcesLI(allCodePaths);
10858            }
10859            return !mounted;
10860        }
10861
10862        @Override
10863        int doPreCopy() {
10864            if (isFwdLocked()) {
10865                if (!PackageHelper.fixSdPermissions(cid,
10866                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
10867                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10868                }
10869            }
10870
10871            return PackageManager.INSTALL_SUCCEEDED;
10872        }
10873
10874        @Override
10875        int doPostCopy(int uid) {
10876            if (isFwdLocked()) {
10877                if (uid < Process.FIRST_APPLICATION_UID
10878                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
10879                                RES_FILE_NAME)) {
10880                    Slog.e(TAG, "Failed to finalize " + cid);
10881                    PackageHelper.destroySdDir(cid);
10882                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10883                }
10884            }
10885
10886            return PackageManager.INSTALL_SUCCEEDED;
10887        }
10888    }
10889
10890    /**
10891     * Logic to handle movement of existing installed applications.
10892     */
10893    class MoveInstallArgs extends InstallArgs {
10894        private File codeFile;
10895        private File resourceFile;
10896
10897        /** New install */
10898        MoveInstallArgs(InstallParams params) {
10899            super(params.origin, params.move, params.observer, params.installFlags,
10900                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10901                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10902        }
10903
10904        int copyApk(IMediaContainerService imcs, boolean temp) {
10905            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
10906                    + move.fromUuid + " to " + move.toUuid);
10907            synchronized (mInstaller) {
10908                if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
10909                        move.dataAppName, move.appId, move.seinfo) != 0) {
10910                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10911                }
10912            }
10913
10914            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
10915            resourceFile = codeFile;
10916            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
10917
10918            return PackageManager.INSTALL_SUCCEEDED;
10919        }
10920
10921        int doPreInstall(int status) {
10922            if (status != PackageManager.INSTALL_SUCCEEDED) {
10923                cleanUp();
10924            }
10925            return status;
10926        }
10927
10928        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10929            if (status != PackageManager.INSTALL_SUCCEEDED) {
10930                cleanUp();
10931                return false;
10932            }
10933
10934            // Reflect the move in app info
10935            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10936            pkg.applicationInfo.setCodePath(pkg.codePath);
10937            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10938            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10939            pkg.applicationInfo.setResourcePath(pkg.codePath);
10940            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10941            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10942
10943            return true;
10944        }
10945
10946        int doPostInstall(int status, int uid) {
10947            if (status != PackageManager.INSTALL_SUCCEEDED) {
10948                cleanUp();
10949            }
10950            return status;
10951        }
10952
10953        @Override
10954        String getCodePath() {
10955            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10956        }
10957
10958        @Override
10959        String getResourcePath() {
10960            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10961        }
10962
10963        private boolean cleanUp() {
10964            if (codeFile == null || !codeFile.exists()) {
10965                return false;
10966            }
10967
10968            if (codeFile.isDirectory()) {
10969                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10970            } else {
10971                codeFile.delete();
10972            }
10973
10974            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10975                resourceFile.delete();
10976            }
10977
10978            return true;
10979        }
10980
10981        void cleanUpResourcesLI() {
10982            cleanUp();
10983        }
10984
10985        boolean doPostDeleteLI(boolean delete) {
10986            // XXX err, shouldn't we respect the delete flag?
10987            cleanUpResourcesLI();
10988            return true;
10989        }
10990    }
10991
10992    static String getAsecPackageName(String packageCid) {
10993        int idx = packageCid.lastIndexOf("-");
10994        if (idx == -1) {
10995            return packageCid;
10996        }
10997        return packageCid.substring(0, idx);
10998    }
10999
11000    // Utility method used to create code paths based on package name and available index.
11001    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11002        String idxStr = "";
11003        int idx = 1;
11004        // Fall back to default value of idx=1 if prefix is not
11005        // part of oldCodePath
11006        if (oldCodePath != null) {
11007            String subStr = oldCodePath;
11008            // Drop the suffix right away
11009            if (suffix != null && subStr.endsWith(suffix)) {
11010                subStr = subStr.substring(0, subStr.length() - suffix.length());
11011            }
11012            // If oldCodePath already contains prefix find out the
11013            // ending index to either increment or decrement.
11014            int sidx = subStr.lastIndexOf(prefix);
11015            if (sidx != -1) {
11016                subStr = subStr.substring(sidx + prefix.length());
11017                if (subStr != null) {
11018                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11019                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11020                    }
11021                    try {
11022                        idx = Integer.parseInt(subStr);
11023                        if (idx <= 1) {
11024                            idx++;
11025                        } else {
11026                            idx--;
11027                        }
11028                    } catch(NumberFormatException e) {
11029                    }
11030                }
11031            }
11032        }
11033        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11034        return prefix + idxStr;
11035    }
11036
11037    private File getNextCodePath(File targetDir, String packageName) {
11038        int suffix = 1;
11039        File result;
11040        do {
11041            result = new File(targetDir, packageName + "-" + suffix);
11042            suffix++;
11043        } while (result.exists());
11044        return result;
11045    }
11046
11047    // Utility method that returns the relative package path with respect
11048    // to the installation directory. Like say for /data/data/com.test-1.apk
11049    // string com.test-1 is returned.
11050    static String deriveCodePathName(String codePath) {
11051        if (codePath == null) {
11052            return null;
11053        }
11054        final File codeFile = new File(codePath);
11055        final String name = codeFile.getName();
11056        if (codeFile.isDirectory()) {
11057            return name;
11058        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11059            final int lastDot = name.lastIndexOf('.');
11060            return name.substring(0, lastDot);
11061        } else {
11062            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11063            return null;
11064        }
11065    }
11066
11067    class PackageInstalledInfo {
11068        String name;
11069        int uid;
11070        // The set of users that originally had this package installed.
11071        int[] origUsers;
11072        // The set of users that now have this package installed.
11073        int[] newUsers;
11074        PackageParser.Package pkg;
11075        int returnCode;
11076        String returnMsg;
11077        PackageRemovedInfo removedInfo;
11078
11079        public void setError(int code, String msg) {
11080            returnCode = code;
11081            returnMsg = msg;
11082            Slog.w(TAG, msg);
11083        }
11084
11085        public void setError(String msg, PackageParserException e) {
11086            returnCode = e.error;
11087            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11088            Slog.w(TAG, msg, e);
11089        }
11090
11091        public void setError(String msg, PackageManagerException e) {
11092            returnCode = e.error;
11093            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11094            Slog.w(TAG, msg, e);
11095        }
11096
11097        // In some error cases we want to convey more info back to the observer
11098        String origPackage;
11099        String origPermission;
11100    }
11101
11102    /*
11103     * Install a non-existing package.
11104     */
11105    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11106            UserHandle user, String installerPackageName, String volumeUuid,
11107            PackageInstalledInfo res) {
11108        // Remember this for later, in case we need to rollback this install
11109        String pkgName = pkg.packageName;
11110
11111        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11112        final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName,
11113                UserHandle.USER_OWNER).exists();
11114        synchronized(mPackages) {
11115            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11116                // A package with the same name is already installed, though
11117                // it has been renamed to an older name.  The package we
11118                // are trying to install should be installed as an update to
11119                // the existing one, but that has not been requested, so bail.
11120                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11121                        + " without first uninstalling package running as "
11122                        + mSettings.mRenamedPackages.get(pkgName));
11123                return;
11124            }
11125            if (mPackages.containsKey(pkgName)) {
11126                // Don't allow installation over an existing package with the same name.
11127                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11128                        + " without first uninstalling.");
11129                return;
11130            }
11131        }
11132
11133        try {
11134            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11135                    System.currentTimeMillis(), user);
11136
11137            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11138            // delete the partially installed application. the data directory will have to be
11139            // restored if it was already existing
11140            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11141                // remove package from internal structures.  Note that we want deletePackageX to
11142                // delete the package data and cache directories that it created in
11143                // scanPackageLocked, unless those directories existed before we even tried to
11144                // install.
11145                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11146                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11147                                res.removedInfo, true);
11148            }
11149
11150        } catch (PackageManagerException e) {
11151            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11152        }
11153    }
11154
11155    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11156        // Can't rotate keys during boot or if sharedUser.
11157        if (oldPs == null || (scanFlags&SCAN_BOOTING) != 0 || oldPs.sharedUser != null
11158                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11159            return false;
11160        }
11161        // app is using upgradeKeySets; make sure all are valid
11162        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11163        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11164        for (int i = 0; i < upgradeKeySets.length; i++) {
11165            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11166                Slog.wtf(TAG, "Package "
11167                         + (oldPs.name != null ? oldPs.name : "<null>")
11168                         + " contains upgrade-key-set reference to unknown key-set: "
11169                         + upgradeKeySets[i]
11170                         + " reverting to signatures check.");
11171                return false;
11172            }
11173        }
11174        return true;
11175    }
11176
11177    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11178        // Upgrade keysets are being used.  Determine if new package has a superset of the
11179        // required keys.
11180        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11181        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11182        for (int i = 0; i < upgradeKeySets.length; i++) {
11183            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11184            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11185                return true;
11186            }
11187        }
11188        return false;
11189    }
11190
11191    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11192            UserHandle user, String installerPackageName, String volumeUuid,
11193            PackageInstalledInfo res) {
11194        final PackageParser.Package oldPackage;
11195        final String pkgName = pkg.packageName;
11196        final int[] allUsers;
11197        final boolean[] perUserInstalled;
11198        final boolean weFroze;
11199
11200        // First find the old package info and check signatures
11201        synchronized(mPackages) {
11202            oldPackage = mPackages.get(pkgName);
11203            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11204            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11205            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11206                if(!checkUpgradeKeySetLP(ps, pkg)) {
11207                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11208                            "New package not signed by keys specified by upgrade-keysets: "
11209                            + pkgName);
11210                    return;
11211                }
11212            } else {
11213                // default to original signature matching
11214                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11215                    != PackageManager.SIGNATURE_MATCH) {
11216                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11217                            "New package has a different signature: " + pkgName);
11218                    return;
11219                }
11220            }
11221
11222            // In case of rollback, remember per-user/profile install state
11223            allUsers = sUserManager.getUserIds();
11224            perUserInstalled = new boolean[allUsers.length];
11225            for (int i = 0; i < allUsers.length; i++) {
11226                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11227            }
11228
11229            // Mark the app as frozen to prevent launching during the upgrade
11230            // process, and then kill all running instances
11231            if (!ps.frozen) {
11232                ps.frozen = true;
11233                weFroze = true;
11234            } else {
11235                weFroze = false;
11236            }
11237        }
11238
11239        // Now that we're guarded by frozen state, kill app during upgrade
11240        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11241
11242        try {
11243            boolean sysPkg = (isSystemApp(oldPackage));
11244            if (sysPkg) {
11245                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11246                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11247            } else {
11248                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11249                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11250            }
11251        } finally {
11252            // Regardless of success or failure of upgrade steps above, always
11253            // unfreeze the package if we froze it
11254            if (weFroze) {
11255                unfreezePackage(pkgName);
11256            }
11257        }
11258    }
11259
11260    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11261            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11262            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11263            String volumeUuid, PackageInstalledInfo res) {
11264        String pkgName = deletedPackage.packageName;
11265        boolean deletedPkg = true;
11266        boolean updatedSettings = false;
11267
11268        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11269                + deletedPackage);
11270        long origUpdateTime;
11271        if (pkg.mExtras != null) {
11272            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11273        } else {
11274            origUpdateTime = 0;
11275        }
11276
11277        // First delete the existing package while retaining the data directory
11278        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11279                res.removedInfo, true)) {
11280            // If the existing package wasn't successfully deleted
11281            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11282            deletedPkg = false;
11283        } else {
11284            // Successfully deleted the old package; proceed with replace.
11285
11286            // If deleted package lived in a container, give users a chance to
11287            // relinquish resources before killing.
11288            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11289                if (DEBUG_INSTALL) {
11290                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11291                }
11292                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11293                final ArrayList<String> pkgList = new ArrayList<String>(1);
11294                pkgList.add(deletedPackage.applicationInfo.packageName);
11295                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11296            }
11297
11298            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11299            try {
11300                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11301                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11302                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11303                        perUserInstalled, res, user);
11304                updatedSettings = true;
11305            } catch (PackageManagerException e) {
11306                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11307            }
11308        }
11309
11310        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11311            // remove package from internal structures.  Note that we want deletePackageX to
11312            // delete the package data and cache directories that it created in
11313            // scanPackageLocked, unless those directories existed before we even tried to
11314            // install.
11315            if(updatedSettings) {
11316                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11317                deletePackageLI(
11318                        pkgName, null, true, allUsers, perUserInstalled,
11319                        PackageManager.DELETE_KEEP_DATA,
11320                                res.removedInfo, true);
11321            }
11322            // Since we failed to install the new package we need to restore the old
11323            // package that we deleted.
11324            if (deletedPkg) {
11325                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11326                File restoreFile = new File(deletedPackage.codePath);
11327                // Parse old package
11328                boolean oldExternal = isExternal(deletedPackage);
11329                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11330                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11331                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11332                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11333                try {
11334                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11335                } catch (PackageManagerException e) {
11336                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11337                            + e.getMessage());
11338                    return;
11339                }
11340                // Restore of old package succeeded. Update permissions.
11341                // writer
11342                synchronized (mPackages) {
11343                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11344                            UPDATE_PERMISSIONS_ALL);
11345                    // can downgrade to reader
11346                    mSettings.writeLPr();
11347                }
11348                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11349            }
11350        }
11351    }
11352
11353    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11354            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11355            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11356            String volumeUuid, PackageInstalledInfo res) {
11357        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11358                + ", old=" + deletedPackage);
11359        boolean disabledSystem = false;
11360        boolean updatedSettings = false;
11361        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11362        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11363                != 0) {
11364            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11365        }
11366        String packageName = deletedPackage.packageName;
11367        if (packageName == null) {
11368            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11369                    "Attempt to delete null packageName.");
11370            return;
11371        }
11372        PackageParser.Package oldPkg;
11373        PackageSetting oldPkgSetting;
11374        // reader
11375        synchronized (mPackages) {
11376            oldPkg = mPackages.get(packageName);
11377            oldPkgSetting = mSettings.mPackages.get(packageName);
11378            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11379                    (oldPkgSetting == null)) {
11380                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11381                        "Couldn't find package:" + packageName + " information");
11382                return;
11383            }
11384        }
11385
11386        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11387        res.removedInfo.removedPackage = packageName;
11388        // Remove existing system package
11389        removePackageLI(oldPkgSetting, true);
11390        // writer
11391        synchronized (mPackages) {
11392            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11393            if (!disabledSystem && deletedPackage != null) {
11394                // We didn't need to disable the .apk as a current system package,
11395                // which means we are replacing another update that is already
11396                // installed.  We need to make sure to delete the older one's .apk.
11397                res.removedInfo.args = createInstallArgsForExisting(0,
11398                        deletedPackage.applicationInfo.getCodePath(),
11399                        deletedPackage.applicationInfo.getResourcePath(),
11400                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11401            } else {
11402                res.removedInfo.args = null;
11403            }
11404        }
11405
11406        // Successfully disabled the old package. Now proceed with re-installation
11407        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11408
11409        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11410        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11411
11412        PackageParser.Package newPackage = null;
11413        try {
11414            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11415            if (newPackage.mExtras != null) {
11416                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11417                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11418                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11419
11420                // is the update attempting to change shared user? that isn't going to work...
11421                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11422                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11423                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11424                            + " to " + newPkgSetting.sharedUser);
11425                    updatedSettings = true;
11426                }
11427            }
11428
11429            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11430                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11431                        perUserInstalled, res, user);
11432                updatedSettings = true;
11433            }
11434
11435        } catch (PackageManagerException e) {
11436            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11437        }
11438
11439        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11440            // Re installation failed. Restore old information
11441            // Remove new pkg information
11442            if (newPackage != null) {
11443                removeInstalledPackageLI(newPackage, true);
11444            }
11445            // Add back the old system package
11446            try {
11447                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11448            } catch (PackageManagerException e) {
11449                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11450            }
11451            // Restore the old system information in Settings
11452            synchronized (mPackages) {
11453                if (disabledSystem) {
11454                    mSettings.enableSystemPackageLPw(packageName);
11455                }
11456                if (updatedSettings) {
11457                    mSettings.setInstallerPackageName(packageName,
11458                            oldPkgSetting.installerPackageName);
11459                }
11460                mSettings.writeLPr();
11461            }
11462        }
11463    }
11464
11465    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
11466            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
11467            UserHandle user) {
11468        String pkgName = newPackage.packageName;
11469        synchronized (mPackages) {
11470            //write settings. the installStatus will be incomplete at this stage.
11471            //note that the new package setting would have already been
11472            //added to mPackages. It hasn't been persisted yet.
11473            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11474            mSettings.writeLPr();
11475        }
11476
11477        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11478
11479        synchronized (mPackages) {
11480            updatePermissionsLPw(newPackage.packageName, newPackage,
11481                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11482                            ? UPDATE_PERMISSIONS_ALL : 0));
11483            // For system-bundled packages, we assume that installing an upgraded version
11484            // of the package implies that the user actually wants to run that new code,
11485            // so we enable the package.
11486            PackageSetting ps = mSettings.mPackages.get(pkgName);
11487            if (ps != null) {
11488                if (isSystemApp(newPackage)) {
11489                    // NB: implicit assumption that system package upgrades apply to all users
11490                    if (DEBUG_INSTALL) {
11491                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
11492                    }
11493                    if (res.origUsers != null) {
11494                        for (int userHandle : res.origUsers) {
11495                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
11496                                    userHandle, installerPackageName);
11497                        }
11498                    }
11499                    // Also convey the prior install/uninstall state
11500                    if (allUsers != null && perUserInstalled != null) {
11501                        for (int i = 0; i < allUsers.length; i++) {
11502                            if (DEBUG_INSTALL) {
11503                                Slog.d(TAG, "    user " + allUsers[i]
11504                                        + " => " + perUserInstalled[i]);
11505                            }
11506                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
11507                        }
11508                        // these install state changes will be persisted in the
11509                        // upcoming call to mSettings.writeLPr().
11510                    }
11511                }
11512                // It's implied that when a user requests installation, they want the app to be
11513                // installed and enabled.
11514                int userId = user.getIdentifier();
11515                if (userId != UserHandle.USER_ALL) {
11516                    ps.setInstalled(true, userId);
11517                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
11518                }
11519            }
11520            res.name = pkgName;
11521            res.uid = newPackage.applicationInfo.uid;
11522            res.pkg = newPackage;
11523            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
11524            mSettings.setInstallerPackageName(pkgName, installerPackageName);
11525            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11526            //to update install status
11527            mSettings.writeLPr();
11528        }
11529    }
11530
11531    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
11532        final int installFlags = args.installFlags;
11533        final String installerPackageName = args.installerPackageName;
11534        final String volumeUuid = args.volumeUuid;
11535        final File tmpPackageFile = new File(args.getCodePath());
11536        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
11537        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
11538                || (args.volumeUuid != null));
11539        boolean replace = false;
11540        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
11541        // Result object to be returned
11542        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11543
11544        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
11545        // Retrieve PackageSettings and parse package
11546        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
11547                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
11548                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11549        PackageParser pp = new PackageParser();
11550        pp.setSeparateProcesses(mSeparateProcesses);
11551        pp.setDisplayMetrics(mMetrics);
11552
11553        final PackageParser.Package pkg;
11554        try {
11555            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
11556        } catch (PackageParserException e) {
11557            res.setError("Failed parse during installPackageLI", e);
11558            return;
11559        }
11560
11561        // Mark that we have an install time CPU ABI override.
11562        pkg.cpuAbiOverride = args.abiOverride;
11563
11564        String pkgName = res.name = pkg.packageName;
11565        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
11566            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
11567                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
11568                return;
11569            }
11570        }
11571
11572        try {
11573            pp.collectCertificates(pkg, parseFlags);
11574            pp.collectManifestDigest(pkg);
11575        } catch (PackageParserException e) {
11576            res.setError("Failed collect during installPackageLI", e);
11577            return;
11578        }
11579
11580        /* If the installer passed in a manifest digest, compare it now. */
11581        if (args.manifestDigest != null) {
11582            if (DEBUG_INSTALL) {
11583                final String parsedManifest = pkg.manifestDigest == null ? "null"
11584                        : pkg.manifestDigest.toString();
11585                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
11586                        + parsedManifest);
11587            }
11588
11589            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
11590                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
11591                return;
11592            }
11593        } else if (DEBUG_INSTALL) {
11594            final String parsedManifest = pkg.manifestDigest == null
11595                    ? "null" : pkg.manifestDigest.toString();
11596            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
11597        }
11598
11599        // Get rid of all references to package scan path via parser.
11600        pp = null;
11601        String oldCodePath = null;
11602        boolean systemApp = false;
11603        synchronized (mPackages) {
11604            // Check if installing already existing package
11605            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11606                String oldName = mSettings.mRenamedPackages.get(pkgName);
11607                if (pkg.mOriginalPackages != null
11608                        && pkg.mOriginalPackages.contains(oldName)
11609                        && mPackages.containsKey(oldName)) {
11610                    // This package is derived from an original package,
11611                    // and this device has been updating from that original
11612                    // name.  We must continue using the original name, so
11613                    // rename the new package here.
11614                    pkg.setPackageName(oldName);
11615                    pkgName = pkg.packageName;
11616                    replace = true;
11617                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
11618                            + oldName + " pkgName=" + pkgName);
11619                } else if (mPackages.containsKey(pkgName)) {
11620                    // This package, under its official name, already exists
11621                    // on the device; we should replace it.
11622                    replace = true;
11623                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
11624                }
11625
11626                // Prevent apps opting out from runtime permissions
11627                if (replace) {
11628                    PackageParser.Package oldPackage = mPackages.get(pkgName);
11629                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
11630                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
11631                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
11632                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
11633                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
11634                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
11635                                        + " doesn't support runtime permissions but the old"
11636                                        + " target SDK " + oldTargetSdk + " does.");
11637                        return;
11638                    }
11639                }
11640            }
11641
11642            PackageSetting ps = mSettings.mPackages.get(pkgName);
11643            if (ps != null) {
11644                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
11645
11646                // Quick sanity check that we're signed correctly if updating;
11647                // we'll check this again later when scanning, but we want to
11648                // bail early here before tripping over redefined permissions.
11649                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11650                    if (!checkUpgradeKeySetLP(ps, pkg)) {
11651                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
11652                                + pkg.packageName + " upgrade keys do not match the "
11653                                + "previously installed version");
11654                        return;
11655                    }
11656                } else {
11657                    try {
11658                        verifySignaturesLP(ps, pkg);
11659                    } catch (PackageManagerException e) {
11660                        res.setError(e.error, e.getMessage());
11661                        return;
11662                    }
11663                }
11664
11665                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
11666                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
11667                    systemApp = (ps.pkg.applicationInfo.flags &
11668                            ApplicationInfo.FLAG_SYSTEM) != 0;
11669                }
11670                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11671            }
11672
11673            // Check whether the newly-scanned package wants to define an already-defined perm
11674            int N = pkg.permissions.size();
11675            for (int i = N-1; i >= 0; i--) {
11676                PackageParser.Permission perm = pkg.permissions.get(i);
11677                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
11678                if (bp != null) {
11679                    // If the defining package is signed with our cert, it's okay.  This
11680                    // also includes the "updating the same package" case, of course.
11681                    // "updating same package" could also involve key-rotation.
11682                    final boolean sigsOk;
11683                    if (bp.sourcePackage.equals(pkg.packageName)
11684                            && (bp.packageSetting instanceof PackageSetting)
11685                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
11686                                    scanFlags))) {
11687                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
11688                    } else {
11689                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
11690                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
11691                    }
11692                    if (!sigsOk) {
11693                        // If the owning package is the system itself, we log but allow
11694                        // install to proceed; we fail the install on all other permission
11695                        // redefinitions.
11696                        if (!bp.sourcePackage.equals("android")) {
11697                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
11698                                    + pkg.packageName + " attempting to redeclare permission "
11699                                    + perm.info.name + " already owned by " + bp.sourcePackage);
11700                            res.origPermission = perm.info.name;
11701                            res.origPackage = bp.sourcePackage;
11702                            return;
11703                        } else {
11704                            Slog.w(TAG, "Package " + pkg.packageName
11705                                    + " attempting to redeclare system permission "
11706                                    + perm.info.name + "; ignoring new declaration");
11707                            pkg.permissions.remove(i);
11708                        }
11709                    }
11710                }
11711            }
11712
11713        }
11714
11715        if (systemApp && onExternal) {
11716            // Disable updates to system apps on sdcard
11717            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11718                    "Cannot install updates to system apps on sdcard");
11719            return;
11720        }
11721
11722        if (args.move != null) {
11723            // We did an in-place move, so dex is ready to roll
11724            scanFlags |= SCAN_NO_DEX;
11725            scanFlags |= SCAN_MOVE;
11726        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
11727            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
11728            scanFlags |= SCAN_NO_DEX;
11729
11730            try {
11731                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
11732                        true /* extract libs */);
11733            } catch (PackageManagerException pme) {
11734                Slog.e(TAG, "Error deriving application ABI", pme);
11735                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
11736                return;
11737            }
11738
11739            // Run dexopt before old package gets removed, to minimize time when app is unavailable
11740            int result = mPackageDexOptimizer
11741                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
11742                            false /* defer */, false /* inclDependencies */);
11743            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
11744                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
11745                return;
11746            }
11747        }
11748
11749        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
11750            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
11751            return;
11752        }
11753
11754        startIntentFilterVerifications(args.user.getIdentifier(), pkg);
11755
11756        if (replace) {
11757            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
11758                    installerPackageName, volumeUuid, res);
11759        } else {
11760            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
11761                    args.user, installerPackageName, volumeUuid, res);
11762        }
11763        synchronized (mPackages) {
11764            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11765            if (ps != null) {
11766                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11767            }
11768        }
11769    }
11770
11771    private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) {
11772        if (mIntentFilterVerifierComponent == null) {
11773            Slog.w(TAG, "No IntentFilter verification will not be done as "
11774                    + "there is no IntentFilterVerifier available!");
11775            return;
11776        }
11777
11778        final int verifierUid = getPackageUid(
11779                mIntentFilterVerifierComponent.getPackageName(),
11780                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
11781
11782        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
11783        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
11784        msg.obj = pkg;
11785        msg.arg1 = userId;
11786        msg.arg2 = verifierUid;
11787
11788        mHandler.sendMessage(msg);
11789    }
11790
11791    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid,
11792            PackageParser.Package pkg) {
11793        int size = pkg.activities.size();
11794        if (size == 0) {
11795            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
11796                    "No activity, so no need to verify any IntentFilter!");
11797            return;
11798        }
11799
11800        final boolean hasDomainURLs = hasDomainURLs(pkg);
11801        if (!hasDomainURLs) {
11802            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
11803                    "No domain URLs, so no need to verify any IntentFilter!");
11804            return;
11805        }
11806
11807        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
11808                + " if any IntentFilter from the " + size
11809                + " Activities needs verification ...");
11810
11811        final int verificationId = mIntentFilterVerificationToken++;
11812        int count = 0;
11813        final String packageName = pkg.packageName;
11814        boolean needToVerify = false;
11815
11816        synchronized (mPackages) {
11817            // If any filters need to be verified, then all need to be.
11818            for (PackageParser.Activity a : pkg.activities) {
11819                for (ActivityIntentInfo filter : a.intents) {
11820                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
11821                        if (DEBUG_DOMAIN_VERIFICATION) {
11822                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
11823                        }
11824                        needToVerify = true;
11825                        break;
11826                    }
11827                }
11828            }
11829            if (needToVerify) {
11830                for (PackageParser.Activity a : pkg.activities) {
11831                    for (ActivityIntentInfo filter : a.intents) {
11832                        boolean needsFilterVerification = filter.hasWebDataURI();
11833                        if (needsFilterVerification && needsNetworkVerificationLPr(filter)) {
11834                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
11835                                    "Verification needed for IntentFilter:" + filter.toString());
11836                            mIntentFilterVerifier.addOneIntentFilterVerification(
11837                                    verifierUid, userId, verificationId, filter, packageName);
11838                            count++;
11839                        }
11840                    }
11841                }
11842            }
11843        }
11844
11845        if (count > 0) {
11846            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
11847                    + " IntentFilter verification" + (count > 1 ? "s" : "")
11848                    +  " for userId:" + userId);
11849            mIntentFilterVerifier.startVerifications(userId);
11850        } else {
11851            if (DEBUG_DOMAIN_VERIFICATION) {
11852                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
11853            }
11854        }
11855    }
11856
11857    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
11858        final ComponentName cn  = filter.activity.getComponentName();
11859        final String packageName = cn.getPackageName();
11860
11861        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
11862                packageName);
11863        if (ivi == null) {
11864            return true;
11865        }
11866        int status = ivi.getStatus();
11867        switch (status) {
11868            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
11869            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
11870                return true;
11871
11872            default:
11873                // Nothing to do
11874                return false;
11875        }
11876    }
11877
11878    private boolean isSystemComponentOrPersistentPrivApp(PackageParser.Package pkg) {
11879        return UserHandle.getAppId(pkg.applicationInfo.uid) < FIRST_APPLICATION_UID
11880                || ((pkg.applicationInfo.privateFlags
11881                        & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0
11882                && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0);
11883    }
11884
11885    private static boolean isMultiArch(PackageSetting ps) {
11886        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
11887    }
11888
11889    private static boolean isMultiArch(ApplicationInfo info) {
11890        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
11891    }
11892
11893    private static boolean isExternal(PackageParser.Package pkg) {
11894        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11895    }
11896
11897    private static boolean isExternal(PackageSetting ps) {
11898        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11899    }
11900
11901    private static boolean isExternal(ApplicationInfo info) {
11902        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11903    }
11904
11905    private static boolean isSystemApp(PackageParser.Package pkg) {
11906        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
11907    }
11908
11909    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
11910        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
11911    }
11912
11913    private static boolean hasDomainURLs(PackageParser.Package pkg) {
11914        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
11915    }
11916
11917    private static boolean isSystemApp(PackageSetting ps) {
11918        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
11919    }
11920
11921    private static boolean isUpdatedSystemApp(PackageSetting ps) {
11922        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
11923    }
11924
11925    private int packageFlagsToInstallFlags(PackageSetting ps) {
11926        int installFlags = 0;
11927        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
11928            // This existing package was an external ASEC install when we have
11929            // the external flag without a UUID
11930            installFlags |= PackageManager.INSTALL_EXTERNAL;
11931        }
11932        if (ps.isForwardLocked()) {
11933            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
11934        }
11935        return installFlags;
11936    }
11937
11938    private void deleteTempPackageFiles() {
11939        final FilenameFilter filter = new FilenameFilter() {
11940            public boolean accept(File dir, String name) {
11941                return name.startsWith("vmdl") && name.endsWith(".tmp");
11942            }
11943        };
11944        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
11945            file.delete();
11946        }
11947    }
11948
11949    @Override
11950    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
11951            int flags) {
11952        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
11953                flags);
11954    }
11955
11956    @Override
11957    public void deletePackage(final String packageName,
11958            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
11959        mContext.enforceCallingOrSelfPermission(
11960                android.Manifest.permission.DELETE_PACKAGES, null);
11961        final int uid = Binder.getCallingUid();
11962        if (UserHandle.getUserId(uid) != userId) {
11963            mContext.enforceCallingPermission(
11964                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
11965                    "deletePackage for user " + userId);
11966        }
11967        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
11968            try {
11969                observer.onPackageDeleted(packageName,
11970                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
11971            } catch (RemoteException re) {
11972            }
11973            return;
11974        }
11975
11976        boolean uninstallBlocked = false;
11977        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
11978            int[] users = sUserManager.getUserIds();
11979            for (int i = 0; i < users.length; ++i) {
11980                if (getBlockUninstallForUser(packageName, users[i])) {
11981                    uninstallBlocked = true;
11982                    break;
11983                }
11984            }
11985        } else {
11986            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
11987        }
11988        if (uninstallBlocked) {
11989            try {
11990                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
11991                        null);
11992            } catch (RemoteException re) {
11993            }
11994            return;
11995        }
11996
11997        if (DEBUG_REMOVE) {
11998            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
11999        }
12000        // Queue up an async operation since the package deletion may take a little while.
12001        mHandler.post(new Runnable() {
12002            public void run() {
12003                mHandler.removeCallbacks(this);
12004                final int returnCode = deletePackageX(packageName, userId, flags);
12005                if (observer != null) {
12006                    try {
12007                        observer.onPackageDeleted(packageName, returnCode, null);
12008                    } catch (RemoteException e) {
12009                        Log.i(TAG, "Observer no longer exists.");
12010                    } //end catch
12011                } //end if
12012            } //end run
12013        });
12014    }
12015
12016    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12017        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12018                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12019        try {
12020            if (dpm != null) {
12021                if (dpm.isDeviceOwner(packageName)) {
12022                    return true;
12023                }
12024                int[] users;
12025                if (userId == UserHandle.USER_ALL) {
12026                    users = sUserManager.getUserIds();
12027                } else {
12028                    users = new int[]{userId};
12029                }
12030                for (int i = 0; i < users.length; ++i) {
12031                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12032                        return true;
12033                    }
12034                }
12035            }
12036        } catch (RemoteException e) {
12037        }
12038        return false;
12039    }
12040
12041    /**
12042     *  This method is an internal method that could be get invoked either
12043     *  to delete an installed package or to clean up a failed installation.
12044     *  After deleting an installed package, a broadcast is sent to notify any
12045     *  listeners that the package has been installed. For cleaning up a failed
12046     *  installation, the broadcast is not necessary since the package's
12047     *  installation wouldn't have sent the initial broadcast either
12048     *  The key steps in deleting a package are
12049     *  deleting the package information in internal structures like mPackages,
12050     *  deleting the packages base directories through installd
12051     *  updating mSettings to reflect current status
12052     *  persisting settings for later use
12053     *  sending a broadcast if necessary
12054     */
12055    private int deletePackageX(String packageName, int userId, int flags) {
12056        final PackageRemovedInfo info = new PackageRemovedInfo();
12057        final boolean res;
12058
12059        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12060                ? UserHandle.ALL : new UserHandle(userId);
12061
12062        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12063            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12064            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12065        }
12066
12067        boolean removedForAllUsers = false;
12068        boolean systemUpdate = false;
12069
12070        // for the uninstall-updates case and restricted profiles, remember the per-
12071        // userhandle installed state
12072        int[] allUsers;
12073        boolean[] perUserInstalled;
12074        synchronized (mPackages) {
12075            PackageSetting ps = mSettings.mPackages.get(packageName);
12076            allUsers = sUserManager.getUserIds();
12077            perUserInstalled = new boolean[allUsers.length];
12078            for (int i = 0; i < allUsers.length; i++) {
12079                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12080            }
12081        }
12082
12083        synchronized (mInstallLock) {
12084            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12085            res = deletePackageLI(packageName, removeForUser,
12086                    true, allUsers, perUserInstalled,
12087                    flags | REMOVE_CHATTY, info, true);
12088            systemUpdate = info.isRemovedPackageSystemUpdate;
12089            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12090                removedForAllUsers = true;
12091            }
12092            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12093                    + " removedForAllUsers=" + removedForAllUsers);
12094        }
12095
12096        if (res) {
12097            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12098
12099            // If the removed package was a system update, the old system package
12100            // was re-enabled; we need to broadcast this information
12101            if (systemUpdate) {
12102                Bundle extras = new Bundle(1);
12103                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12104                        ? info.removedAppId : info.uid);
12105                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12106
12107                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12108                        extras, null, null, null);
12109                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12110                        extras, null, null, null);
12111                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12112                        null, packageName, null, null);
12113            }
12114        }
12115        // Force a gc here.
12116        Runtime.getRuntime().gc();
12117        // Delete the resources here after sending the broadcast to let
12118        // other processes clean up before deleting resources.
12119        if (info.args != null) {
12120            synchronized (mInstallLock) {
12121                info.args.doPostDeleteLI(true);
12122            }
12123        }
12124
12125        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12126    }
12127
12128    class PackageRemovedInfo {
12129        String removedPackage;
12130        int uid = -1;
12131        int removedAppId = -1;
12132        int[] removedUsers = null;
12133        boolean isRemovedPackageSystemUpdate = false;
12134        // Clean up resources deleted packages.
12135        InstallArgs args = null;
12136
12137        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12138            Bundle extras = new Bundle(1);
12139            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12140            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12141            if (replacing) {
12142                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12143            }
12144            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12145            if (removedPackage != null) {
12146                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12147                        extras, null, null, removedUsers);
12148                if (fullRemove && !replacing) {
12149                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12150                            extras, null, null, removedUsers);
12151                }
12152            }
12153            if (removedAppId >= 0) {
12154                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12155                        removedUsers);
12156            }
12157        }
12158    }
12159
12160    /*
12161     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12162     * flag is not set, the data directory is removed as well.
12163     * make sure this flag is set for partially installed apps. If not its meaningless to
12164     * delete a partially installed application.
12165     */
12166    private void removePackageDataLI(PackageSetting ps,
12167            int[] allUserHandles, boolean[] perUserInstalled,
12168            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12169        String packageName = ps.name;
12170        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12171        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12172        // Retrieve object to delete permissions for shared user later on
12173        final PackageSetting deletedPs;
12174        // reader
12175        synchronized (mPackages) {
12176            deletedPs = mSettings.mPackages.get(packageName);
12177            if (outInfo != null) {
12178                outInfo.removedPackage = packageName;
12179                outInfo.removedUsers = deletedPs != null
12180                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12181                        : null;
12182            }
12183        }
12184        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12185            removeDataDirsLI(ps.volumeUuid, packageName);
12186            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12187        }
12188        // writer
12189        synchronized (mPackages) {
12190            if (deletedPs != null) {
12191                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12192                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12193                    clearDefaultBrowserIfNeeded(packageName);
12194                    if (outInfo != null) {
12195                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12196                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12197                    }
12198                    updatePermissionsLPw(deletedPs.name, null, 0);
12199                    if (deletedPs.sharedUser != null) {
12200                        // Remove permissions associated with package. Since runtime
12201                        // permissions are per user we have to kill the removed package
12202                        // or packages running under the shared user of the removed
12203                        // package if revoking the permissions requested only by the removed
12204                        // package is successful and this causes a change in gids.
12205                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12206                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12207                                    userId);
12208                            if (userIdToKill == UserHandle.USER_ALL
12209                                    || userIdToKill >= UserHandle.USER_OWNER) {
12210                                // If gids changed for this user, kill all affected packages.
12211                                mHandler.post(new Runnable() {
12212                                    @Override
12213                                    public void run() {
12214                                        // This has to happen with no lock held.
12215                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12216                                                KILL_APP_REASON_GIDS_CHANGED);
12217                                    }
12218                                });
12219                            break;
12220                            }
12221                        }
12222                    }
12223                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12224                }
12225                // make sure to preserve per-user disabled state if this removal was just
12226                // a downgrade of a system app to the factory package
12227                if (allUserHandles != null && perUserInstalled != null) {
12228                    if (DEBUG_REMOVE) {
12229                        Slog.d(TAG, "Propagating install state across downgrade");
12230                    }
12231                    for (int i = 0; i < allUserHandles.length; i++) {
12232                        if (DEBUG_REMOVE) {
12233                            Slog.d(TAG, "    user " + allUserHandles[i]
12234                                    + " => " + perUserInstalled[i]);
12235                        }
12236                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12237                    }
12238                }
12239            }
12240            // can downgrade to reader
12241            if (writeSettings) {
12242                // Save settings now
12243                mSettings.writeLPr();
12244            }
12245        }
12246        if (outInfo != null) {
12247            // A user ID was deleted here. Go through all users and remove it
12248            // from KeyStore.
12249            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12250        }
12251    }
12252
12253    static boolean locationIsPrivileged(File path) {
12254        try {
12255            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12256                    .getCanonicalPath();
12257            return path.getCanonicalPath().startsWith(privilegedAppDir);
12258        } catch (IOException e) {
12259            Slog.e(TAG, "Unable to access code path " + path);
12260        }
12261        return false;
12262    }
12263
12264    /*
12265     * Tries to delete system package.
12266     */
12267    private boolean deleteSystemPackageLI(PackageSetting newPs,
12268            int[] allUserHandles, boolean[] perUserInstalled,
12269            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12270        final boolean applyUserRestrictions
12271                = (allUserHandles != null) && (perUserInstalled != null);
12272        PackageSetting disabledPs = null;
12273        // Confirm if the system package has been updated
12274        // An updated system app can be deleted. This will also have to restore
12275        // the system pkg from system partition
12276        // reader
12277        synchronized (mPackages) {
12278            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12279        }
12280        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12281                + " disabledPs=" + disabledPs);
12282        if (disabledPs == null) {
12283            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12284            return false;
12285        } else if (DEBUG_REMOVE) {
12286            Slog.d(TAG, "Deleting system pkg from data partition");
12287        }
12288        if (DEBUG_REMOVE) {
12289            if (applyUserRestrictions) {
12290                Slog.d(TAG, "Remembering install states:");
12291                for (int i = 0; i < allUserHandles.length; i++) {
12292                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12293                }
12294            }
12295        }
12296        // Delete the updated package
12297        outInfo.isRemovedPackageSystemUpdate = true;
12298        if (disabledPs.versionCode < newPs.versionCode) {
12299            // Delete data for downgrades
12300            flags &= ~PackageManager.DELETE_KEEP_DATA;
12301        } else {
12302            // Preserve data by setting flag
12303            flags |= PackageManager.DELETE_KEEP_DATA;
12304        }
12305        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12306                allUserHandles, perUserInstalled, outInfo, writeSettings);
12307        if (!ret) {
12308            return false;
12309        }
12310        // writer
12311        synchronized (mPackages) {
12312            // Reinstate the old system package
12313            mSettings.enableSystemPackageLPw(newPs.name);
12314            // Remove any native libraries from the upgraded package.
12315            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12316        }
12317        // Install the system package
12318        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12319        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12320        if (locationIsPrivileged(disabledPs.codePath)) {
12321            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12322        }
12323
12324        final PackageParser.Package newPkg;
12325        try {
12326            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12327        } catch (PackageManagerException e) {
12328            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12329            return false;
12330        }
12331
12332        // writer
12333        synchronized (mPackages) {
12334            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12335            updatePermissionsLPw(newPkg.packageName, newPkg,
12336                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12337            if (applyUserRestrictions) {
12338                if (DEBUG_REMOVE) {
12339                    Slog.d(TAG, "Propagating install state across reinstall");
12340                }
12341                for (int i = 0; i < allUserHandles.length; i++) {
12342                    if (DEBUG_REMOVE) {
12343                        Slog.d(TAG, "    user " + allUserHandles[i]
12344                                + " => " + perUserInstalled[i]);
12345                    }
12346                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12347                }
12348                // Regardless of writeSettings we need to ensure that this restriction
12349                // state propagation is persisted
12350                mSettings.writeAllUsersPackageRestrictionsLPr();
12351            }
12352            // can downgrade to reader here
12353            if (writeSettings) {
12354                mSettings.writeLPr();
12355            }
12356        }
12357        return true;
12358    }
12359
12360    private boolean deleteInstalledPackageLI(PackageSetting ps,
12361            boolean deleteCodeAndResources, int flags,
12362            int[] allUserHandles, boolean[] perUserInstalled,
12363            PackageRemovedInfo outInfo, boolean writeSettings) {
12364        if (outInfo != null) {
12365            outInfo.uid = ps.appId;
12366        }
12367
12368        // Delete package data from internal structures and also remove data if flag is set
12369        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12370
12371        // Delete application code and resources
12372        if (deleteCodeAndResources && (outInfo != null)) {
12373            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12374                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12375            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12376        }
12377        return true;
12378    }
12379
12380    @Override
12381    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12382            int userId) {
12383        mContext.enforceCallingOrSelfPermission(
12384                android.Manifest.permission.DELETE_PACKAGES, null);
12385        synchronized (mPackages) {
12386            PackageSetting ps = mSettings.mPackages.get(packageName);
12387            if (ps == null) {
12388                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12389                return false;
12390            }
12391            if (!ps.getInstalled(userId)) {
12392                // Can't block uninstall for an app that is not installed or enabled.
12393                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12394                return false;
12395            }
12396            ps.setBlockUninstall(blockUninstall, userId);
12397            mSettings.writePackageRestrictionsLPr(userId);
12398        }
12399        return true;
12400    }
12401
12402    @Override
12403    public boolean getBlockUninstallForUser(String packageName, int userId) {
12404        synchronized (mPackages) {
12405            PackageSetting ps = mSettings.mPackages.get(packageName);
12406            if (ps == null) {
12407                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
12408                return false;
12409            }
12410            return ps.getBlockUninstall(userId);
12411        }
12412    }
12413
12414    /*
12415     * This method handles package deletion in general
12416     */
12417    private boolean deletePackageLI(String packageName, UserHandle user,
12418            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
12419            int flags, PackageRemovedInfo outInfo,
12420            boolean writeSettings) {
12421        if (packageName == null) {
12422            Slog.w(TAG, "Attempt to delete null packageName.");
12423            return false;
12424        }
12425        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
12426        PackageSetting ps;
12427        boolean dataOnly = false;
12428        int removeUser = -1;
12429        int appId = -1;
12430        synchronized (mPackages) {
12431            ps = mSettings.mPackages.get(packageName);
12432            if (ps == null) {
12433                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12434                return false;
12435            }
12436            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
12437                    && user.getIdentifier() != UserHandle.USER_ALL) {
12438                // The caller is asking that the package only be deleted for a single
12439                // user.  To do this, we just mark its uninstalled state and delete
12440                // its data.  If this is a system app, we only allow this to happen if
12441                // they have set the special DELETE_SYSTEM_APP which requests different
12442                // semantics than normal for uninstalling system apps.
12443                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
12444                ps.setUserState(user.getIdentifier(),
12445                        COMPONENT_ENABLED_STATE_DEFAULT,
12446                        false, //installed
12447                        true,  //stopped
12448                        true,  //notLaunched
12449                        false, //hidden
12450                        null, null, null,
12451                        false, // blockUninstall
12452                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
12453                if (!isSystemApp(ps)) {
12454                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
12455                        // Other user still have this package installed, so all
12456                        // we need to do is clear this user's data and save that
12457                        // it is uninstalled.
12458                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
12459                        removeUser = user.getIdentifier();
12460                        appId = ps.appId;
12461                        scheduleWritePackageRestrictionsLocked(removeUser);
12462                    } else {
12463                        // We need to set it back to 'installed' so the uninstall
12464                        // broadcasts will be sent correctly.
12465                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
12466                        ps.setInstalled(true, user.getIdentifier());
12467                    }
12468                } else {
12469                    // This is a system app, so we assume that the
12470                    // other users still have this package installed, so all
12471                    // we need to do is clear this user's data and save that
12472                    // it is uninstalled.
12473                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
12474                    removeUser = user.getIdentifier();
12475                    appId = ps.appId;
12476                    scheduleWritePackageRestrictionsLocked(removeUser);
12477                }
12478            }
12479        }
12480
12481        if (removeUser >= 0) {
12482            // From above, we determined that we are deleting this only
12483            // for a single user.  Continue the work here.
12484            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
12485            if (outInfo != null) {
12486                outInfo.removedPackage = packageName;
12487                outInfo.removedAppId = appId;
12488                outInfo.removedUsers = new int[] {removeUser};
12489            }
12490            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
12491            removeKeystoreDataIfNeeded(removeUser, appId);
12492            schedulePackageCleaning(packageName, removeUser, false);
12493            synchronized (mPackages) {
12494                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
12495                    scheduleWritePackageRestrictionsLocked(removeUser);
12496                }
12497            }
12498            return true;
12499        }
12500
12501        if (dataOnly) {
12502            // Delete application data first
12503            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
12504            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
12505            return true;
12506        }
12507
12508        boolean ret = false;
12509        if (isSystemApp(ps)) {
12510            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
12511            // When an updated system application is deleted we delete the existing resources as well and
12512            // fall back to existing code in system partition
12513            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
12514                    flags, outInfo, writeSettings);
12515        } else {
12516            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
12517            // Kill application pre-emptively especially for apps on sd.
12518            killApplication(packageName, ps.appId, "uninstall pkg");
12519            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
12520                    allUserHandles, perUserInstalled,
12521                    outInfo, writeSettings);
12522        }
12523
12524        return ret;
12525    }
12526
12527    private final class ClearStorageConnection implements ServiceConnection {
12528        IMediaContainerService mContainerService;
12529
12530        @Override
12531        public void onServiceConnected(ComponentName name, IBinder service) {
12532            synchronized (this) {
12533                mContainerService = IMediaContainerService.Stub.asInterface(service);
12534                notifyAll();
12535            }
12536        }
12537
12538        @Override
12539        public void onServiceDisconnected(ComponentName name) {
12540        }
12541    }
12542
12543    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
12544        final boolean mounted;
12545        if (Environment.isExternalStorageEmulated()) {
12546            mounted = true;
12547        } else {
12548            final String status = Environment.getExternalStorageState();
12549
12550            mounted = status.equals(Environment.MEDIA_MOUNTED)
12551                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
12552        }
12553
12554        if (!mounted) {
12555            return;
12556        }
12557
12558        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
12559        int[] users;
12560        if (userId == UserHandle.USER_ALL) {
12561            users = sUserManager.getUserIds();
12562        } else {
12563            users = new int[] { userId };
12564        }
12565        final ClearStorageConnection conn = new ClearStorageConnection();
12566        if (mContext.bindServiceAsUser(
12567                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
12568            try {
12569                for (int curUser : users) {
12570                    long timeout = SystemClock.uptimeMillis() + 5000;
12571                    synchronized (conn) {
12572                        long now = SystemClock.uptimeMillis();
12573                        while (conn.mContainerService == null && now < timeout) {
12574                            try {
12575                                conn.wait(timeout - now);
12576                            } catch (InterruptedException e) {
12577                            }
12578                        }
12579                    }
12580                    if (conn.mContainerService == null) {
12581                        return;
12582                    }
12583
12584                    final UserEnvironment userEnv = new UserEnvironment(curUser);
12585                    clearDirectory(conn.mContainerService,
12586                            userEnv.buildExternalStorageAppCacheDirs(packageName));
12587                    if (allData) {
12588                        clearDirectory(conn.mContainerService,
12589                                userEnv.buildExternalStorageAppDataDirs(packageName));
12590                        clearDirectory(conn.mContainerService,
12591                                userEnv.buildExternalStorageAppMediaDirs(packageName));
12592                    }
12593                }
12594            } finally {
12595                mContext.unbindService(conn);
12596            }
12597        }
12598    }
12599
12600    @Override
12601    public void clearApplicationUserData(final String packageName,
12602            final IPackageDataObserver observer, final int userId) {
12603        mContext.enforceCallingOrSelfPermission(
12604                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
12605        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
12606        // Queue up an async operation since the package deletion may take a little while.
12607        mHandler.post(new Runnable() {
12608            public void run() {
12609                mHandler.removeCallbacks(this);
12610                final boolean succeeded;
12611                synchronized (mInstallLock) {
12612                    succeeded = clearApplicationUserDataLI(packageName, userId);
12613                }
12614                clearExternalStorageDataSync(packageName, userId, true);
12615                if (succeeded) {
12616                    // invoke DeviceStorageMonitor's update method to clear any notifications
12617                    DeviceStorageMonitorInternal
12618                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
12619                    if (dsm != null) {
12620                        dsm.checkMemory();
12621                    }
12622                }
12623                if(observer != null) {
12624                    try {
12625                        observer.onRemoveCompleted(packageName, succeeded);
12626                    } catch (RemoteException e) {
12627                        Log.i(TAG, "Observer no longer exists.");
12628                    }
12629                } //end if observer
12630            } //end run
12631        });
12632    }
12633
12634    private boolean clearApplicationUserDataLI(String packageName, int userId) {
12635        if (packageName == null) {
12636            Slog.w(TAG, "Attempt to delete null packageName.");
12637            return false;
12638        }
12639
12640        // Try finding details about the requested package
12641        PackageParser.Package pkg;
12642        synchronized (mPackages) {
12643            pkg = mPackages.get(packageName);
12644            if (pkg == null) {
12645                final PackageSetting ps = mSettings.mPackages.get(packageName);
12646                if (ps != null) {
12647                    pkg = ps.pkg;
12648                }
12649            }
12650
12651            if (pkg == null) {
12652                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12653                return false;
12654            }
12655
12656            PackageSetting ps = (PackageSetting) pkg.mExtras;
12657            PermissionsState permissionsState = ps.getPermissionsState();
12658            revokeRuntimePermissionsAndClearUserSetFlagsLocked(permissionsState, userId);
12659        }
12660
12661        // Always delete data directories for package, even if we found no other
12662        // record of app. This helps users recover from UID mismatches without
12663        // resorting to a full data wipe.
12664        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
12665        if (retCode < 0) {
12666            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
12667            return false;
12668        }
12669
12670        final int appId = pkg.applicationInfo.uid;
12671        removeKeystoreDataIfNeeded(userId, appId);
12672
12673        // Create a native library symlink only if we have native libraries
12674        // and if the native libraries are 32 bit libraries. We do not provide
12675        // this symlink for 64 bit libraries.
12676        if (pkg.applicationInfo.primaryCpuAbi != null &&
12677                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
12678            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
12679            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
12680                    nativeLibPath, userId) < 0) {
12681                Slog.w(TAG, "Failed linking native library dir");
12682                return false;
12683            }
12684        }
12685
12686        return true;
12687    }
12688
12689
12690    /**
12691     * Revokes granted runtime permissions and clears resettable flags
12692     * which are flags that can be set by a user interaction.
12693     *
12694     * @param permissionsState The permission state to reset.
12695     * @param userId The device user for which to do a reset.
12696     */
12697    private void revokeRuntimePermissionsAndClearUserSetFlagsLocked(
12698            PermissionsState permissionsState, int userId) {
12699        final int userSetFlags = PackageManager.FLAG_PERMISSION_USER_SET
12700                | PackageManager.FLAG_PERMISSION_USER_FIXED
12701                | PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12702
12703        boolean needsWrite = false;
12704
12705        for (PermissionState state : permissionsState.getRuntimePermissionStates(userId)) {
12706            BasePermission bp = mSettings.mPermissions.get(state.getName());
12707            if (bp != null) {
12708                permissionsState.revokeRuntimePermission(bp, userId);
12709                permissionsState.updatePermissionFlags(bp, userId, userSetFlags, 0);
12710                needsWrite = true;
12711            }
12712        }
12713
12714        if (needsWrite) {
12715            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
12716        }
12717    }
12718
12719    /**
12720     * Remove entries from the keystore daemon. Will only remove it if the
12721     * {@code appId} is valid.
12722     */
12723    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
12724        if (appId < 0) {
12725            return;
12726        }
12727
12728        final KeyStore keyStore = KeyStore.getInstance();
12729        if (keyStore != null) {
12730            if (userId == UserHandle.USER_ALL) {
12731                for (final int individual : sUserManager.getUserIds()) {
12732                    keyStore.clearUid(UserHandle.getUid(individual, appId));
12733                }
12734            } else {
12735                keyStore.clearUid(UserHandle.getUid(userId, appId));
12736            }
12737        } else {
12738            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
12739        }
12740    }
12741
12742    @Override
12743    public void deleteApplicationCacheFiles(final String packageName,
12744            final IPackageDataObserver observer) {
12745        mContext.enforceCallingOrSelfPermission(
12746                android.Manifest.permission.DELETE_CACHE_FILES, null);
12747        // Queue up an async operation since the package deletion may take a little while.
12748        final int userId = UserHandle.getCallingUserId();
12749        mHandler.post(new Runnable() {
12750            public void run() {
12751                mHandler.removeCallbacks(this);
12752                final boolean succeded;
12753                synchronized (mInstallLock) {
12754                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
12755                }
12756                clearExternalStorageDataSync(packageName, userId, false);
12757                if (observer != null) {
12758                    try {
12759                        observer.onRemoveCompleted(packageName, succeded);
12760                    } catch (RemoteException e) {
12761                        Log.i(TAG, "Observer no longer exists.");
12762                    }
12763                } //end if observer
12764            } //end run
12765        });
12766    }
12767
12768    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
12769        if (packageName == null) {
12770            Slog.w(TAG, "Attempt to delete null packageName.");
12771            return false;
12772        }
12773        PackageParser.Package p;
12774        synchronized (mPackages) {
12775            p = mPackages.get(packageName);
12776        }
12777        if (p == null) {
12778            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12779            return false;
12780        }
12781        final ApplicationInfo applicationInfo = p.applicationInfo;
12782        if (applicationInfo == null) {
12783            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12784            return false;
12785        }
12786        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
12787        if (retCode < 0) {
12788            Slog.w(TAG, "Couldn't remove cache files for package: "
12789                       + packageName + " u" + userId);
12790            return false;
12791        }
12792        return true;
12793    }
12794
12795    @Override
12796    public void getPackageSizeInfo(final String packageName, int userHandle,
12797            final IPackageStatsObserver observer) {
12798        mContext.enforceCallingOrSelfPermission(
12799                android.Manifest.permission.GET_PACKAGE_SIZE, null);
12800        if (packageName == null) {
12801            throw new IllegalArgumentException("Attempt to get size of null packageName");
12802        }
12803
12804        PackageStats stats = new PackageStats(packageName, userHandle);
12805
12806        /*
12807         * Queue up an async operation since the package measurement may take a
12808         * little while.
12809         */
12810        Message msg = mHandler.obtainMessage(INIT_COPY);
12811        msg.obj = new MeasureParams(stats, observer);
12812        mHandler.sendMessage(msg);
12813    }
12814
12815    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
12816            PackageStats pStats) {
12817        if (packageName == null) {
12818            Slog.w(TAG, "Attempt to get size of null packageName.");
12819            return false;
12820        }
12821        PackageParser.Package p;
12822        boolean dataOnly = false;
12823        String libDirRoot = null;
12824        String asecPath = null;
12825        PackageSetting ps = null;
12826        synchronized (mPackages) {
12827            p = mPackages.get(packageName);
12828            ps = mSettings.mPackages.get(packageName);
12829            if(p == null) {
12830                dataOnly = true;
12831                if((ps == null) || (ps.pkg == null)) {
12832                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12833                    return false;
12834                }
12835                p = ps.pkg;
12836            }
12837            if (ps != null) {
12838                libDirRoot = ps.legacyNativeLibraryPathString;
12839            }
12840            if (p != null && (isExternal(p) || p.isForwardLocked())) {
12841                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
12842                if (secureContainerId != null) {
12843                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
12844                }
12845            }
12846        }
12847        String publicSrcDir = null;
12848        if(!dataOnly) {
12849            final ApplicationInfo applicationInfo = p.applicationInfo;
12850            if (applicationInfo == null) {
12851                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12852                return false;
12853            }
12854            if (p.isForwardLocked()) {
12855                publicSrcDir = applicationInfo.getBaseResourcePath();
12856            }
12857        }
12858        // TODO: extend to measure size of split APKs
12859        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
12860        // not just the first level.
12861        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
12862        // just the primary.
12863        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
12864        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
12865                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
12866        if (res < 0) {
12867            return false;
12868        }
12869
12870        // Fix-up for forward-locked applications in ASEC containers.
12871        if (!isExternal(p)) {
12872            pStats.codeSize += pStats.externalCodeSize;
12873            pStats.externalCodeSize = 0L;
12874        }
12875
12876        return true;
12877    }
12878
12879
12880    @Override
12881    public void addPackageToPreferred(String packageName) {
12882        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
12883    }
12884
12885    @Override
12886    public void removePackageFromPreferred(String packageName) {
12887        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
12888    }
12889
12890    @Override
12891    public List<PackageInfo> getPreferredPackages(int flags) {
12892        return new ArrayList<PackageInfo>();
12893    }
12894
12895    private int getUidTargetSdkVersionLockedLPr(int uid) {
12896        Object obj = mSettings.getUserIdLPr(uid);
12897        if (obj instanceof SharedUserSetting) {
12898            final SharedUserSetting sus = (SharedUserSetting) obj;
12899            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
12900            final Iterator<PackageSetting> it = sus.packages.iterator();
12901            while (it.hasNext()) {
12902                final PackageSetting ps = it.next();
12903                if (ps.pkg != null) {
12904                    int v = ps.pkg.applicationInfo.targetSdkVersion;
12905                    if (v < vers) vers = v;
12906                }
12907            }
12908            return vers;
12909        } else if (obj instanceof PackageSetting) {
12910            final PackageSetting ps = (PackageSetting) obj;
12911            if (ps.pkg != null) {
12912                return ps.pkg.applicationInfo.targetSdkVersion;
12913            }
12914        }
12915        return Build.VERSION_CODES.CUR_DEVELOPMENT;
12916    }
12917
12918    @Override
12919    public void addPreferredActivity(IntentFilter filter, int match,
12920            ComponentName[] set, ComponentName activity, int userId) {
12921        addPreferredActivityInternal(filter, match, set, activity, true, userId,
12922                "Adding preferred");
12923    }
12924
12925    private void addPreferredActivityInternal(IntentFilter filter, int match,
12926            ComponentName[] set, ComponentName activity, boolean always, int userId,
12927            String opname) {
12928        // writer
12929        int callingUid = Binder.getCallingUid();
12930        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
12931        if (filter.countActions() == 0) {
12932            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
12933            return;
12934        }
12935        synchronized (mPackages) {
12936            if (mContext.checkCallingOrSelfPermission(
12937                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12938                    != PackageManager.PERMISSION_GRANTED) {
12939                if (getUidTargetSdkVersionLockedLPr(callingUid)
12940                        < Build.VERSION_CODES.FROYO) {
12941                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
12942                            + callingUid);
12943                    return;
12944                }
12945                mContext.enforceCallingOrSelfPermission(
12946                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12947            }
12948
12949            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
12950            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
12951                    + userId + ":");
12952            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12953            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
12954            scheduleWritePackageRestrictionsLocked(userId);
12955        }
12956    }
12957
12958    @Override
12959    public void replacePreferredActivity(IntentFilter filter, int match,
12960            ComponentName[] set, ComponentName activity, int userId) {
12961        if (filter.countActions() != 1) {
12962            throw new IllegalArgumentException(
12963                    "replacePreferredActivity expects filter to have only 1 action.");
12964        }
12965        if (filter.countDataAuthorities() != 0
12966                || filter.countDataPaths() != 0
12967                || filter.countDataSchemes() > 1
12968                || filter.countDataTypes() != 0) {
12969            throw new IllegalArgumentException(
12970                    "replacePreferredActivity expects filter to have no data authorities, " +
12971                    "paths, or types; and at most one scheme.");
12972        }
12973
12974        final int callingUid = Binder.getCallingUid();
12975        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
12976        synchronized (mPackages) {
12977            if (mContext.checkCallingOrSelfPermission(
12978                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12979                    != PackageManager.PERMISSION_GRANTED) {
12980                if (getUidTargetSdkVersionLockedLPr(callingUid)
12981                        < Build.VERSION_CODES.FROYO) {
12982                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
12983                            + Binder.getCallingUid());
12984                    return;
12985                }
12986                mContext.enforceCallingOrSelfPermission(
12987                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12988            }
12989
12990            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
12991            if (pir != null) {
12992                // Get all of the existing entries that exactly match this filter.
12993                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
12994                if (existing != null && existing.size() == 1) {
12995                    PreferredActivity cur = existing.get(0);
12996                    if (DEBUG_PREFERRED) {
12997                        Slog.i(TAG, "Checking replace of preferred:");
12998                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12999                        if (!cur.mPref.mAlways) {
13000                            Slog.i(TAG, "  -- CUR; not mAlways!");
13001                        } else {
13002                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13003                            Slog.i(TAG, "  -- CUR: mSet="
13004                                    + Arrays.toString(cur.mPref.mSetComponents));
13005                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13006                            Slog.i(TAG, "  -- NEW: mMatch="
13007                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13008                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13009                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13010                        }
13011                    }
13012                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13013                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13014                            && cur.mPref.sameSet(set)) {
13015                        // Setting the preferred activity to what it happens to be already
13016                        if (DEBUG_PREFERRED) {
13017                            Slog.i(TAG, "Replacing with same preferred activity "
13018                                    + cur.mPref.mShortComponent + " for user "
13019                                    + userId + ":");
13020                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13021                        }
13022                        return;
13023                    }
13024                }
13025
13026                if (existing != null) {
13027                    if (DEBUG_PREFERRED) {
13028                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13029                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13030                    }
13031                    for (int i = 0; i < existing.size(); i++) {
13032                        PreferredActivity pa = existing.get(i);
13033                        if (DEBUG_PREFERRED) {
13034                            Slog.i(TAG, "Removing existing preferred activity "
13035                                    + pa.mPref.mComponent + ":");
13036                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13037                        }
13038                        pir.removeFilter(pa);
13039                    }
13040                }
13041            }
13042            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13043                    "Replacing preferred");
13044        }
13045    }
13046
13047    @Override
13048    public void clearPackagePreferredActivities(String packageName) {
13049        final int uid = Binder.getCallingUid();
13050        // writer
13051        synchronized (mPackages) {
13052            PackageParser.Package pkg = mPackages.get(packageName);
13053            if (pkg == null || pkg.applicationInfo.uid != uid) {
13054                if (mContext.checkCallingOrSelfPermission(
13055                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13056                        != PackageManager.PERMISSION_GRANTED) {
13057                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13058                            < Build.VERSION_CODES.FROYO) {
13059                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13060                                + Binder.getCallingUid());
13061                        return;
13062                    }
13063                    mContext.enforceCallingOrSelfPermission(
13064                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13065                }
13066            }
13067
13068            int user = UserHandle.getCallingUserId();
13069            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13070                scheduleWritePackageRestrictionsLocked(user);
13071            }
13072        }
13073    }
13074
13075    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13076    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13077        ArrayList<PreferredActivity> removed = null;
13078        boolean changed = false;
13079        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13080            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13081            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13082            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13083                continue;
13084            }
13085            Iterator<PreferredActivity> it = pir.filterIterator();
13086            while (it.hasNext()) {
13087                PreferredActivity pa = it.next();
13088                // Mark entry for removal only if it matches the package name
13089                // and the entry is of type "always".
13090                if (packageName == null ||
13091                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13092                                && pa.mPref.mAlways)) {
13093                    if (removed == null) {
13094                        removed = new ArrayList<PreferredActivity>();
13095                    }
13096                    removed.add(pa);
13097                }
13098            }
13099            if (removed != null) {
13100                for (int j=0; j<removed.size(); j++) {
13101                    PreferredActivity pa = removed.get(j);
13102                    pir.removeFilter(pa);
13103                }
13104                changed = true;
13105            }
13106        }
13107        return changed;
13108    }
13109
13110    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13111    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13112        if (userId == UserHandle.USER_ALL) {
13113            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13114                    sUserManager.getUserIds())) {
13115                for (int oneUserId : sUserManager.getUserIds()) {
13116                    scheduleWritePackageRestrictionsLocked(oneUserId);
13117                }
13118            }
13119        } else {
13120            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13121                scheduleWritePackageRestrictionsLocked(userId);
13122            }
13123        }
13124    }
13125
13126
13127    void clearDefaultBrowserIfNeeded(String packageName) {
13128        for (int oneUserId : sUserManager.getUserIds()) {
13129            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13130            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13131            if (packageName.equals(defaultBrowserPackageName)) {
13132                setDefaultBrowserPackageName(null, oneUserId);
13133            }
13134        }
13135    }
13136
13137    @Override
13138    public void resetPreferredActivities(int userId) {
13139        /* TODO: Actually use userId. Why is it being passed in? */
13140        mContext.enforceCallingOrSelfPermission(
13141                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13142        // writer
13143        synchronized (mPackages) {
13144            int user = UserHandle.getCallingUserId();
13145            clearPackagePreferredActivitiesLPw(null, user);
13146            mSettings.readDefaultPreferredAppsLPw(this, user);
13147            scheduleWritePackageRestrictionsLocked(user);
13148        }
13149    }
13150
13151    @Override
13152    public int getPreferredActivities(List<IntentFilter> outFilters,
13153            List<ComponentName> outActivities, String packageName) {
13154
13155        int num = 0;
13156        final int userId = UserHandle.getCallingUserId();
13157        // reader
13158        synchronized (mPackages) {
13159            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13160            if (pir != null) {
13161                final Iterator<PreferredActivity> it = pir.filterIterator();
13162                while (it.hasNext()) {
13163                    final PreferredActivity pa = it.next();
13164                    if (packageName == null
13165                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13166                                    && pa.mPref.mAlways)) {
13167                        if (outFilters != null) {
13168                            outFilters.add(new IntentFilter(pa));
13169                        }
13170                        if (outActivities != null) {
13171                            outActivities.add(pa.mPref.mComponent);
13172                        }
13173                    }
13174                }
13175            }
13176        }
13177
13178        return num;
13179    }
13180
13181    @Override
13182    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13183            int userId) {
13184        int callingUid = Binder.getCallingUid();
13185        if (callingUid != Process.SYSTEM_UID) {
13186            throw new SecurityException(
13187                    "addPersistentPreferredActivity can only be run by the system");
13188        }
13189        if (filter.countActions() == 0) {
13190            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13191            return;
13192        }
13193        synchronized (mPackages) {
13194            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13195                    " :");
13196            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13197            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13198                    new PersistentPreferredActivity(filter, activity));
13199            scheduleWritePackageRestrictionsLocked(userId);
13200        }
13201    }
13202
13203    @Override
13204    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13205        int callingUid = Binder.getCallingUid();
13206        if (callingUid != Process.SYSTEM_UID) {
13207            throw new SecurityException(
13208                    "clearPackagePersistentPreferredActivities can only be run by the system");
13209        }
13210        ArrayList<PersistentPreferredActivity> removed = null;
13211        boolean changed = false;
13212        synchronized (mPackages) {
13213            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13214                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13215                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13216                        .valueAt(i);
13217                if (userId != thisUserId) {
13218                    continue;
13219                }
13220                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13221                while (it.hasNext()) {
13222                    PersistentPreferredActivity ppa = it.next();
13223                    // Mark entry for removal only if it matches the package name.
13224                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13225                        if (removed == null) {
13226                            removed = new ArrayList<PersistentPreferredActivity>();
13227                        }
13228                        removed.add(ppa);
13229                    }
13230                }
13231                if (removed != null) {
13232                    for (int j=0; j<removed.size(); j++) {
13233                        PersistentPreferredActivity ppa = removed.get(j);
13234                        ppir.removeFilter(ppa);
13235                    }
13236                    changed = true;
13237                }
13238            }
13239
13240            if (changed) {
13241                scheduleWritePackageRestrictionsLocked(userId);
13242            }
13243        }
13244    }
13245
13246    /**
13247     * Non-Binder method, support for the backup/restore mechanism: write the
13248     * full set of preferred activities in its canonical XML format.  Returns true
13249     * on success; false otherwise.
13250     */
13251    @Override
13252    public byte[] getPreferredActivityBackup(int userId) {
13253        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13254            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13255        }
13256
13257        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13258        try {
13259            final XmlSerializer serializer = new FastXmlSerializer();
13260            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13261            serializer.startDocument(null, true);
13262            serializer.startTag(null, TAG_PREFERRED_BACKUP);
13263
13264            synchronized (mPackages) {
13265                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13266            }
13267
13268            serializer.endTag(null, TAG_PREFERRED_BACKUP);
13269            serializer.endDocument();
13270            serializer.flush();
13271        } catch (Exception e) {
13272            if (DEBUG_BACKUP) {
13273                Slog.e(TAG, "Unable to write preferred activities for backup", e);
13274            }
13275            return null;
13276        }
13277
13278        return dataStream.toByteArray();
13279    }
13280
13281    @Override
13282    public void restorePreferredActivities(byte[] backup, int userId) {
13283        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13284            throw new SecurityException("Only the system may call restorePreferredActivities()");
13285        }
13286
13287        try {
13288            final XmlPullParser parser = Xml.newPullParser();
13289            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13290
13291            int type;
13292            while ((type = parser.next()) != XmlPullParser.START_TAG
13293                    && type != XmlPullParser.END_DOCUMENT) {
13294            }
13295            if (type != XmlPullParser.START_TAG) {
13296                // oops didn't find a start tag?!
13297                if (DEBUG_BACKUP) {
13298                    Slog.e(TAG, "Didn't find start tag during restore");
13299                }
13300                return;
13301            }
13302
13303            // this is supposed to be TAG_PREFERRED_BACKUP
13304            if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) {
13305                if (DEBUG_BACKUP) {
13306                    Slog.e(TAG, "Found unexpected tag " + parser.getName());
13307                }
13308                return;
13309            }
13310
13311            // skip interfering stuff, then we're aligned with the backing implementation
13312            while ((type = parser.next()) == XmlPullParser.TEXT) { }
13313            synchronized (mPackages) {
13314                mSettings.readPreferredActivitiesLPw(parser, userId);
13315            }
13316        } catch (Exception e) {
13317            if (DEBUG_BACKUP) {
13318                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13319            }
13320        }
13321    }
13322
13323    @Override
13324    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
13325            int sourceUserId, int targetUserId, int flags) {
13326        mContext.enforceCallingOrSelfPermission(
13327                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13328        int callingUid = Binder.getCallingUid();
13329        enforceOwnerRights(ownerPackage, callingUid);
13330        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13331        if (intentFilter.countActions() == 0) {
13332            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
13333            return;
13334        }
13335        synchronized (mPackages) {
13336            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
13337                    ownerPackage, targetUserId, flags);
13338            CrossProfileIntentResolver resolver =
13339                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13340            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
13341            // We have all those whose filter is equal. Now checking if the rest is equal as well.
13342            if (existing != null) {
13343                int size = existing.size();
13344                for (int i = 0; i < size; i++) {
13345                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
13346                        return;
13347                    }
13348                }
13349            }
13350            resolver.addFilter(newFilter);
13351            scheduleWritePackageRestrictionsLocked(sourceUserId);
13352        }
13353    }
13354
13355    @Override
13356    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
13357        mContext.enforceCallingOrSelfPermission(
13358                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13359        int callingUid = Binder.getCallingUid();
13360        enforceOwnerRights(ownerPackage, callingUid);
13361        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13362        synchronized (mPackages) {
13363            CrossProfileIntentResolver resolver =
13364                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13365            ArraySet<CrossProfileIntentFilter> set =
13366                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
13367            for (CrossProfileIntentFilter filter : set) {
13368                if (filter.getOwnerPackage().equals(ownerPackage)) {
13369                    resolver.removeFilter(filter);
13370                }
13371            }
13372            scheduleWritePackageRestrictionsLocked(sourceUserId);
13373        }
13374    }
13375
13376    // Enforcing that callingUid is owning pkg on userId
13377    private void enforceOwnerRights(String pkg, int callingUid) {
13378        // The system owns everything.
13379        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
13380            return;
13381        }
13382        int callingUserId = UserHandle.getUserId(callingUid);
13383        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
13384        if (pi == null) {
13385            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
13386                    + callingUserId);
13387        }
13388        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
13389            throw new SecurityException("Calling uid " + callingUid
13390                    + " does not own package " + pkg);
13391        }
13392    }
13393
13394    @Override
13395    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
13396        Intent intent = new Intent(Intent.ACTION_MAIN);
13397        intent.addCategory(Intent.CATEGORY_HOME);
13398
13399        final int callingUserId = UserHandle.getCallingUserId();
13400        List<ResolveInfo> list = queryIntentActivities(intent, null,
13401                PackageManager.GET_META_DATA, callingUserId);
13402        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
13403                true, false, false, callingUserId);
13404
13405        allHomeCandidates.clear();
13406        if (list != null) {
13407            for (ResolveInfo ri : list) {
13408                allHomeCandidates.add(ri);
13409            }
13410        }
13411        return (preferred == null || preferred.activityInfo == null)
13412                ? null
13413                : new ComponentName(preferred.activityInfo.packageName,
13414                        preferred.activityInfo.name);
13415    }
13416
13417    @Override
13418    public void setApplicationEnabledSetting(String appPackageName,
13419            int newState, int flags, int userId, String callingPackage) {
13420        if (!sUserManager.exists(userId)) return;
13421        if (callingPackage == null) {
13422            callingPackage = Integer.toString(Binder.getCallingUid());
13423        }
13424        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
13425    }
13426
13427    @Override
13428    public void setComponentEnabledSetting(ComponentName componentName,
13429            int newState, int flags, int userId) {
13430        if (!sUserManager.exists(userId)) return;
13431        setEnabledSetting(componentName.getPackageName(),
13432                componentName.getClassName(), newState, flags, userId, null);
13433    }
13434
13435    private void setEnabledSetting(final String packageName, String className, int newState,
13436            final int flags, int userId, String callingPackage) {
13437        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
13438              || newState == COMPONENT_ENABLED_STATE_ENABLED
13439              || newState == COMPONENT_ENABLED_STATE_DISABLED
13440              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
13441              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
13442            throw new IllegalArgumentException("Invalid new component state: "
13443                    + newState);
13444        }
13445        PackageSetting pkgSetting;
13446        final int uid = Binder.getCallingUid();
13447        final int permission = mContext.checkCallingOrSelfPermission(
13448                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13449        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
13450        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13451        boolean sendNow = false;
13452        boolean isApp = (className == null);
13453        String componentName = isApp ? packageName : className;
13454        int packageUid = -1;
13455        ArrayList<String> components;
13456
13457        // writer
13458        synchronized (mPackages) {
13459            pkgSetting = mSettings.mPackages.get(packageName);
13460            if (pkgSetting == null) {
13461                if (className == null) {
13462                    throw new IllegalArgumentException(
13463                            "Unknown package: " + packageName);
13464                }
13465                throw new IllegalArgumentException(
13466                        "Unknown component: " + packageName
13467                        + "/" + className);
13468            }
13469            // Allow root and verify that userId is not being specified by a different user
13470            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
13471                throw new SecurityException(
13472                        "Permission Denial: attempt to change component state from pid="
13473                        + Binder.getCallingPid()
13474                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
13475            }
13476            if (className == null) {
13477                // We're dealing with an application/package level state change
13478                if (pkgSetting.getEnabled(userId) == newState) {
13479                    // Nothing to do
13480                    return;
13481                }
13482                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
13483                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
13484                    // Don't care about who enables an app.
13485                    callingPackage = null;
13486                }
13487                pkgSetting.setEnabled(newState, userId, callingPackage);
13488                // pkgSetting.pkg.mSetEnabled = newState;
13489            } else {
13490                // We're dealing with a component level state change
13491                // First, verify that this is a valid class name.
13492                PackageParser.Package pkg = pkgSetting.pkg;
13493                if (pkg == null || !pkg.hasComponentClassName(className)) {
13494                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
13495                        throw new IllegalArgumentException("Component class " + className
13496                                + " does not exist in " + packageName);
13497                    } else {
13498                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
13499                                + className + " does not exist in " + packageName);
13500                    }
13501                }
13502                switch (newState) {
13503                case COMPONENT_ENABLED_STATE_ENABLED:
13504                    if (!pkgSetting.enableComponentLPw(className, userId)) {
13505                        return;
13506                    }
13507                    break;
13508                case COMPONENT_ENABLED_STATE_DISABLED:
13509                    if (!pkgSetting.disableComponentLPw(className, userId)) {
13510                        return;
13511                    }
13512                    break;
13513                case COMPONENT_ENABLED_STATE_DEFAULT:
13514                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
13515                        return;
13516                    }
13517                    break;
13518                default:
13519                    Slog.e(TAG, "Invalid new component state: " + newState);
13520                    return;
13521                }
13522            }
13523            scheduleWritePackageRestrictionsLocked(userId);
13524            components = mPendingBroadcasts.get(userId, packageName);
13525            final boolean newPackage = components == null;
13526            if (newPackage) {
13527                components = new ArrayList<String>();
13528            }
13529            if (!components.contains(componentName)) {
13530                components.add(componentName);
13531            }
13532            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
13533                sendNow = true;
13534                // Purge entry from pending broadcast list if another one exists already
13535                // since we are sending one right away.
13536                mPendingBroadcasts.remove(userId, packageName);
13537            } else {
13538                if (newPackage) {
13539                    mPendingBroadcasts.put(userId, packageName, components);
13540                }
13541                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
13542                    // Schedule a message
13543                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
13544                }
13545            }
13546        }
13547
13548        long callingId = Binder.clearCallingIdentity();
13549        try {
13550            if (sendNow) {
13551                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
13552                sendPackageChangedBroadcast(packageName,
13553                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
13554            }
13555        } finally {
13556            Binder.restoreCallingIdentity(callingId);
13557        }
13558    }
13559
13560    private void sendPackageChangedBroadcast(String packageName,
13561            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
13562        if (DEBUG_INSTALL)
13563            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
13564                    + componentNames);
13565        Bundle extras = new Bundle(4);
13566        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
13567        String nameList[] = new String[componentNames.size()];
13568        componentNames.toArray(nameList);
13569        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
13570        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
13571        extras.putInt(Intent.EXTRA_UID, packageUid);
13572        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
13573                new int[] {UserHandle.getUserId(packageUid)});
13574    }
13575
13576    @Override
13577    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
13578        if (!sUserManager.exists(userId)) return;
13579        final int uid = Binder.getCallingUid();
13580        final int permission = mContext.checkCallingOrSelfPermission(
13581                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13582        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13583        enforceCrossUserPermission(uid, userId, true, true, "stop package");
13584        // writer
13585        synchronized (mPackages) {
13586            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
13587                    allowedByPermission, uid, userId)) {
13588                scheduleWritePackageRestrictionsLocked(userId);
13589            }
13590        }
13591    }
13592
13593    @Override
13594    public String getInstallerPackageName(String packageName) {
13595        // reader
13596        synchronized (mPackages) {
13597            return mSettings.getInstallerPackageNameLPr(packageName);
13598        }
13599    }
13600
13601    @Override
13602    public int getApplicationEnabledSetting(String packageName, int userId) {
13603        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13604        int uid = Binder.getCallingUid();
13605        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
13606        // reader
13607        synchronized (mPackages) {
13608            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
13609        }
13610    }
13611
13612    @Override
13613    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
13614        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13615        int uid = Binder.getCallingUid();
13616        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
13617        // reader
13618        synchronized (mPackages) {
13619            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
13620        }
13621    }
13622
13623    @Override
13624    public void enterSafeMode() {
13625        enforceSystemOrRoot("Only the system can request entering safe mode");
13626
13627        if (!mSystemReady) {
13628            mSafeMode = true;
13629        }
13630    }
13631
13632    @Override
13633    public void systemReady() {
13634        mSystemReady = true;
13635
13636        // Read the compatibilty setting when the system is ready.
13637        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
13638                mContext.getContentResolver(),
13639                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
13640        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
13641        if (DEBUG_SETTINGS) {
13642            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
13643        }
13644
13645        synchronized (mPackages) {
13646            // Verify that all of the preferred activity components actually
13647            // exist.  It is possible for applications to be updated and at
13648            // that point remove a previously declared activity component that
13649            // had been set as a preferred activity.  We try to clean this up
13650            // the next time we encounter that preferred activity, but it is
13651            // possible for the user flow to never be able to return to that
13652            // situation so here we do a sanity check to make sure we haven't
13653            // left any junk around.
13654            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
13655            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13656                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13657                removed.clear();
13658                for (PreferredActivity pa : pir.filterSet()) {
13659                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
13660                        removed.add(pa);
13661                    }
13662                }
13663                if (removed.size() > 0) {
13664                    for (int r=0; r<removed.size(); r++) {
13665                        PreferredActivity pa = removed.get(r);
13666                        Slog.w(TAG, "Removing dangling preferred activity: "
13667                                + pa.mPref.mComponent);
13668                        pir.removeFilter(pa);
13669                    }
13670                    mSettings.writePackageRestrictionsLPr(
13671                            mSettings.mPreferredActivities.keyAt(i));
13672                }
13673            }
13674        }
13675        sUserManager.systemReady();
13676
13677        // Kick off any messages waiting for system ready
13678        if (mPostSystemReadyMessages != null) {
13679            for (Message msg : mPostSystemReadyMessages) {
13680                msg.sendToTarget();
13681            }
13682            mPostSystemReadyMessages = null;
13683        }
13684
13685        // Watch for external volumes that come and go over time
13686        final StorageManager storage = mContext.getSystemService(StorageManager.class);
13687        storage.registerListener(mStorageListener);
13688
13689        mInstallerService.systemReady();
13690        mPackageDexOptimizer.systemReady();
13691    }
13692
13693    @Override
13694    public boolean isSafeMode() {
13695        return mSafeMode;
13696    }
13697
13698    @Override
13699    public boolean hasSystemUidErrors() {
13700        return mHasSystemUidErrors;
13701    }
13702
13703    static String arrayToString(int[] array) {
13704        StringBuffer buf = new StringBuffer(128);
13705        buf.append('[');
13706        if (array != null) {
13707            for (int i=0; i<array.length; i++) {
13708                if (i > 0) buf.append(", ");
13709                buf.append(array[i]);
13710            }
13711        }
13712        buf.append(']');
13713        return buf.toString();
13714    }
13715
13716    static class DumpState {
13717        public static final int DUMP_LIBS = 1 << 0;
13718        public static final int DUMP_FEATURES = 1 << 1;
13719        public static final int DUMP_RESOLVERS = 1 << 2;
13720        public static final int DUMP_PERMISSIONS = 1 << 3;
13721        public static final int DUMP_PACKAGES = 1 << 4;
13722        public static final int DUMP_SHARED_USERS = 1 << 5;
13723        public static final int DUMP_MESSAGES = 1 << 6;
13724        public static final int DUMP_PROVIDERS = 1 << 7;
13725        public static final int DUMP_VERIFIERS = 1 << 8;
13726        public static final int DUMP_PREFERRED = 1 << 9;
13727        public static final int DUMP_PREFERRED_XML = 1 << 10;
13728        public static final int DUMP_KEYSETS = 1 << 11;
13729        public static final int DUMP_VERSION = 1 << 12;
13730        public static final int DUMP_INSTALLS = 1 << 13;
13731        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
13732        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
13733
13734        public static final int OPTION_SHOW_FILTERS = 1 << 0;
13735
13736        private int mTypes;
13737
13738        private int mOptions;
13739
13740        private boolean mTitlePrinted;
13741
13742        private SharedUserSetting mSharedUser;
13743
13744        public boolean isDumping(int type) {
13745            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
13746                return true;
13747            }
13748
13749            return (mTypes & type) != 0;
13750        }
13751
13752        public void setDump(int type) {
13753            mTypes |= type;
13754        }
13755
13756        public boolean isOptionEnabled(int option) {
13757            return (mOptions & option) != 0;
13758        }
13759
13760        public void setOptionEnabled(int option) {
13761            mOptions |= option;
13762        }
13763
13764        public boolean onTitlePrinted() {
13765            final boolean printed = mTitlePrinted;
13766            mTitlePrinted = true;
13767            return printed;
13768        }
13769
13770        public boolean getTitlePrinted() {
13771            return mTitlePrinted;
13772        }
13773
13774        public void setTitlePrinted(boolean enabled) {
13775            mTitlePrinted = enabled;
13776        }
13777
13778        public SharedUserSetting getSharedUser() {
13779            return mSharedUser;
13780        }
13781
13782        public void setSharedUser(SharedUserSetting user) {
13783            mSharedUser = user;
13784        }
13785    }
13786
13787    @Override
13788    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
13789        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
13790                != PackageManager.PERMISSION_GRANTED) {
13791            pw.println("Permission Denial: can't dump ActivityManager from from pid="
13792                    + Binder.getCallingPid()
13793                    + ", uid=" + Binder.getCallingUid()
13794                    + " without permission "
13795                    + android.Manifest.permission.DUMP);
13796            return;
13797        }
13798
13799        DumpState dumpState = new DumpState();
13800        boolean fullPreferred = false;
13801        boolean checkin = false;
13802
13803        String packageName = null;
13804
13805        int opti = 0;
13806        while (opti < args.length) {
13807            String opt = args[opti];
13808            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
13809                break;
13810            }
13811            opti++;
13812
13813            if ("-a".equals(opt)) {
13814                // Right now we only know how to print all.
13815            } else if ("-h".equals(opt)) {
13816                pw.println("Package manager dump options:");
13817                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
13818                pw.println("    --checkin: dump for a checkin");
13819                pw.println("    -f: print details of intent filters");
13820                pw.println("    -h: print this help");
13821                pw.println("  cmd may be one of:");
13822                pw.println("    l[ibraries]: list known shared libraries");
13823                pw.println("    f[ibraries]: list device features");
13824                pw.println("    k[eysets]: print known keysets");
13825                pw.println("    r[esolvers]: dump intent resolvers");
13826                pw.println("    perm[issions]: dump permissions");
13827                pw.println("    pref[erred]: print preferred package settings");
13828                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
13829                pw.println("    prov[iders]: dump content providers");
13830                pw.println("    p[ackages]: dump installed packages");
13831                pw.println("    s[hared-users]: dump shared user IDs");
13832                pw.println("    m[essages]: print collected runtime messages");
13833                pw.println("    v[erifiers]: print package verifier info");
13834                pw.println("    version: print database version info");
13835                pw.println("    write: write current settings now");
13836                pw.println("    <package.name>: info about given package");
13837                pw.println("    installs: details about install sessions");
13838                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
13839                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
13840                return;
13841            } else if ("--checkin".equals(opt)) {
13842                checkin = true;
13843            } else if ("-f".equals(opt)) {
13844                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
13845            } else {
13846                pw.println("Unknown argument: " + opt + "; use -h for help");
13847            }
13848        }
13849
13850        // Is the caller requesting to dump a particular piece of data?
13851        if (opti < args.length) {
13852            String cmd = args[opti];
13853            opti++;
13854            // Is this a package name?
13855            if ("android".equals(cmd) || cmd.contains(".")) {
13856                packageName = cmd;
13857                // When dumping a single package, we always dump all of its
13858                // filter information since the amount of data will be reasonable.
13859                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
13860            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
13861                dumpState.setDump(DumpState.DUMP_LIBS);
13862            } else if ("f".equals(cmd) || "features".equals(cmd)) {
13863                dumpState.setDump(DumpState.DUMP_FEATURES);
13864            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
13865                dumpState.setDump(DumpState.DUMP_RESOLVERS);
13866            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
13867                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
13868            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
13869                dumpState.setDump(DumpState.DUMP_PREFERRED);
13870            } else if ("preferred-xml".equals(cmd)) {
13871                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
13872                if (opti < args.length && "--full".equals(args[opti])) {
13873                    fullPreferred = true;
13874                    opti++;
13875                }
13876            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
13877                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
13878            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
13879                dumpState.setDump(DumpState.DUMP_PACKAGES);
13880            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
13881                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
13882            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
13883                dumpState.setDump(DumpState.DUMP_PROVIDERS);
13884            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
13885                dumpState.setDump(DumpState.DUMP_MESSAGES);
13886            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
13887                dumpState.setDump(DumpState.DUMP_VERIFIERS);
13888            } else if ("i".equals(cmd) || "ifv".equals(cmd)
13889                    || "intent-filter-verifiers".equals(cmd)) {
13890                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
13891            } else if ("version".equals(cmd)) {
13892                dumpState.setDump(DumpState.DUMP_VERSION);
13893            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
13894                dumpState.setDump(DumpState.DUMP_KEYSETS);
13895            } else if ("installs".equals(cmd)) {
13896                dumpState.setDump(DumpState.DUMP_INSTALLS);
13897            } else if ("write".equals(cmd)) {
13898                synchronized (mPackages) {
13899                    mSettings.writeLPr();
13900                    pw.println("Settings written.");
13901                    return;
13902                }
13903            }
13904        }
13905
13906        if (checkin) {
13907            pw.println("vers,1");
13908        }
13909
13910        // reader
13911        synchronized (mPackages) {
13912            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
13913                if (!checkin) {
13914                    if (dumpState.onTitlePrinted())
13915                        pw.println();
13916                    pw.println("Database versions:");
13917                    pw.print("  SDK Version:");
13918                    pw.print(" internal=");
13919                    pw.print(mSettings.mInternalSdkPlatform);
13920                    pw.print(" external=");
13921                    pw.println(mSettings.mExternalSdkPlatform);
13922                    pw.print("  DB Version:");
13923                    pw.print(" internal=");
13924                    pw.print(mSettings.mInternalDatabaseVersion);
13925                    pw.print(" external=");
13926                    pw.println(mSettings.mExternalDatabaseVersion);
13927                }
13928            }
13929
13930            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
13931                if (!checkin) {
13932                    if (dumpState.onTitlePrinted())
13933                        pw.println();
13934                    pw.println("Verifiers:");
13935                    pw.print("  Required: ");
13936                    pw.print(mRequiredVerifierPackage);
13937                    pw.print(" (uid=");
13938                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
13939                    pw.println(")");
13940                } else if (mRequiredVerifierPackage != null) {
13941                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
13942                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
13943                }
13944            }
13945
13946            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
13947                    packageName == null) {
13948                if (mIntentFilterVerifierComponent != null) {
13949                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
13950                    if (!checkin) {
13951                        if (dumpState.onTitlePrinted())
13952                            pw.println();
13953                        pw.println("Intent Filter Verifier:");
13954                        pw.print("  Using: ");
13955                        pw.print(verifierPackageName);
13956                        pw.print(" (uid=");
13957                        pw.print(getPackageUid(verifierPackageName, 0));
13958                        pw.println(")");
13959                    } else if (verifierPackageName != null) {
13960                        pw.print("ifv,"); pw.print(verifierPackageName);
13961                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
13962                    }
13963                } else {
13964                    pw.println();
13965                    pw.println("No Intent Filter Verifier available!");
13966                }
13967            }
13968
13969            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
13970                boolean printedHeader = false;
13971                final Iterator<String> it = mSharedLibraries.keySet().iterator();
13972                while (it.hasNext()) {
13973                    String name = it.next();
13974                    SharedLibraryEntry ent = mSharedLibraries.get(name);
13975                    if (!checkin) {
13976                        if (!printedHeader) {
13977                            if (dumpState.onTitlePrinted())
13978                                pw.println();
13979                            pw.println("Libraries:");
13980                            printedHeader = true;
13981                        }
13982                        pw.print("  ");
13983                    } else {
13984                        pw.print("lib,");
13985                    }
13986                    pw.print(name);
13987                    if (!checkin) {
13988                        pw.print(" -> ");
13989                    }
13990                    if (ent.path != null) {
13991                        if (!checkin) {
13992                            pw.print("(jar) ");
13993                            pw.print(ent.path);
13994                        } else {
13995                            pw.print(",jar,");
13996                            pw.print(ent.path);
13997                        }
13998                    } else {
13999                        if (!checkin) {
14000                            pw.print("(apk) ");
14001                            pw.print(ent.apk);
14002                        } else {
14003                            pw.print(",apk,");
14004                            pw.print(ent.apk);
14005                        }
14006                    }
14007                    pw.println();
14008                }
14009            }
14010
14011            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14012                if (dumpState.onTitlePrinted())
14013                    pw.println();
14014                if (!checkin) {
14015                    pw.println("Features:");
14016                }
14017                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14018                while (it.hasNext()) {
14019                    String name = it.next();
14020                    if (!checkin) {
14021                        pw.print("  ");
14022                    } else {
14023                        pw.print("feat,");
14024                    }
14025                    pw.println(name);
14026                }
14027            }
14028
14029            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14030                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14031                        : "Activity Resolver Table:", "  ", packageName,
14032                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14033                    dumpState.setTitlePrinted(true);
14034                }
14035                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14036                        : "Receiver Resolver Table:", "  ", packageName,
14037                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14038                    dumpState.setTitlePrinted(true);
14039                }
14040                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14041                        : "Service Resolver Table:", "  ", packageName,
14042                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14043                    dumpState.setTitlePrinted(true);
14044                }
14045                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14046                        : "Provider Resolver Table:", "  ", packageName,
14047                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14048                    dumpState.setTitlePrinted(true);
14049                }
14050            }
14051
14052            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14053                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14054                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14055                    int user = mSettings.mPreferredActivities.keyAt(i);
14056                    if (pir.dump(pw,
14057                            dumpState.getTitlePrinted()
14058                                ? "\nPreferred Activities User " + user + ":"
14059                                : "Preferred Activities User " + user + ":", "  ",
14060                            packageName, true, false)) {
14061                        dumpState.setTitlePrinted(true);
14062                    }
14063                }
14064            }
14065
14066            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14067                pw.flush();
14068                FileOutputStream fout = new FileOutputStream(fd);
14069                BufferedOutputStream str = new BufferedOutputStream(fout);
14070                XmlSerializer serializer = new FastXmlSerializer();
14071                try {
14072                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14073                    serializer.startDocument(null, true);
14074                    serializer.setFeature(
14075                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14076                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14077                    serializer.endDocument();
14078                    serializer.flush();
14079                } catch (IllegalArgumentException e) {
14080                    pw.println("Failed writing: " + e);
14081                } catch (IllegalStateException e) {
14082                    pw.println("Failed writing: " + e);
14083                } catch (IOException e) {
14084                    pw.println("Failed writing: " + e);
14085                }
14086            }
14087
14088            if (!checkin
14089                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
14090                    && packageName == null) {
14091                pw.println();
14092                int count = mSettings.mPackages.size();
14093                if (count == 0) {
14094                    pw.println("No domain preferred apps!");
14095                    pw.println();
14096                } else {
14097                    final String prefix = "  ";
14098                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
14099                    if (allPackageSettings.size() == 0) {
14100                        pw.println("No domain preferred apps!");
14101                        pw.println();
14102                    } else {
14103                        pw.println("Domain preferred apps status:");
14104                        pw.println();
14105                        count = 0;
14106                        for (PackageSetting ps : allPackageSettings) {
14107                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14108                            if (ivi == null || ivi.getPackageName() == null) continue;
14109                            pw.println(prefix + "Package Name: " + ivi.getPackageName());
14110                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
14111                            pw.println(prefix + "Status: " + ivi.getStatusString());
14112                            pw.println();
14113                            count++;
14114                        }
14115                        if (count == 0) {
14116                            pw.println(prefix + "No domain preferred app status!");
14117                            pw.println();
14118                        }
14119                        for (int userId : sUserManager.getUserIds()) {
14120                            pw.println("Domain preferred apps for User " + userId + ":");
14121                            pw.println();
14122                            count = 0;
14123                            for (PackageSetting ps : allPackageSettings) {
14124                                IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14125                                if (ivi == null || ivi.getPackageName() == null) {
14126                                    continue;
14127                                }
14128                                final int status = ps.getDomainVerificationStatusForUser(userId);
14129                                if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
14130                                    continue;
14131                                }
14132                                pw.println(prefix + "Package Name: " + ivi.getPackageName());
14133                                pw.println(prefix + "Domains: " + ivi.getDomainsString());
14134                                String statusStr = IntentFilterVerificationInfo.
14135                                        getStatusStringFromValue(status);
14136                                pw.println(prefix + "Status: " + statusStr);
14137                                pw.println();
14138                                count++;
14139                            }
14140                            if (count == 0) {
14141                                pw.println(prefix + "No domain preferred apps!");
14142                                pw.println();
14143                            }
14144                        }
14145                    }
14146                }
14147            }
14148
14149            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
14150                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
14151                if (packageName == null) {
14152                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
14153                        if (iperm == 0) {
14154                            if (dumpState.onTitlePrinted())
14155                                pw.println();
14156                            pw.println("AppOp Permissions:");
14157                        }
14158                        pw.print("  AppOp Permission ");
14159                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
14160                        pw.println(":");
14161                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
14162                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
14163                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
14164                        }
14165                    }
14166                }
14167            }
14168
14169            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
14170                boolean printedSomething = false;
14171                for (PackageParser.Provider p : mProviders.mProviders.values()) {
14172                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14173                        continue;
14174                    }
14175                    if (!printedSomething) {
14176                        if (dumpState.onTitlePrinted())
14177                            pw.println();
14178                        pw.println("Registered ContentProviders:");
14179                        printedSomething = true;
14180                    }
14181                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
14182                    pw.print("    "); pw.println(p.toString());
14183                }
14184                printedSomething = false;
14185                for (Map.Entry<String, PackageParser.Provider> entry :
14186                        mProvidersByAuthority.entrySet()) {
14187                    PackageParser.Provider p = entry.getValue();
14188                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14189                        continue;
14190                    }
14191                    if (!printedSomething) {
14192                        if (dumpState.onTitlePrinted())
14193                            pw.println();
14194                        pw.println("ContentProvider Authorities:");
14195                        printedSomething = true;
14196                    }
14197                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
14198                    pw.print("    "); pw.println(p.toString());
14199                    if (p.info != null && p.info.applicationInfo != null) {
14200                        final String appInfo = p.info.applicationInfo.toString();
14201                        pw.print("      applicationInfo="); pw.println(appInfo);
14202                    }
14203                }
14204            }
14205
14206            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
14207                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
14208            }
14209
14210            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
14211                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
14212            }
14213
14214            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
14215                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin);
14216            }
14217
14218            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
14219                // XXX should handle packageName != null by dumping only install data that
14220                // the given package is involved with.
14221                if (dumpState.onTitlePrinted()) pw.println();
14222                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
14223            }
14224
14225            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
14226                if (dumpState.onTitlePrinted()) pw.println();
14227                mSettings.dumpReadMessagesLPr(pw, dumpState);
14228
14229                pw.println();
14230                pw.println("Package warning messages:");
14231                BufferedReader in = null;
14232                String line = null;
14233                try {
14234                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14235                    while ((line = in.readLine()) != null) {
14236                        if (line.contains("ignored: updated version")) continue;
14237                        pw.println(line);
14238                    }
14239                } catch (IOException ignored) {
14240                } finally {
14241                    IoUtils.closeQuietly(in);
14242                }
14243            }
14244
14245            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
14246                BufferedReader in = null;
14247                String line = null;
14248                try {
14249                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14250                    while ((line = in.readLine()) != null) {
14251                        if (line.contains("ignored: updated version")) continue;
14252                        pw.print("msg,");
14253                        pw.println(line);
14254                    }
14255                } catch (IOException ignored) {
14256                } finally {
14257                    IoUtils.closeQuietly(in);
14258                }
14259            }
14260        }
14261    }
14262
14263    // ------- apps on sdcard specific code -------
14264    static final boolean DEBUG_SD_INSTALL = false;
14265
14266    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
14267
14268    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
14269
14270    private boolean mMediaMounted = false;
14271
14272    static String getEncryptKey() {
14273        try {
14274            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
14275                    SD_ENCRYPTION_KEYSTORE_NAME);
14276            if (sdEncKey == null) {
14277                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
14278                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
14279                if (sdEncKey == null) {
14280                    Slog.e(TAG, "Failed to create encryption keys");
14281                    return null;
14282                }
14283            }
14284            return sdEncKey;
14285        } catch (NoSuchAlgorithmException nsae) {
14286            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
14287            return null;
14288        } catch (IOException ioe) {
14289            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
14290            return null;
14291        }
14292    }
14293
14294    /*
14295     * Update media status on PackageManager.
14296     */
14297    @Override
14298    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
14299        int callingUid = Binder.getCallingUid();
14300        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
14301            throw new SecurityException("Media status can only be updated by the system");
14302        }
14303        // reader; this apparently protects mMediaMounted, but should probably
14304        // be a different lock in that case.
14305        synchronized (mPackages) {
14306            Log.i(TAG, "Updating external media status from "
14307                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
14308                    + (mediaStatus ? "mounted" : "unmounted"));
14309            if (DEBUG_SD_INSTALL)
14310                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
14311                        + ", mMediaMounted=" + mMediaMounted);
14312            if (mediaStatus == mMediaMounted) {
14313                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
14314                        : 0, -1);
14315                mHandler.sendMessage(msg);
14316                return;
14317            }
14318            mMediaMounted = mediaStatus;
14319        }
14320        // Queue up an async operation since the package installation may take a
14321        // little while.
14322        mHandler.post(new Runnable() {
14323            public void run() {
14324                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
14325            }
14326        });
14327    }
14328
14329    /**
14330     * Called by MountService when the initial ASECs to scan are available.
14331     * Should block until all the ASEC containers are finished being scanned.
14332     */
14333    public void scanAvailableAsecs() {
14334        updateExternalMediaStatusInner(true, false, false);
14335        if (mShouldRestoreconData) {
14336            SELinuxMMAC.setRestoreconDone();
14337            mShouldRestoreconData = false;
14338        }
14339    }
14340
14341    /*
14342     * Collect information of applications on external media, map them against
14343     * existing containers and update information based on current mount status.
14344     * Please note that we always have to report status if reportStatus has been
14345     * set to true especially when unloading packages.
14346     */
14347    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
14348            boolean externalStorage) {
14349        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
14350        int[] uidArr = EmptyArray.INT;
14351
14352        final String[] list = PackageHelper.getSecureContainerList();
14353        if (ArrayUtils.isEmpty(list)) {
14354            Log.i(TAG, "No secure containers found");
14355        } else {
14356            // Process list of secure containers and categorize them
14357            // as active or stale based on their package internal state.
14358
14359            // reader
14360            synchronized (mPackages) {
14361                for (String cid : list) {
14362                    // Leave stages untouched for now; installer service owns them
14363                    if (PackageInstallerService.isStageName(cid)) continue;
14364
14365                    if (DEBUG_SD_INSTALL)
14366                        Log.i(TAG, "Processing container " + cid);
14367                    String pkgName = getAsecPackageName(cid);
14368                    if (pkgName == null) {
14369                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
14370                        continue;
14371                    }
14372                    if (DEBUG_SD_INSTALL)
14373                        Log.i(TAG, "Looking for pkg : " + pkgName);
14374
14375                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
14376                    if (ps == null) {
14377                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
14378                        continue;
14379                    }
14380
14381                    /*
14382                     * Skip packages that are not external if we're unmounting
14383                     * external storage.
14384                     */
14385                    if (externalStorage && !isMounted && !isExternal(ps)) {
14386                        continue;
14387                    }
14388
14389                    final AsecInstallArgs args = new AsecInstallArgs(cid,
14390                            getAppDexInstructionSets(ps), ps.isForwardLocked());
14391                    // The package status is changed only if the code path
14392                    // matches between settings and the container id.
14393                    if (ps.codePathString != null
14394                            && ps.codePathString.startsWith(args.getCodePath())) {
14395                        if (DEBUG_SD_INSTALL) {
14396                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
14397                                    + " at code path: " + ps.codePathString);
14398                        }
14399
14400                        // We do have a valid package installed on sdcard
14401                        processCids.put(args, ps.codePathString);
14402                        final int uid = ps.appId;
14403                        if (uid != -1) {
14404                            uidArr = ArrayUtils.appendInt(uidArr, uid);
14405                        }
14406                    } else {
14407                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
14408                                + ps.codePathString);
14409                    }
14410                }
14411            }
14412
14413            Arrays.sort(uidArr);
14414        }
14415
14416        // Process packages with valid entries.
14417        if (isMounted) {
14418            if (DEBUG_SD_INSTALL)
14419                Log.i(TAG, "Loading packages");
14420            loadMediaPackages(processCids, uidArr);
14421            startCleaningPackages();
14422            mInstallerService.onSecureContainersAvailable();
14423        } else {
14424            if (DEBUG_SD_INSTALL)
14425                Log.i(TAG, "Unloading packages");
14426            unloadMediaPackages(processCids, uidArr, reportStatus);
14427        }
14428    }
14429
14430    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14431            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
14432        final int size = infos.size();
14433        final String[] packageNames = new String[size];
14434        final int[] packageUids = new int[size];
14435        for (int i = 0; i < size; i++) {
14436            final ApplicationInfo info = infos.get(i);
14437            packageNames[i] = info.packageName;
14438            packageUids[i] = info.uid;
14439        }
14440        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
14441                finishedReceiver);
14442    }
14443
14444    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14445            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14446        sendResourcesChangedBroadcast(mediaStatus, replacing,
14447                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
14448    }
14449
14450    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14451            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14452        int size = pkgList.length;
14453        if (size > 0) {
14454            // Send broadcasts here
14455            Bundle extras = new Bundle();
14456            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14457            if (uidArr != null) {
14458                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
14459            }
14460            if (replacing) {
14461                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
14462            }
14463            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
14464                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
14465            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
14466        }
14467    }
14468
14469   /*
14470     * Look at potentially valid container ids from processCids If package
14471     * information doesn't match the one on record or package scanning fails,
14472     * the cid is added to list of removeCids. We currently don't delete stale
14473     * containers.
14474     */
14475    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
14476        ArrayList<String> pkgList = new ArrayList<String>();
14477        Set<AsecInstallArgs> keys = processCids.keySet();
14478
14479        for (AsecInstallArgs args : keys) {
14480            String codePath = processCids.get(args);
14481            if (DEBUG_SD_INSTALL)
14482                Log.i(TAG, "Loading container : " + args.cid);
14483            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14484            try {
14485                // Make sure there are no container errors first.
14486                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
14487                    Slog.e(TAG, "Failed to mount cid : " + args.cid
14488                            + " when installing from sdcard");
14489                    continue;
14490                }
14491                // Check code path here.
14492                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
14493                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
14494                            + " does not match one in settings " + codePath);
14495                    continue;
14496                }
14497                // Parse package
14498                int parseFlags = mDefParseFlags;
14499                if (args.isExternalAsec()) {
14500                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
14501                }
14502                if (args.isFwdLocked()) {
14503                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
14504                }
14505
14506                synchronized (mInstallLock) {
14507                    PackageParser.Package pkg = null;
14508                    try {
14509                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
14510                    } catch (PackageManagerException e) {
14511                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
14512                    }
14513                    // Scan the package
14514                    if (pkg != null) {
14515                        /*
14516                         * TODO why is the lock being held? doPostInstall is
14517                         * called in other places without the lock. This needs
14518                         * to be straightened out.
14519                         */
14520                        // writer
14521                        synchronized (mPackages) {
14522                            retCode = PackageManager.INSTALL_SUCCEEDED;
14523                            pkgList.add(pkg.packageName);
14524                            // Post process args
14525                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
14526                                    pkg.applicationInfo.uid);
14527                        }
14528                    } else {
14529                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
14530                    }
14531                }
14532
14533            } finally {
14534                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
14535                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
14536                }
14537            }
14538        }
14539        // writer
14540        synchronized (mPackages) {
14541            // If the platform SDK has changed since the last time we booted,
14542            // we need to re-grant app permission to catch any new ones that
14543            // appear. This is really a hack, and means that apps can in some
14544            // cases get permissions that the user didn't initially explicitly
14545            // allow... it would be nice to have some better way to handle
14546            // this situation.
14547            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
14548            if (regrantPermissions)
14549                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
14550                        + mSdkVersion + "; regranting permissions for external storage");
14551            mSettings.mExternalSdkPlatform = mSdkVersion;
14552
14553            // Make sure group IDs have been assigned, and any permission
14554            // changes in other apps are accounted for
14555            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
14556                    | (regrantPermissions
14557                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
14558                            : 0));
14559
14560            mSettings.updateExternalDatabaseVersion();
14561
14562            // can downgrade to reader
14563            // Persist settings
14564            mSettings.writeLPr();
14565        }
14566        // Send a broadcast to let everyone know we are done processing
14567        if (pkgList.size() > 0) {
14568            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
14569        }
14570    }
14571
14572   /*
14573     * Utility method to unload a list of specified containers
14574     */
14575    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
14576        // Just unmount all valid containers.
14577        for (AsecInstallArgs arg : cidArgs) {
14578            synchronized (mInstallLock) {
14579                arg.doPostDeleteLI(false);
14580           }
14581       }
14582   }
14583
14584    /*
14585     * Unload packages mounted on external media. This involves deleting package
14586     * data from internal structures, sending broadcasts about diabled packages,
14587     * gc'ing to free up references, unmounting all secure containers
14588     * corresponding to packages on external media, and posting a
14589     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
14590     * that we always have to post this message if status has been requested no
14591     * matter what.
14592     */
14593    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
14594            final boolean reportStatus) {
14595        if (DEBUG_SD_INSTALL)
14596            Log.i(TAG, "unloading media packages");
14597        ArrayList<String> pkgList = new ArrayList<String>();
14598        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
14599        final Set<AsecInstallArgs> keys = processCids.keySet();
14600        for (AsecInstallArgs args : keys) {
14601            String pkgName = args.getPackageName();
14602            if (DEBUG_SD_INSTALL)
14603                Log.i(TAG, "Trying to unload pkg : " + pkgName);
14604            // Delete package internally
14605            PackageRemovedInfo outInfo = new PackageRemovedInfo();
14606            synchronized (mInstallLock) {
14607                boolean res = deletePackageLI(pkgName, null, false, null, null,
14608                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
14609                if (res) {
14610                    pkgList.add(pkgName);
14611                } else {
14612                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
14613                    failedList.add(args);
14614                }
14615            }
14616        }
14617
14618        // reader
14619        synchronized (mPackages) {
14620            // We didn't update the settings after removing each package;
14621            // write them now for all packages.
14622            mSettings.writeLPr();
14623        }
14624
14625        // We have to absolutely send UPDATED_MEDIA_STATUS only
14626        // after confirming that all the receivers processed the ordered
14627        // broadcast when packages get disabled, force a gc to clean things up.
14628        // and unload all the containers.
14629        if (pkgList.size() > 0) {
14630            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
14631                    new IIntentReceiver.Stub() {
14632                public void performReceive(Intent intent, int resultCode, String data,
14633                        Bundle extras, boolean ordered, boolean sticky,
14634                        int sendingUser) throws RemoteException {
14635                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
14636                            reportStatus ? 1 : 0, 1, keys);
14637                    mHandler.sendMessage(msg);
14638                }
14639            });
14640        } else {
14641            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
14642                    keys);
14643            mHandler.sendMessage(msg);
14644        }
14645    }
14646
14647    private void loadPrivatePackages(VolumeInfo vol) {
14648        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
14649        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
14650        synchronized (mInstallLock) {
14651        synchronized (mPackages) {
14652            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14653            for (PackageSetting ps : packages) {
14654                final PackageParser.Package pkg;
14655                try {
14656                    pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null);
14657                    loaded.add(pkg.applicationInfo);
14658                } catch (PackageManagerException e) {
14659                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
14660                }
14661            }
14662
14663            // TODO: regrant any permissions that changed based since original install
14664
14665            mSettings.writeLPr();
14666        }
14667        }
14668
14669        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
14670        sendResourcesChangedBroadcast(true, false, loaded, null);
14671    }
14672
14673    private void unloadPrivatePackages(VolumeInfo vol) {
14674        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
14675        synchronized (mInstallLock) {
14676        synchronized (mPackages) {
14677            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14678            for (PackageSetting ps : packages) {
14679                if (ps.pkg == null) continue;
14680
14681                final ApplicationInfo info = ps.pkg.applicationInfo;
14682                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
14683                if (deletePackageLI(ps.name, null, false, null, null,
14684                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
14685                    unloaded.add(info);
14686                } else {
14687                    Slog.w(TAG, "Failed to unload " + ps.codePath);
14688                }
14689            }
14690
14691            mSettings.writeLPr();
14692        }
14693        }
14694
14695        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
14696        sendResourcesChangedBroadcast(false, false, unloaded, null);
14697    }
14698
14699    private void unfreezePackage(String packageName) {
14700        synchronized (mPackages) {
14701            final PackageSetting ps = mSettings.mPackages.get(packageName);
14702            if (ps != null) {
14703                ps.frozen = false;
14704            }
14705        }
14706    }
14707
14708    @Override
14709    public int movePackage(final String packageName, final String volumeUuid) {
14710        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
14711
14712        final int moveId = mNextMoveId.getAndIncrement();
14713        try {
14714            movePackageInternal(packageName, volumeUuid, moveId);
14715        } catch (PackageManagerException e) {
14716            Slog.w(TAG, "Failed to move " + packageName, e);
14717            mMoveCallbacks.notifyStatusChanged(moveId,
14718                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
14719        }
14720        return moveId;
14721    }
14722
14723    private void movePackageInternal(final String packageName, final String volumeUuid,
14724            final int moveId) throws PackageManagerException {
14725        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
14726        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14727        final PackageManager pm = mContext.getPackageManager();
14728
14729        final boolean currentAsec;
14730        final String currentVolumeUuid;
14731        final File codeFile;
14732        final String installerPackageName;
14733        final String packageAbiOverride;
14734        final int appId;
14735        final String seinfo;
14736        final String label;
14737
14738        // reader
14739        synchronized (mPackages) {
14740            final PackageParser.Package pkg = mPackages.get(packageName);
14741            final PackageSetting ps = mSettings.mPackages.get(packageName);
14742            if (pkg == null || ps == null) {
14743                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
14744            }
14745
14746            if (pkg.applicationInfo.isSystemApp()) {
14747                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
14748                        "Cannot move system application");
14749            }
14750
14751            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
14752                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14753                        "Package already moved to " + volumeUuid);
14754            }
14755
14756            final File probe = new File(pkg.codePath);
14757            final File probeOat = new File(probe, "oat");
14758            if (!probe.isDirectory() || !probeOat.isDirectory()) {
14759                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14760                        "Move only supported for modern cluster style installs");
14761            }
14762
14763            if (ps.frozen) {
14764                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
14765                        "Failed to move already frozen package");
14766            }
14767            ps.frozen = true;
14768
14769            currentAsec = pkg.applicationInfo.isForwardLocked()
14770                    || pkg.applicationInfo.isExternalAsec();
14771            currentVolumeUuid = ps.volumeUuid;
14772            codeFile = new File(pkg.codePath);
14773            installerPackageName = ps.installerPackageName;
14774            packageAbiOverride = ps.cpuAbiOverrideString;
14775            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
14776            seinfo = pkg.applicationInfo.seinfo;
14777            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
14778        }
14779
14780        // Now that we're guarded by frozen state, kill app during move
14781        killApplication(packageName, appId, "move pkg");
14782
14783        final Bundle extras = new Bundle();
14784        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
14785        extras.putString(Intent.EXTRA_TITLE, label);
14786        mMoveCallbacks.notifyCreated(moveId, extras);
14787
14788        int installFlags;
14789        final boolean moveCompleteApp;
14790        final File measurePath;
14791
14792        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
14793            installFlags = INSTALL_INTERNAL;
14794            moveCompleteApp = !currentAsec;
14795            measurePath = Environment.getDataAppDirectory(volumeUuid);
14796        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
14797            installFlags = INSTALL_EXTERNAL;
14798            moveCompleteApp = false;
14799            measurePath = storage.getPrimaryPhysicalVolume().getPath();
14800        } else {
14801            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
14802            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
14803                    || !volume.isMountedWritable()) {
14804                unfreezePackage(packageName);
14805                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14806                        "Move location not mounted private volume");
14807            }
14808
14809            Preconditions.checkState(!currentAsec);
14810
14811            installFlags = INSTALL_INTERNAL;
14812            moveCompleteApp = true;
14813            measurePath = Environment.getDataAppDirectory(volumeUuid);
14814        }
14815
14816        final PackageStats stats = new PackageStats(null, -1);
14817        synchronized (mInstaller) {
14818            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
14819                unfreezePackage(packageName);
14820                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14821                        "Failed to measure package size");
14822            }
14823        }
14824
14825        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
14826                + stats.dataSize);
14827
14828        final long startFreeBytes = measurePath.getFreeSpace();
14829        final long sizeBytes;
14830        if (moveCompleteApp) {
14831            sizeBytes = stats.codeSize + stats.dataSize;
14832        } else {
14833            sizeBytes = stats.codeSize;
14834        }
14835
14836        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
14837            unfreezePackage(packageName);
14838            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14839                    "Not enough free space to move");
14840        }
14841
14842        mMoveCallbacks.notifyStatusChanged(moveId, 10);
14843
14844        final CountDownLatch installedLatch = new CountDownLatch(1);
14845        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
14846            @Override
14847            public void onUserActionRequired(Intent intent) throws RemoteException {
14848                throw new IllegalStateException();
14849            }
14850
14851            @Override
14852            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
14853                    Bundle extras) throws RemoteException {
14854                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
14855                        + PackageManager.installStatusToString(returnCode, msg));
14856
14857                installedLatch.countDown();
14858
14859                // Regardless of success or failure of the move operation,
14860                // always unfreeze the package
14861                unfreezePackage(packageName);
14862
14863                final int status = PackageManager.installStatusToPublicStatus(returnCode);
14864                switch (status) {
14865                    case PackageInstaller.STATUS_SUCCESS:
14866                        mMoveCallbacks.notifyStatusChanged(moveId,
14867                                PackageManager.MOVE_SUCCEEDED);
14868                        break;
14869                    case PackageInstaller.STATUS_FAILURE_STORAGE:
14870                        mMoveCallbacks.notifyStatusChanged(moveId,
14871                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
14872                        break;
14873                    default:
14874                        mMoveCallbacks.notifyStatusChanged(moveId,
14875                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
14876                        break;
14877                }
14878            }
14879        };
14880
14881        final MoveInfo move;
14882        if (moveCompleteApp) {
14883            // Kick off a thread to report progress estimates
14884            new Thread() {
14885                @Override
14886                public void run() {
14887                    while (true) {
14888                        try {
14889                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
14890                                break;
14891                            }
14892                        } catch (InterruptedException ignored) {
14893                        }
14894
14895                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
14896                        final int progress = 10 + (int) MathUtils.constrain(
14897                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
14898                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
14899                    }
14900                }
14901            }.start();
14902
14903            final String dataAppName = codeFile.getName();
14904            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
14905                    dataAppName, appId, seinfo);
14906        } else {
14907            move = null;
14908        }
14909
14910        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
14911
14912        final Message msg = mHandler.obtainMessage(INIT_COPY);
14913        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
14914        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
14915                installerPackageName, volumeUuid, null, user, packageAbiOverride);
14916        mHandler.sendMessage(msg);
14917    }
14918
14919    @Override
14920    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
14921        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
14922
14923        final int realMoveId = mNextMoveId.getAndIncrement();
14924        final Bundle extras = new Bundle();
14925        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
14926        mMoveCallbacks.notifyCreated(realMoveId, extras);
14927
14928        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
14929            @Override
14930            public void onCreated(int moveId, Bundle extras) {
14931                // Ignored
14932            }
14933
14934            @Override
14935            public void onStatusChanged(int moveId, int status, long estMillis) {
14936                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
14937            }
14938        };
14939
14940        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14941        storage.setPrimaryStorageUuid(volumeUuid, callback);
14942        return realMoveId;
14943    }
14944
14945    @Override
14946    public int getMoveStatus(int moveId) {
14947        mContext.enforceCallingOrSelfPermission(
14948                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
14949        return mMoveCallbacks.mLastStatus.get(moveId);
14950    }
14951
14952    @Override
14953    public void registerMoveCallback(IPackageMoveObserver callback) {
14954        mContext.enforceCallingOrSelfPermission(
14955                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
14956        mMoveCallbacks.register(callback);
14957    }
14958
14959    @Override
14960    public void unregisterMoveCallback(IPackageMoveObserver callback) {
14961        mContext.enforceCallingOrSelfPermission(
14962                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
14963        mMoveCallbacks.unregister(callback);
14964    }
14965
14966    @Override
14967    public boolean setInstallLocation(int loc) {
14968        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
14969                null);
14970        if (getInstallLocation() == loc) {
14971            return true;
14972        }
14973        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
14974                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
14975            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
14976                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
14977            return true;
14978        }
14979        return false;
14980   }
14981
14982    @Override
14983    public int getInstallLocation() {
14984        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14985                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
14986                PackageHelper.APP_INSTALL_AUTO);
14987    }
14988
14989    /** Called by UserManagerService */
14990    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
14991        mDirtyUsers.remove(userHandle);
14992        mSettings.removeUserLPw(userHandle);
14993        mPendingBroadcasts.remove(userHandle);
14994        if (mInstaller != null) {
14995            // Technically, we shouldn't be doing this with the package lock
14996            // held.  However, this is very rare, and there is already so much
14997            // other disk I/O going on, that we'll let it slide for now.
14998            final StorageManager storage = StorageManager.from(mContext);
14999            final List<VolumeInfo> vols = storage.getVolumes();
15000            for (VolumeInfo vol : vols) {
15001                if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) {
15002                    final String volumeUuid = vol.getFsUuid();
15003                    if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
15004                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
15005                }
15006            }
15007        }
15008        mUserNeedsBadging.delete(userHandle);
15009        removeUnusedPackagesLILPw(userManager, userHandle);
15010    }
15011
15012    /**
15013     * We're removing userHandle and would like to remove any downloaded packages
15014     * that are no longer in use by any other user.
15015     * @param userHandle the user being removed
15016     */
15017    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
15018        final boolean DEBUG_CLEAN_APKS = false;
15019        int [] users = userManager.getUserIdsLPr();
15020        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
15021        while (psit.hasNext()) {
15022            PackageSetting ps = psit.next();
15023            if (ps.pkg == null) {
15024                continue;
15025            }
15026            final String packageName = ps.pkg.packageName;
15027            // Skip over if system app
15028            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15029                continue;
15030            }
15031            if (DEBUG_CLEAN_APKS) {
15032                Slog.i(TAG, "Checking package " + packageName);
15033            }
15034            boolean keep = false;
15035            for (int i = 0; i < users.length; i++) {
15036                if (users[i] != userHandle && ps.getInstalled(users[i])) {
15037                    keep = true;
15038                    if (DEBUG_CLEAN_APKS) {
15039                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
15040                                + users[i]);
15041                    }
15042                    break;
15043                }
15044            }
15045            if (!keep) {
15046                if (DEBUG_CLEAN_APKS) {
15047                    Slog.i(TAG, "  Removing package " + packageName);
15048                }
15049                mHandler.post(new Runnable() {
15050                    public void run() {
15051                        deletePackageX(packageName, userHandle, 0);
15052                    } //end run
15053                });
15054            }
15055        }
15056    }
15057
15058    /** Called by UserManagerService */
15059    void createNewUserLILPw(int userHandle, File path) {
15060        if (mInstaller != null) {
15061            mInstaller.createUserConfig(userHandle);
15062            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
15063        }
15064    }
15065
15066    void newUserCreatedLILPw(int userHandle) {
15067        // Adding a user requires updating runtime permissions for system apps.
15068        updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
15069    }
15070
15071    @Override
15072    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
15073        mContext.enforceCallingOrSelfPermission(
15074                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15075                "Only package verification agents can read the verifier device identity");
15076
15077        synchronized (mPackages) {
15078            return mSettings.getVerifierDeviceIdentityLPw();
15079        }
15080    }
15081
15082    @Override
15083    public void setPermissionEnforced(String permission, boolean enforced) {
15084        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
15085        if (READ_EXTERNAL_STORAGE.equals(permission)) {
15086            synchronized (mPackages) {
15087                if (mSettings.mReadExternalStorageEnforced == null
15088                        || mSettings.mReadExternalStorageEnforced != enforced) {
15089                    mSettings.mReadExternalStorageEnforced = enforced;
15090                    mSettings.writeLPr();
15091                }
15092            }
15093            // kill any non-foreground processes so we restart them and
15094            // grant/revoke the GID.
15095            final IActivityManager am = ActivityManagerNative.getDefault();
15096            if (am != null) {
15097                final long token = Binder.clearCallingIdentity();
15098                try {
15099                    am.killProcessesBelowForeground("setPermissionEnforcement");
15100                } catch (RemoteException e) {
15101                } finally {
15102                    Binder.restoreCallingIdentity(token);
15103                }
15104            }
15105        } else {
15106            throw new IllegalArgumentException("No selective enforcement for " + permission);
15107        }
15108    }
15109
15110    @Override
15111    @Deprecated
15112    public boolean isPermissionEnforced(String permission) {
15113        return true;
15114    }
15115
15116    @Override
15117    public boolean isStorageLow() {
15118        final long token = Binder.clearCallingIdentity();
15119        try {
15120            final DeviceStorageMonitorInternal
15121                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
15122            if (dsm != null) {
15123                return dsm.isMemoryLow();
15124            } else {
15125                return false;
15126            }
15127        } finally {
15128            Binder.restoreCallingIdentity(token);
15129        }
15130    }
15131
15132    @Override
15133    public IPackageInstaller getPackageInstaller() {
15134        return mInstallerService;
15135    }
15136
15137    private boolean userNeedsBadging(int userId) {
15138        int index = mUserNeedsBadging.indexOfKey(userId);
15139        if (index < 0) {
15140            final UserInfo userInfo;
15141            final long token = Binder.clearCallingIdentity();
15142            try {
15143                userInfo = sUserManager.getUserInfo(userId);
15144            } finally {
15145                Binder.restoreCallingIdentity(token);
15146            }
15147            final boolean b;
15148            if (userInfo != null && userInfo.isManagedProfile()) {
15149                b = true;
15150            } else {
15151                b = false;
15152            }
15153            mUserNeedsBadging.put(userId, b);
15154            return b;
15155        }
15156        return mUserNeedsBadging.valueAt(index);
15157    }
15158
15159    @Override
15160    public KeySet getKeySetByAlias(String packageName, String alias) {
15161        if (packageName == null || alias == null) {
15162            return null;
15163        }
15164        synchronized(mPackages) {
15165            final PackageParser.Package pkg = mPackages.get(packageName);
15166            if (pkg == null) {
15167                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15168                throw new IllegalArgumentException("Unknown package: " + packageName);
15169            }
15170            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15171            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
15172        }
15173    }
15174
15175    @Override
15176    public KeySet getSigningKeySet(String packageName) {
15177        if (packageName == null) {
15178            return null;
15179        }
15180        synchronized(mPackages) {
15181            final PackageParser.Package pkg = mPackages.get(packageName);
15182            if (pkg == null) {
15183                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15184                throw new IllegalArgumentException("Unknown package: " + packageName);
15185            }
15186            if (pkg.applicationInfo.uid != Binder.getCallingUid()
15187                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
15188                throw new SecurityException("May not access signing KeySet of other apps.");
15189            }
15190            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15191            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
15192        }
15193    }
15194
15195    @Override
15196    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
15197        if (packageName == null || ks == null) {
15198            return false;
15199        }
15200        synchronized(mPackages) {
15201            final PackageParser.Package pkg = mPackages.get(packageName);
15202            if (pkg == null) {
15203                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15204                throw new IllegalArgumentException("Unknown package: " + packageName);
15205            }
15206            IBinder ksh = ks.getToken();
15207            if (ksh instanceof KeySetHandle) {
15208                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15209                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
15210            }
15211            return false;
15212        }
15213    }
15214
15215    @Override
15216    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
15217        if (packageName == null || ks == null) {
15218            return false;
15219        }
15220        synchronized(mPackages) {
15221            final PackageParser.Package pkg = mPackages.get(packageName);
15222            if (pkg == null) {
15223                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15224                throw new IllegalArgumentException("Unknown package: " + packageName);
15225            }
15226            IBinder ksh = ks.getToken();
15227            if (ksh instanceof KeySetHandle) {
15228                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15229                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
15230            }
15231            return false;
15232        }
15233    }
15234
15235    public void getUsageStatsIfNoPackageUsageInfo() {
15236        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
15237            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
15238            if (usm == null) {
15239                throw new IllegalStateException("UsageStatsManager must be initialized");
15240            }
15241            long now = System.currentTimeMillis();
15242            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
15243            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
15244                String packageName = entry.getKey();
15245                PackageParser.Package pkg = mPackages.get(packageName);
15246                if (pkg == null) {
15247                    continue;
15248                }
15249                UsageStats usage = entry.getValue();
15250                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
15251                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
15252            }
15253        }
15254    }
15255
15256    /**
15257     * Check and throw if the given before/after packages would be considered a
15258     * downgrade.
15259     */
15260    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
15261            throws PackageManagerException {
15262        if (after.versionCode < before.mVersionCode) {
15263            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15264                    "Update version code " + after.versionCode + " is older than current "
15265                    + before.mVersionCode);
15266        } else if (after.versionCode == before.mVersionCode) {
15267            if (after.baseRevisionCode < before.baseRevisionCode) {
15268                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15269                        "Update base revision code " + after.baseRevisionCode
15270                        + " is older than current " + before.baseRevisionCode);
15271            }
15272
15273            if (!ArrayUtils.isEmpty(after.splitNames)) {
15274                for (int i = 0; i < after.splitNames.length; i++) {
15275                    final String splitName = after.splitNames[i];
15276                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
15277                    if (j != -1) {
15278                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
15279                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15280                                    "Update split " + splitName + " revision code "
15281                                    + after.splitRevisionCodes[i] + " is older than current "
15282                                    + before.splitRevisionCodes[j]);
15283                        }
15284                    }
15285                }
15286            }
15287        }
15288    }
15289
15290    private static class MoveCallbacks extends Handler {
15291        private static final int MSG_CREATED = 1;
15292        private static final int MSG_STATUS_CHANGED = 2;
15293
15294        private final RemoteCallbackList<IPackageMoveObserver>
15295                mCallbacks = new RemoteCallbackList<>();
15296
15297        private final SparseIntArray mLastStatus = new SparseIntArray();
15298
15299        public MoveCallbacks(Looper looper) {
15300            super(looper);
15301        }
15302
15303        public void register(IPackageMoveObserver callback) {
15304            mCallbacks.register(callback);
15305        }
15306
15307        public void unregister(IPackageMoveObserver callback) {
15308            mCallbacks.unregister(callback);
15309        }
15310
15311        @Override
15312        public void handleMessage(Message msg) {
15313            final SomeArgs args = (SomeArgs) msg.obj;
15314            final int n = mCallbacks.beginBroadcast();
15315            for (int i = 0; i < n; i++) {
15316                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
15317                try {
15318                    invokeCallback(callback, msg.what, args);
15319                } catch (RemoteException ignored) {
15320                }
15321            }
15322            mCallbacks.finishBroadcast();
15323            args.recycle();
15324        }
15325
15326        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
15327                throws RemoteException {
15328            switch (what) {
15329                case MSG_CREATED: {
15330                    callback.onCreated(args.argi1, (Bundle) args.arg2);
15331                    break;
15332                }
15333                case MSG_STATUS_CHANGED: {
15334                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
15335                    break;
15336                }
15337            }
15338        }
15339
15340        private void notifyCreated(int moveId, Bundle extras) {
15341            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
15342
15343            final SomeArgs args = SomeArgs.obtain();
15344            args.argi1 = moveId;
15345            args.arg2 = extras;
15346            obtainMessage(MSG_CREATED, args).sendToTarget();
15347        }
15348
15349        private void notifyStatusChanged(int moveId, int status) {
15350            notifyStatusChanged(moveId, status, -1);
15351        }
15352
15353        private void notifyStatusChanged(int moveId, int status, long estMillis) {
15354            Slog.v(TAG, "Move " + moveId + " status " + status);
15355
15356            final SomeArgs args = SomeArgs.obtain();
15357            args.argi1 = moveId;
15358            args.argi2 = status;
15359            args.arg3 = estMillis;
15360            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
15361
15362            synchronized (mLastStatus) {
15363                mLastStatus.put(moveId, status);
15364            }
15365        }
15366    }
15367
15368    private final class OnPermissionChangeListeners extends Handler {
15369        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
15370
15371        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
15372                new RemoteCallbackList<>();
15373
15374        public OnPermissionChangeListeners(Looper looper) {
15375            super(looper);
15376        }
15377
15378        @Override
15379        public void handleMessage(Message msg) {
15380            switch (msg.what) {
15381                case MSG_ON_PERMISSIONS_CHANGED: {
15382                    final int uid = msg.arg1;
15383                    handleOnPermissionsChanged(uid);
15384                } break;
15385            }
15386        }
15387
15388        public void addListenerLocked(IOnPermissionsChangeListener listener) {
15389            mPermissionListeners.register(listener);
15390
15391        }
15392
15393        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
15394            mPermissionListeners.unregister(listener);
15395        }
15396
15397        public void onPermissionsChanged(int uid) {
15398            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
15399                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
15400            }
15401        }
15402
15403        private void handleOnPermissionsChanged(int uid) {
15404            final int count = mPermissionListeners.beginBroadcast();
15405            try {
15406                for (int i = 0; i < count; i++) {
15407                    IOnPermissionsChangeListener callback = mPermissionListeners
15408                            .getBroadcastItem(i);
15409                    try {
15410                        callback.onPermissionsChanged(uid);
15411                    } catch (RemoteException e) {
15412                        Log.e(TAG, "Permission listener is dead", e);
15413                    }
15414                }
15415            } finally {
15416                mPermissionListeners.finishBroadcast();
15417            }
15418        }
15419    }
15420}
15421